2

I need to retrieve session variable data inside an ajax call. Here is my try.

$('#update').click(function(){ 
 
 
 var number = $('#num').val();
 var curuser = <?php echo $_SESSION['userName'];?>
 
 if( number != '' && number.length==9 )
 {
 
 $.ajax({
 data:{number:number},
 success:function(data){ 
 
 $('#number_add').val(number); 
 $('#new_data_Modal').modal('show'); 
 } 
 
 });
 }
 
 
 });

Seems like var curuser = <?php echo $_SESSION['userName'];?> prevents opening my model(new_data_Modal) after button(update) click. When I remove that line it works fine(Model is opening as previous).

But alert("<?php echo $_SESSION['userName'];?>") is working and it prints the session variable as well.

Can someone show me where I made the wrong?

asked Aug 6, 2022 at 12:14
1
  • 4
    wrap <?php echo $_SESSION['userName'];?> with quotes, because in your example in result you would have sth like following: var curuser = userNameValue which is not valid code in JS (if it would return string value). Also one suggestion (not really important) consider using let (mutable) and const (immutable) instead var. Commented Aug 6, 2022 at 12:20

2 Answers 2

1

If this is a string you need to wrap the variable in quotes:

var curuser = '<?php echo $_SESSION['userName'];?>';

otherwise, when PHP code is executed you will get a syntax error:

var curuser = John

You can check the source code of the generate HTML to see what is the output.

NOTE: Your javascript code needs to be a PHP file with a PHP extension, it can be your HTML or JavaScript file. You can use JS file as PHP script in script tag <script src="code.php"></script>

answered Aug 6, 2022 at 13:41
Sign up to request clarification or add additional context in comments.

Comments

1

If you're outputting JavaScript values from your php script you should use json_encode, that way any data type will work and there is no risk of your code breaking if you data has a quote or new line in it.

var curuser = <?php echo json_encode($_SESSION['userName']);?>
answered Aug 7, 2022 at 1:50

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.