0

I am new to JSON and ajax. Basically i am trying to fetch the list of events from mysql database & send them as JSON encoded file back to .ajax() & display those event list from that function. I tried different ways but i dont think that i am on the right track. As a newbie to Ajax and JSON, Sending and receiving data using ajax is a bit confusing but interesting

The JSON obects and arrays are confusing me that i get stunned without knowing how to access the inner elements

$.ajax({ 
...
...
...
})
.done(function(result)
{
})

Is result an object or array or string ? should i use JSON.parse() method here or should i used the result directly for the processing and display of data?

Here is the input format for my backend php file,

{"data": 
    {
        "dept": "CSE"
    }
}

This input is from a drop-down list,

$("#dept_drop_down").on("change", function() {
...
...
})

And the output format from my php file is,

{
  "data": {
    "status": "success",
    "response_code": "202",
    "events": {
      "1": {
        "name": "Help Dexter",
        "desc": "Help Dexter to Solve the Puzzle",
        "coordinate": "1307",
        "dept": "CSE"
      },
      "2": {
        "name": "Code Hunt",
        "desc": "Lets hunt the CODE ..!!",
        "coordinate": "2145",
        "dept": "CSE"
      }
    }
  }
}

Please Help me with the JavaScript code for sending that input format JSON and receiving output format JSON and displaying them using AJAX(format of input & output given above).

Waiting for your help. Thanks in advance...

here is my code ...

$(document).ready(function(){ 
    $("#dept_drop_down").on("change", function(){ 
        var dat = $(document.getElementById("dept")).serializeJSON();
        var postdata = JSON.stringify(dat); 
        $.ajax({ 
            url: "elist.php", 
            type: "POST", 
            data: postdata, 
            datatype: 'application/json', 
            error: function(xhr,a,b){alert("This is "+xhr.status)}, 
            beforeSend: function(){alert("Sending.......")}, 
            success:function(result){ 
                var obj=result; 
                d=$.parseJSON(result); 
                if(obj.data.resopnse_code==202)
                { 
                    //object processing .. Here is the place i need help
                }
                else if(obj.data.response_code==200)
                { 
                    //object processing .. Here is the place i need help
                } 
                else if(obj.data.response_code==201)
                { 
                    //object processing .. Here is the place i need help
                } 
                else if(obj.data.response_code==400)
                { 
                    //object processing .. Here is the place i need help
                } 
            }    
        });     
    }); 
});
  • 2
    Possible duplicate of [how to parse json data with jquery / javascript?](http://stackoverflow.com/questions/8951810/how-to-parse-json-data-with-jquery-javascript) – Apb Jan 15 '16 at 07:35
  • 1
    You should console.log(response.data) it looks like it sent back a json obj when you console log the response you should be able to access the properties using dot notation – Enjayy Jan 15 '16 at 07:38
  • @Apb no thats not a duplicate .. i know how to parse but my problem is with the usage & working with objects and the arrays ... i just wanted to know whether it is necessary to parse ... – R S Muthu Kumaran Jan 15 '16 at 09:01

2 Answers2

1

result is a string. You can make a JSON object out of it with jQuery.parseJSON.

var jsonObj = jQuery.parseJSON( result );

You can access the inner elements with the variable you created (in my sample jsonObj) and the element's name.

Let's say you want the coordinate of the second event in your JSON, you access it with

jsonObj.events.data[1].coordinate

That's:

  • jsonObj: access the main JSON object
  • data: access the data element in jsonObj
  • events: access events in data
  • 1: access 1 element in events element
  • coordinate: access coordinate in the second event element

That would return string "1307"

Overall, Ajax isn't that difficult when you get it and you seem to have a good grasp on it already.

Here's a playground for this: http://codepen.io/anon/pen/WrZQrj

Pekka
  • 71
  • 5
0

Well it all depends what you PHP script returns to the call as Content-Type. For example, let's say we got a json.json file which contains your object text above, I can write the PHP script like this:

<?php

$content =file_get_contents ('json.json') ;
echo $content ; // I echo a string here
die ;

The Ajax call will receive a text string, because the call defaults to text/plain Content-Type

$.post ('php.php', {}, function (ret, status) {
    alert (ret) ; // Will alert text
    if ( typeof ret === 'string' )
        ret =JSON.parse (ret) ;
    alert (ret) ; // Will alert [Object] [Object]
    // ret.data.status == 'success'
}) ;

Now, if my PHP script does the following:

<?php

$content =file_get_contents ('json.json') ;
header ('Content-Type: application/json') ;
echo $content ; // I echo a string here still
die ;

It is different. Now I got a JSON object:

$.post ('php.php', {}, function (ret, status) {
    alert (ret) ; // Will alert [Object] [Object]
    if ( typeof ret === 'string' ) // << will not execute anymore
        ret =JSON.parse (ret) ;
    alert (ret) ; // Will alert [Object] [Object]
    // ret.data.status == 'success'
}) ;

I left the if() and JSON.parse() in the second one, but they aren't used anymore in the last case.

One last thing, in the PHP code I echo'ed a string coming from a file, but in case you got an object built by the script, here is the code

$content =(object)[] ;
$content.data =(object)[ "status" => "success" } ;
...
header ('Content-Type: application/json') ;
echo json_encode ($content) ; // I echo a string here
die ;
cyrille
  • 2,616
  • 1
  • 10
  • 18