I've got a simple question, but haven't been able to find the exact solution I need. How can I use a jQuery $.ajax to call a PHP file that just echos two PHP variables, and save them to javascript variables in the response?
1 Answer
you would do something like:
$.getJSON('ajax_responder.php', function(data){
window.var1 = data.var1;
window.var2 = data.var2;
});
and then in ajax_responder.php
<?php
header('Content-type: application/json');
$var1 = 'foo';
$var2 = 'bar';
$data = array(
'var1' => $var1,
'var2' => $var2
);
echo(json_encode($data));
?>
4 Comments
ejfrancis
thanks, this is just what I needed. I'm having a slight problem thought, in the php file I'd like to set $var1 and $var2 to two global vars that I set through a $_GET in a separate PHP file. when I try to access set $var1=$global1 its null, what's the proper way to do this?
DiverseAndRemote.com
if its a global variable try putting
global $global1; somewhere in the code right before you use $global1ejfrancis
this is strange. if i include my ajax_responder.php in my index.php, it echos the correct json formatted data {"var1":"test","var2":"name"}, so I know it's echoing the two variables correctly. but when I try to set window.test = data.var1, in the $.getJson response it comes up null
ejfrancis
nevermind, i got it. the url wasn't being passed the correct variable so it was never being made a global var. thanks for the help!