Reputation: 2925
I am trying to learn the Jquery AJAX function but am struggling to work out how to pass PHP variables into my main document.
This is what I currently 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>
Upvotes: 4
Views: 17921
Reputation: 2498
Another approach (with ajax but 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 that inside of your form you can even use your value in the next Postback without passing it directly.
Upvotes: 1
Reputation: 14318
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
Upvotes: 5
Reputation: 54016
use dataType='json' in ajax option on index.php
and on test.php use json_encode
$ret_array= array ($test1, $test2 and $test3);
echo json_encode($ret_array);
again on index.php
now if u want to use it in your *J*S file then access via object navigation or using getJSON
method
and if u want to use that data directly in php then use json_decode
json_decode($ret_array,true);
json_encode
getJSON
json_decode
Upvotes: 1
Reputation: 9031
Unless im greatly mistaken its as simple as:
<?php
include 'test.php';
?>
To include the test.php file in index.php
Then you can call them as if they were variables set in index.php, i would then do the following to get them into jQuery:
$("#test1") etc...
Update
The problem I have is that the variables in test.php will be changing constantly, and then these need to be updated on index.php. I only set them as 1, 2 and 3 to test it out. – user683526 1 min ago
In that case set them in a function and return the values.
Upvotes: -1
Reputation: 58521
You don't pass them into index.php, but you can add them as content that is loaded by your ajax something like this:
$test1 = '1';
$test2 = '2';
$test3 = '3';
echo $test1 . "<br/>" . $test2 . "<br/>" . $test3 . "<br/>";
Upvotes: -1