tags:

views:

240

answers:

5

I have a jquery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success. Do I have to use JSON, and if so, is it possible to integrate it into the $.ajax function after success?

$.ajax({
   type: "POST",
   data: "action=favorite&username=" + username + "&topic_id=" + topic_id + "&token=" + token,
   url: "favorite.php",
   success: function(response)
   {


   }
  });

EDIT I appreciate everyone's help + 1 to all!

A: 

I have never programmed in PHP. In asp.net JSON is the default mode of data exchange in async webservice call , so as a developer I dont have to worry about underlying details of JSON. I guess even jQuery gets its data in JSON format. If in case you have multiple values , you can get them in the form of list or dictionary format.

Pawan Mishra
+2  A: 

You would have to return JSON (or some other data format supported by jQuery's ajax() function) from favorite.php.
edit: it doesn't have to be json, but for multiple return values, it is the easiest to parse. For instance, if you returned xml or html, you'd have to traverse nodes to return a value.

For instance, if you returned:
{"user": "Joe", "success" : "pass", "message" : "favorite added" }

in success, you would use:

function(response){
  var user = response.user;
  var success = response.success; // etc.
}

The important thing to remember is to specify the dataType in your ajax call as json. jQuery also supports the other dataTypes: xml, html, script, jsonp, text

I believe the default is html. And, having written php to return xml with properly formatted headers in the php script, I can tell you that sometimes you have to specify the dataType for jQuery to parse it correctly.

Jim Schubert
+3  A: 

I have a jquery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success.

You can only return one value - a blob of text (in most cases).

You can, however, structure that text, so you can easily extract different bits of data from it.

Do I have to use JSON

No, but it is the simplest option.

, and if so, is it possible to integrate it into the $.ajax function after success?

Umm. Yes. Did you read the manual for the jQuery ajax function? It explicitly mentions using JSON and getting an object as the argument to the success function.

David Dorward
thanks david appreciate it
Scarface
david how could you structure the text, just curious and when is it best to use json
Scarface
@Scarface — as JSON, as XML, as CSV, as whatever format you like.
David Dorward
+3  A: 

It would be a very good idea to use only JSON responses from the server. That way your server backend would act as a JSON-RPC server and the front-end would be completely independent of it! Of course you can use JSON with the $.ajax function. Here's an example:

$.ajax({
    url: 'http://some.url.com/',
    data: 'some=post&data=xyz',
    type: 'POST',
    dataType: 'json',
    success: function(response, statusText) {
        // `response` here is a valid JSON object; jQuery handles the work of parsing the response, etc.
    }
});
themoondothshine
Also, if the response is NOT valid JSON, the function specified in the `error` parameter is called and passed the `xht` object, `statusText` and the `response`. Check jQuery documentation on more details.
themoondothshine
Another point: It is not considered safe to use the `eval()` function for parsing responses directly. Also, instead accessing parameters like `jsonobj.someparameter` it usually considered more safe to do `jsonobj['someparameter']`.
themoondothshine
+3 Excellent posts.
Jim Schubert
what do you mean by JSON-RPC server and what are the benefites of having this?
Scarface
ps I used your suggestion and it worked, I didn't know you could do that without $get.json! What is the difference of this function and the one you suggested?
Scarface
@Scarface: JSON-RPC allows you to pass commands and parameters to the server and get a response. It's very similar to what you're doing, except (as I understand it; I've never used it) it's JSON to the server, and JSON from the server.
Jim Schubert
o ok I will google it
Scarface
@Scarface: @Jim's right about JSON-RPC. If you've used XML-RPC or SOAP interfaces or such (y'know, like the Twitter API), it's the same concept. Except its much more flexible (personal opinion) than XML-RPC. You make POST or GET requests to the server as you would normally do. The server responds in terms of objects instead of say plain-text or plain XML. These objects may even contain executable functions (although, again, that isn't a safe practice). `$get.json` is actually just a wrapper for `$.ajax` with `dataType` set to `json`.
themoondothshine
PS: If you are a PHP guy, you might want to take a look at Zend Framework's implementation of the JSON-RPC server class.
themoondothshine
+3  A: 

Let's say the returned json is something like this

{
  firstName: 'Ricardo',
  lastName: 'Jones',
  errors: 0
}

You can use the jQuery getJSON method as follows:

$.getJSON(
   'favorite.php',
   { 'action': 'favorite', 'username': username, 'topic_id': topic_id, 'token': token },
   function(data) {
     alert(data.firstName);
     alert(data.lastName);
     alert(errors);
   }
)

In the returning function you can get the many variables you want.

rmarimon
also, getJSON() is a wrapper around ajax() which specifies `dataType: "json"`
Jim Schubert
Just curious, I use php, to pass values in json, I am using this big file called json.php which allows me to use '$json->encode($data);' is there a way to encode without using an external document?
Scarface
@Scarface: php has json_encode built in after 5.2 on default php installs. see: http://php.net/manual/en/function.json-encode.php
Jim Schubert
thanks jim it is working lol.
Scarface