PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to send php variable to AJAX

 September 08, 2022     ajax, jquery, php     No comments   

Issue

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?


Solution

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 By - jcubic
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing