39

I would like to parse JSON array data with jquery ajax with the following code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Sample</title>
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
    var result;
    function jsonparser1() {
        $.ajax({
            type: "GET",
            url: "http://10.211.2.219:8080/SampleWebService/sample.do",
            dataType: "jsonp",
            success: function (xml) {
                alert(xml.data[0].city);
                result = xml.code;
                document.myform.result1.value = result;
            },
        });
    }        
</script>    
</head>
<body>
<p id="details"></p>
<form name="myform">
    <input type="button" name="clickme" value="Click here to show the first name" onclick=jsonparser1() />
    <input type="text" name="result1" readonly="true"/>        
</form>
</body>
</html>

My JSON data is:

{"Data":   [{"Address":"chetpet","FirstName":"arulmani","Id":1,"LastName":"sathish","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"raj","Id":2,"LastName":"nagu","City":"chennai"},{"Address":"ramapuram","FirstName":"ramaraj","Id":3,"LastName":"rajesh","City":"chennai"},{"Address":"ramapuram","FirstName":"yendran","Id":3,"LastName":"sathi","City":"chennai"}],"Code":true}

But i am not getting any output...anybody please help out...

Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
prabu R
  • 2,099
  • 12
  • 32
  • 41
  • 1
    Maybe it's your backend who doesn't return anything. Post it! – Samson Jul 31 '12 at 08:54
  • Use JSON.parse to parse JSON data. in success: function(data) { var result = JSON.parse(data); document...value = result.Code; } – Mifeng Jul 31 '12 at 08:55
  • 1
    **I wrote an answer for this question here: [Loading cross domain html page with jQuery AJAX](http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-jquery-ajax/17299796#17299796)** – _the last one, supports https_ – jherax Jun 26 '14 at 16:26

7 Answers7

91

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
  • **I wrote an answer for this question here: [Loading cross domain html page with jQuery AJAX](http://stackoverflow.com/questions/15005500/loading-cross-domain-html-page-with-jquery-ajax/17299796#17299796)** – _the last one, supports https_ – jherax Jun 26 '14 at 16:01
  • @AbdulMunim: Is it possible to mention the json file in the url property of $.ajax? What are the file extensions supported in url property? is just anything returns with padded js callback? – Mohamed Hussain Oct 19 '15 at 08:38
  • Is that why I get this error: `Uncaught SyntaxError: Unexpected token :` in the console? The error has a link which once I click on shows me the JSON data. – Si8 Jan 26 '17 at 21:28
8

You need to use the ajax-cross-origin plugin: http://www.ajax-cross-origin.com/

Just add the option crossOrigin: true

$.ajax({
    crossOrigin: true,
    url: url,
    success: function(data) {
        console.log(data);
    }
});
Ninioe
  • 520
  • 1
  • 6
  • 6
  • 1
    if I got that right it routes things through a third party proxy. convenient, but traffic through a server might defeat the original idea – FeeJai Jul 31 '16 at 21:45
  • I have added the same but everytime it gives a failed error. I am using jsonp data type. – Mohneesh Agrawal Nov 13 '17 at 10:34
1

Your JSON-data contains the property Data, but you're accessing data. It's case sensitive

function jsonparser1() {
    $.ajax({
        type: "GET",
        url: "http://10.211.2.219:8080/SampleWebService/sample.do",
        dataType: "json",
        success: function (xml) {
            alert(xml.Data[0].City);
            result = xml.Code;
            document.myform.result1.value = result;
        },
    });
}        

EDIT Also City and Code is in the wrong case. (Thanks @Christopher Kenney)

EDIT2 It should also be json, and not jsonp (at least in this case)

UPDATE According to your latest comment, you should read this answer: https://stackoverflow.com/a/11736771/325836 by Abdul Munim

Community
  • 1
  • 1
Yngve B-Nilsen
  • 9,606
  • 2
  • 36
  • 50
  • What happens if you try to browse directly to the URL? – Yngve B-Nilsen Jul 31 '12 at 09:42
  • And what errors do you get in the Error console of your browser? – Yngve B-Nilsen Jul 31 '12 at 09:56
  • Its showing there is unexpected token : in JSON data... but its the correct way of usind the arrays in JSON right??? – prabu R Jul 31 '12 at 10:04
  • @ChristopherKenney : Its showing error if i put datatype as 'json'. Its ok if i put it as 'jsonp'. – prabu R Jul 31 '12 at 10:46
  • Errors if i use json instead of jsonp: 1)XMLHttpRequest cannot load http://10.211.2.219:8080/SampleWebService/sample.do. Origin http://localhost:3555 is not allowed by Access-Control-Allow-Origin. sample.do 2)GET http://10.211.2.219:8080/SampleWebService/sample.do undefined (undefined) – prabu R Jul 31 '12 at 12:40
1

Try

alert(xml.Data[0].City)

Case sensitivly!

Jithin Raj P R
  • 6,667
  • 8
  • 38
  • 69
pirklajos
  • 38
  • 2
0

you need to parse your xml with jquery json parse...i.e

  var parsed_json = $.parseJSON(xml);
Erdem E.
  • 170
  • 1
  • 5
  • 1
    Is that in the success function? Because I get an error in the console: `Uncaught SyntaxError: Unexpected token :` and it displays the error function alert, doesn't even hit the success function. – Si8 Jan 26 '17 at 21:30
0

alert(xml.data[0].city);

use xml.data["Data"][0].city instead

Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176
0

use open public proxy YQL, hosted by Yahoo. Handles XML and HTML

https://gist.github.com/rickdog/d66a03d1e1e5959aa9b68869807791d5

rickdog
  • 748
  • 8
  • 10