alapeno
alapeno

Reputation: 2814

Getting json via ajax in a specific format

A javascript function on a webpage requires data in the following format:

// Javascript
var data = [
            {"AKey" : "AVal", "BKey" : "BVal"},
            {"AKey" : "AVal", "BKey" : "BVal"},
            {"AKey" : "AVal", "BKey" : "BVal"}
];

At the moment, this variable is hardcoded in the javascript file and everything works fine. In the second step, I want to improve it by requesting the data from a server via jQuery's ajax functionality instead of using the hardcoded variable, because of course, until now, the data is static.

So I put a text file on my server, it contains:

// textfile on server
[
            {"AKey" : "AVal", "BKey" : "BVal"},
            {"AKey" : "AVal", "BKey" : "BVal"},
            {"AKey" : "AVal", "BKey" : "BVal"}
];

And apart from that, a PHP script. the PHP script sets its content type to application/json and prints the textfile.

In Javascript, i tried something like this:

var jqxhr = $.getJSON("http://www.myserver.com/output.php", function() {
    alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

jqxhr.complete(function(){ alert("second complete"); });

Unfortunately, I only get an "error" alert and the two complete alerts.

So I have two questions:

The only requirement is that I need both a success and an error handler, just a success handler is not enough.

Thank you

Upvotes: 0

Views: 236

Answers (2)

Chamika Sandamal
Chamika Sandamal

Reputation: 24332

you are accessing it through cross domain and it violates Same origin policy.

follow this link to learn how to overcome this.

see my answer on this question $.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers

and your JSON should be in following format.

[
   {"AKey" : "AVal", "BKey" : "BVal"},
   {"AKey" : "AVal","BKey" : "BVal"},
   {"AKey" : "AVal", "BKey" : "BVal"}
];

Upvotes: 1

Matt Fenwick
Matt Fenwick

Reputation: 49115

JSON is a subset of JavaScript. While this

[
            {"AKey" : "AVal". "BKey" : "BVal"},
            {"AKey" : "AVal". "BKey" : "BVal"},
            {"AKey" : "AVal". "BKey" : "BVal"}
];

may be Javascript, the semicolon means it's not JSON. Also, the periods need to be replaced with commas.

Upvotes: 1

Related Questions