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

Friday, September 9, 2022

[FIXED] How can I set an ajax variable equal to a php variable?

 September 09, 2022     ajax, php, variables     No comments   

Issue

I'm looking for some guidance on how if I have an already existing php variable, that is not a web element, just a string, how can I pass that as a variable to ajax?

here is a santized snippet of what I'm doing.

I want to be able to pass $my_php_var to ajax.

<?php
$my_php_var = "foo";
?>

$(document).on('click', '#btn_add', function(){
    var my_php_var = $my_php_var;
    $.ajax({
       url:"directory/script.php"),
       method:"POST",
       data:{my_php_var:my_php_var},
       dataType:"text",
       success:function(data);
       {
            alert(data);
       }
    })
    

Solution

What you can do is, print it there inside another PHP tag:

<?php
$my_php_var = "foo";
?>

$(document).on('click', '#btn_add', function(){
    $.ajax({
       url:"directory/script.php"),
       method:"POST",
       data:{my_php_var:<?=$my_php_var?>},
       dataType:"text",
       success:function(data);
       {
            alert(data);
       }
    })

Where <?=$var?> is short version of <?php echo $var; ?>.



Answered By - Amir MB
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • 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