Passing PHP variables through jQuery AJAX

I am trying to learn the JQuery AJAX function, but I'm struggling to figure out how to pass PHP variables to my main document.

This is what I have:

<script> var refreshId = setInterval(function() { $.ajax({ url: "test.php", dataType: "json", //the return type data is jsonn success: function(data){ // <--- (data) is in json format $('#testdiv').html(data.test1); $('#testdiv').append(html(data.test2)); //parse the json data } }); }, 1000); </script> 
+4
source share
5 answers

You should use json or xml format and parse it and get the variable.

 <script src="jquery.js"></script> <script> $.ajax({ url: "test.php", dataType: "json", //the return type data is jsonn success: function(data){ // <--- (data) is in json format alert(data.test1); //parse the json data } }); </script> 

on test.php

 <?php $test = array(); $test['test1'] = '1'; $test['test2'] = '2'; $test['test3'] = '3'; echo json_encode($test); //echo nothing after this //not even html 
+5
source

Another approach (with ajax but a hidden field) would be:

 $.ajax({ type: 'POST', url: "test.php", dataType: "json", //the return type data is jsonn success: function(data){ // <--- (data) is in json format $('#testdiv').html('<input type="hidden" value="' + data.test1 + '" />'); } error: ajaxError, dataType: "html" }); 

With this internal form, you can even use your value in the next Postback without passing it directly.

+1
source

use dataType = 'json' in ajax option on index.php

and test.php use json_encode

 $ret_array= array ($test1, $test2 and $test3); echo json_encode($ret_array); 

again on index.php

now if u wants to use it in your * J * S file, then access it by navigating the object or using the getJSON method

and if you want to use this data directly in php use json_decode

 json_decode($ret_array,true); 

References

json_encode
getJSON
json_decode

+1
source

If im really mistaken, this is simple:

 <?php include 'test.php'; ?> 

To include the test.php file in index.php

Then you can call them as if they were the variables specified in index.php, I would do the following to get them in jQuery:

$ ("# test1"), etc.

Update

The problem is that the variables in test.php will change constantly, and then they must be updated on index.php. I set them as 1, 2, and 3 to verify this. - user683526 1 min ago

In this case, set them to a function and return the values.

-1
source

You do not pass them to index.php, but you can add them as content loaded by your ajax as follows:

 $test1 = '1'; $test2 = '2'; $test3 = '3'; echo $test1 . "<br/>" . $test2 . "<br/>" . $test3 . "<br/>"; 
-1
source

All Articles