6

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!

1
  • On success, everything is happening on the page the request is done from. Commented Sep 24, 2020 at 10:55

6 Answers 6

14

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.
    }
});
Sign up to request clarification or add additional context in comments.

7 Comments

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.
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'].
what do you mean by JSON-RPC server and what are the benefites of having this?
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: 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.
|
6

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.

2 Comments

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

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.

Comments

3

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.

3 Comments

also, getJSON() is a wrapper around ajax() which specifies dataType: "json"
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: php has json_encode built in after 5.2 on default php installs. see: php.net/manual/en/function.json-encode.php
0

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.

Comments

0

To send some data to the page mentioned under 'url', you can do this using your 'data' section

data: { _token: CSRF_TOKEN, prot_string : request.term, organism : 'homo sapience'} And from the page mentioned under url, these values can be taken as :
$request->get('prot_string'); $request->get('organism');

Comments

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.