Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display returned JSON from a jQuery .ajax post

Starting to work on a project that is built completely on JSON data. It is returned like this:

{"location":{"id":10,"contactPhone":"8675309","contactName":"bob","name":"bill smith","zipCode":"90210","state":"California","address1":"104 S. Olive","city":"Temecula","country":"USA"},"success":true}

I am comfortable processing data returned in HTML form (usually tables) by traversing the DOM with the .find and other filtering to find success flags. I have no idea how to do this with JSON - I need to filter to the last object "success" and check if it is true or false. With HTML returned data I do it like this:

submitHandler: function(form) {
    $.ajax({
     //other ajax stuff
      success: function(data) {
        var answer = $(data).find("td:eq(1)").text();
        var message = $(data).find("td:eq(3)").text();
        //console.log(data);
        if (answer == "True") {
          $('#messages').show().html(message);
      } else {
          $('#messages').show().html('Error logging in: ' + message);
      }
    }
  });
  return false;
  }
  1. Even after using this method I don't completely understand what the function(data) means, Ive used data, msg and response without really understanding what the difference between them are.

I am able to post to the webservice and get the returned JSON with this .ajax call

$.fn.serializeObject = function() {....}
submitHandler: function(form){
    var wrapper = {};
    var location = {};
    wrapper.location = $("#newLocation").serializeObject();
        $.ajax({
            type: $(form).attr('method'),
            url: '/web/service/' + 'locationService' + '/' + 'createLocation',
            dataType: 'json',
            async: false,
            data: JSON.stringify(wrapper),
            success: function(msg) {
                    console.log('success' + msg );
                    //need to traverse to success and if true, do something
            },
                    error: function(msg) {
                    console.log('failure' + msg );
                    //need to traverse to success and if false, do something
            }
    });
    return false;
}
  1. How do you filter to the "success" part in a JSON string (string or object?)

  2. What are the correct terms for the key/number pairs (is that even correct) in the JSON string IE "contactPhone":"8675309"

  3. How do you then display the data if "success":"true" - I will work on that myself but if anyone has good method I would appreciate some advice. I would imagine you just appendTo a table somehow?

    I have a lot of questions on JSON, and am trying to word the questions in a general manner so that the help I am given can help someone else, I apologize for the length of this post. I appreciate any help and if requested will shorten/edit this question.

like image 337
Dirty Bird Design Avatar asked May 29 '13 19:05

Dirty Bird Design


People also ask

How do I get JSON response?

json() returns a JSON object of the result (if the result was written in JSON format, if not it raises an error). Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object.

How do I get Ajax response in JSON?

Approach: To solve this problem, we will first consider a JSON file named “capitals. json” and try to get this JSON data as a response using AJAX. Then we will create an HTML file “capitals. html” which contains a table which we will use to populate the data we are getting in response.

How display JSON data in HTML using jQuery?

The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.


2 Answers

msg here is a json formatted object. You can get success value like that:

success: function(msg) {
                    console.log('success' + msg.success );
                    if(msg.success) { //could be wrote: msg.success === true
                        //do some stuff
                    }
            },

"contactPhone":"8675309"

contactPhone is the key, "8675309" is the value. But in your sample, to get "contactPhone" value, you need to first get the location object:

var contactPhoneValue = msg.location.contactPhone;
like image 160
A. Wolff Avatar answered Oct 11 '22 05:10

A. Wolff


JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. http://www.json.org/

Now the code for reading and writing properties of json object is very similar as it is for normal javascript object.

$ajax({
  dataType:'json',
  success:function(data){
        console.log(data['success']);   //returns for whatever will be the value for succes
        //or
        console.log(data.success);   //returns for whatever will be the value for succes
        data.location['contactName'] = "new name";                    
 }
});

Accessing and manipulating javascript and Json object is same.
Here is a very good guide for them:
http://www.dyn-web.com/tutorials/obj_lit.php



UPDATED:
A better version, maybe this could help:
http://jsfiddle.net/hvzcg/4/

like image 43
TaLha Khan Avatar answered Oct 11 '22 05:10

TaLha Khan