3

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
  • 2
    Encode the data as JSON in PHP, send it as response, parse the JSON in JavaScript and use the data as you see fit. Commented Jan 24, 2013 at 21:22

1 Answer 1

6

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));
?>

see http://api.jquery.com/jQuery.getJSON/

Sign up to request clarification or add additional context in comments.

4 Comments

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?
if its a global variable try putting global $global1; somewhere in the code right before you use $global1
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
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.