views:

182

answers:

1

I'm using the JQuery AJAX function to deliver data to a PHP doc.

Currently, the AJAX success function returns HTML which gets added to the html page.

My goal is for the success function to return a second/different piece of data that can be used as a JavaScript variable.

How can this be done?

Update

The question was answered correctly. Here is an example of the resulting script.

PHP Document

<?php
$some_html = 'foo';
$some_value_for_js_variable = 'bar';

// create json content
echo "{";
echo "\"some_html_outupt\":\"$some_html\",";
echo "\"some_value_for_js_varialbe_output\":\"$some_vale_for_js_variable\"";
echo "}";
?>

JS Document

// Jquery ajax function
$.ajax({
    dataType: 'json',
    type: "POST",
    url: "some_file.php", // the location of the above mentioned php script
    cache: false,
    success: function(json) {
     $(el).html(json['some_html_output']); // add html output to page
     var a = json['some_value_for_js_varialbe_output']; // assign value to js varialbe
        }
    }
}); // ajax
+3  A: 

The way that I would implement this is to return the data in a JSON string with 2 items in it The first part would hold the HTML and the 2nd part holding the data for the variable that you want.

{"html":{html},
"2nd variable":"{data}"}

and then you can do a $.getJSON call to your web server like

$.getJSON('path','querystring=if_needed',function(data){
    var html = data['html'];
    var 2ndVariable = data['2nd Variable']
    //do other things that you want
});

I hope that helps

AutomatedTester