Shade Shade - 1 year ago 55
jQuery Question

Simple JQuery AJax Example: Variables

I took code from the W3 Schools regard jquery ajax and modified it slightly:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("test/test.php");
});
});
</script>
</head>
<body>
<? $a=5; $b=5; $a + $b = $c;?>
<div id="div1"><h2>Let jQuery AJAX Change This Text???</h2></div>
<button>Get External Content</button>

</body>
</html>


On my test.php I have this little line:

<h2>The answer is: <?=$c?></h2>


When I click the button though I am not getting anything, just "The answer is:"

I know this is stupid simple, but I a newb to Jquery AJAX and can't find a solution that answer this question. This is more for my understanding that a real project-based problem.

Thankss

Answer Source

As pointed above, you cannot access the local variables of one page in test.php using jquery load method. If you want to pass the value of $c variable to test.php, you can achieve by passing it as get variable or using ajax.

Please look at the following example:

Your Client side file:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">        </script>
<?php 
$a=5;
$b=5; 
$c = $a + $b;
?>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("test.php?c=<?php echo $c; ?>");
  });
});
</script>
</head>

<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text???</h2></div>
<button>Get External Content</button>

</body>
</html>

And Your Server side file:

<h2>The answer is: <?php echo $_GET['c']; ?></h2>