PHP / JS - How to display an alert () with the value of $ _SESSION

0

Good evening guys! I needed help with the alert (); , I want to display on the index.html page, a alert (); showing that the data was inserted correctly, reading some posts in the forum, gave the idea of the index.php (where it is processed data) save the message in a $ _ SESSION and pull JS from the HTML $ _ SESSION value. I tested the idea and the result was this:

PHP Code:

$_SESSION['registro'] = "Seu gasto foi inserido corretamente!!";
header("location: index.html");

HTML code

<script>alert(".$_SESSION['registro'];.");</script>

Remembering that I tried to change the "" to "", both the $ _SESSION and the alert (); "

The result was:

Doubtis...Whereistheerror?IfyouhavenoerrorwhatotheralternativecanIusetodisplaythisalertaftertheinsertmadebyindex.php?

[RESOLVED]

Ichangedmyindex.htmltoindex.phpthenaddedthefollowinglineofcode:

<script>alert('<?phpsession_start();if($_SESSION['registro']!=null){echo$_SESSION['registro'];}?>');</script>

ImportanttostressthatIwasnotputtingsession_start();

AndonmydatauploadpageIaddedthevalueof$_SESSION

session_start();if($_SESSION['registro']==null){$_SESSION['registro']="Registro cadastro com sucesso !";
           }

           header("location: index.php");
    
asked by anonymous 21.12.2018 / 23:49

3 answers

3

I did not get full knowledge of PHP, but with all that I learned, I can say that the problem lies in the fact that you are trying to get the value in an HTML file, which can not "access" the "objects" of PHP. So you would have to turn that HTML file into PHP, and in case, I think you could do it like this:

<script>alert("<?php echo $_SESSION['registro']; ?>");</script>

[Edited]

Since you are now working with two PHP files, one of which assigns the value and the other accesses the value, you should use session_start() in both, and in the one that accesses the value, you should do the following: / p>
<script>
    alert("<?php echo isset($_SESSION['registro'])?$_SESSION['registro']:null; ?>");
</script>

That is, if $_SESSION['registro'] exists, it puts the value of it, otherwise, the value will be null .

I hope I have helped!

    
21.12.2018 / 23:59
-1

The echo and php tags were missing

<script>
 alert("
   <?php echo $_SESSION['registro']; ?> 
 ");
</script>

Are you running on which server?

    
22.12.2018 / 03:09
-1
<?php if (isset($_SESSION['registro'])) { ?>
    <script>alert('<?= $_SESSION['registro'] ?>');</script>
<?php } ?>
    
22.12.2018 / 03:30