JQuery Ajax response variable from php

I have a simple question, but I could not find the exact solution I need. How can I use jQuery $ .ajax to call a PHP file that simply echoes two PHP variables and stores them in javascript variables in the response?

+3


source to share


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

      

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

+6


source







All Articles