View Full Version : return 2 values in ajax

06-27-2010, 02:50 PM
url: urltoajax,
cache: false,
success: function(html){

above is my current code. In addition to that url I also want to return to another javascript variable - html code retieved from calling a different asp page in ajax.

How can i do this?

07-01-2010, 11:37 AM
Is it JQuery? Prototype? MooTools? Other framework?

As it is not native javascript, it is hard to know what is there...

07-02-2010, 04:20 PM
This is jQuery.

And the answer is you should use JSON: JavaScript Object Notation.

the $.ajax() function in jQuery can take an object literal loaded with all kinds of settings. You have 3 you're using already: url, cache, and success. One of them is called 'dataType' and it allows you to specify the kind of data you're expecting to receive from the server.

//url, cache, success settings, etc.
dataType: "json"

Then you just have to have your server return a string that is JSON. An easy way to do this in PHP is with the json_encode() function. You can create an array of results and then pass them to json_encode() to turn them into JavaScript object literals. If you were getting results from a database you may end up returning a string that looks something like this:

{"name":"Dean", "age":23, "gender":"M", "job":"stamp licker", "department":"collections", "payRate":5.15};

From there in JavaScript you can easily display or manipulate this information.

alert(data["name"]); //Dean
alert(data.age); // 23

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum