get json data with jquery - javascript

Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)

Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});

try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});

You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});

I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;

In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.

You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.

Related

Intercept and modify JSON string before jQuery.getJSON() does its thing

I use jQuery's getJSON call to rerieve the content from a file called my.json.
Now sometimes the JSON file contains a certain character, that would invalidate the syntax. Unfortunately, it is not in my power to change that.
I thought it would be easy to use the success thing to intercept the JSON string and dix it, before $.getJSON() reads it and fails because the syntax is invalid. Obviously, it's not as easy, as I thought.
I would appreciate, if someone could help me out fixing below code.
$.ajaxSetup({
beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}},
cache: false
});
$.getJSON("my.json", function(data){
// Do something with the JSON
console.log("JSON object: " + data);
}).success(function(data, textStatus, jqXHR) {
// Intercept JSON string and modify it.
var fixed_json = fix_json(jqXHR.responseText);
jqXHR.responseText = fixed_json; // Obviously not as simple as I thought.
});
You can use the success callback of $.ajax() to do the required check on the returned data. It would require you to set the dataType to text though, so that jQuery doesn't try and automatically parse it for you. Try this:
$.ajax({
url: "my.json",
dataType: 'text',
success: function(data) {
var obj;
try {
obj = JSON.parse(data);
}
catch(e) {
obj = fix_json(data);
}
// work with the object here...
})
});
Example fiddle
Depending on the work that fix_json does, and assuming that it always returns an object, you could call that directly and remove the try/catch.

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

Parsing JSON returned via an AJAX POST formating issue

I have a php returning some json in response to a POST request made via an ajax function.
In my php function I format the data like this:
//json return
$return["answers"] = json_encode($result);
echo json_encode($return);
This returns the following string:
answers: "[{"aa":"Purple","0":"Purple","ab":"Blue","1":"Blue","ac":"Red","2":"Red","ad":"Yellow","3":"Yellow"}]"
And this is where I am trying to catch it to use the data:
$.ajax({
type: "POST",
url: "http://ldsmatch.com/pieces/functions/question.functions.php",
dataType : 'JSON',
data: dataString,
success: function(data) {
alert(data.answers[0]["aa"]);
}
});
I've been trying to just alert the data so I can visualize it before setting up the vars I need, but am having some trouble formatting it correctly so it is usable.
If I alert data.answers[0] then it just shows me the first character in the string, which is a bracket [ and if i subsequently change the number it will go through each character in the returned string.
I have tried other variations, such as:
data.answers[0]["aa"] (this returns 'undefined' in the alert)
data.answers["aa"] (this returns 'undefined' in the alert)
data.answers[0] (this returns the first character of the string)
I feel like I'm close, but missing something. Any guidance appreciated.
edit:
thanks for all the suggestions. I removed the second json_encode and was able to parse with data.answers[0].aa
success: function(data) {
var json = $.parseJSON(data);
alert(json.answers[0]["aa"]);
}
Use parseJson like this
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
What if you remove double-encoding on PHP side? You've got an object with JSON string instead of object with first property being object itself, or you may explicitly decode "answers" property on client side as it was suggested above.

java script to json

If I have an array like
price=["1#1000", "1000#2000"]
how to convert it into JSON so that it can be send into ajax call of jQuery
$.ajax({
type: 'POST',
url: '',
data: {
'price': price
},
dataType: 'JSON',
success: function(data) {
console.log("success");
console.log(data);
var products = data.products;
console.log(products);
},
});
Since you already posted...parts of jQuery, here is a jQuery plugin that should do it
http://plugins.jquery.com/plugin-tags/stringify
|EDIT| The jQuery-plugins-site is put down for a while.
Anyways, you a looking for a function called Stringify. You can read more about it here:
http://www.json.org/js.html
A simple google-search should give you plenty results.
When writing price=["1#1000", "1000#2000"] you already have your data represented as a javascript array.
It should be possible for you to simply pass this as an argument as you have described within your use of the $.ajax method.
Alternatively (if you really need to parse price as a json object) see the jQuery builtin function for this: http://api.jquery.com/jQuery.parseJSON/
But recheck that this is not just possible, as you have described it, if not, what errors are you getting?

JQuery getJSON - ajax parseerror

I've tried to parse the following json response with both the JQuery getJSON and ajax:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}]
I've also tried it escaping the "/" characters like this:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview <\/h1><h1>January 29, 2009<\/h1>"}]
When I use the getJSON it dose not execute the callback. So, I tried it with JQuery ajax as follows:
$.ajax({
url: jURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(data){
wId = data.iId;
$("#txtHeading").val(data.heading);
$("#txtBody").val(data.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
},//success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
The ajax hits the error ans alerts the following:
XMLHttpRequest=[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]
textStatus=parseerror
errorThrown=undefined
Then I tried a simple JQuery get call to return the JSON using the following code:
$.get(jURL,function(data){
var json = eval("("+data+");");
wId = json.iId;
$("#txtHeading").val(json.heading);
$("#txtBody").val(json.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
})
The .get returns the JSON, but the eval comes up with errors no matter how I've modified the JSON (content-type header, other variations of the format, etc.)
What I've come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. However, I have hope that I may have missed something that would allow me to get this data via JSON. Does anyone have any ideas?
The JSON string you have is an array with 1 object inside of it, so to access the object you have to access the array first. With a json.php that looks like this:
[
{
"iId": "1",
"heading": "Management Services",
"body": "<h1>Program Overview</h1><h1>January 29, 2009</h1>"
}
]
I just tried this
$.getJSON("json.php", function(json) {
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
I also tried this:
$.get("json.php", function(data){
json = eval(data);
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
And they both worked fine for me.
If anyone is still having problems with this it's because your response needs to be a JSON string and content-type "application/json".
Example for HTTP in asp.net (c#):
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ status: 'success' }");
}
hth,
Matti
Did you try XML-encoding the HTML (i.e. <H1>)?
You could have it return as text and then parse it with the json.org parser
To see if it works any differently
Pleas note that in the question there is a syntax error. The line with
x.overrideMimeType("application/j-son;charset=UTF-8");
should read
x.overrideMimeType("application/json; charset=UTF-8");
This makes a big difference too.
Remove the [], on front and last on JsonData, and it work.
Disabling Firebug Lite fixed this problem for me.
Bug with combination of: jQuery 1.4, ajax/json, Firebug Lite and IE 8
This is a working example and tested!
<script type="text/javascript">
function fetchData() {
var dataurl = "pie.json";
$.ajax({
url: dataurl,
cache: false,
method: 'GET',
dataType: 'json',
success: function(series) {
var data = [];
//alert(series.length);
for (var i=0; i<series.length;i++){
data[i]=series[i];
}
$.plot(
$("#placeholder"),
data,
{
series: {
pie: {
show: true,
label: {
show: true
}
}
},
legend: {
show: true
}
}
);
}
});
//setTimeout(fetchData, 1000);
}
</script>
And the json source is the following (pie.json):
[{ "label": "Series1", "data": 10},
{ "label": "Series2", "data": 30},
{ "label": "Series3", "data": 90},
{ "label": "Series4", "data": 70},
{ "label": "Series5", "data": 80},
{ "label": "Series6", "data": 110}]
First, try to pinpoint if the problem is with general JSON encoding/decoding. try simpler objects, with numbers and plain strings, then with quoted HTML.
After you get JSON working, you really should really consider removing the HTML from there. Much better is to move just data, and leave presentation details to the templates. When using AJAX, that means a hidden template in the HTML, and use jQuery to replicate it and fill with the data. check any of the jQuery template plugins. Of these, jTemplates is a common favorite.
I think you are asking wrong question. Using $.getJSON() is much easier, and if you got problem with it, would be better to ask for $.getJSON() than for $.ajax().
You might also find useful looking at getJSON function source code, because I see, you got a lot of useless stuff there with mimeTypes. That's not the way.
The value you are trying to parse is wrapped in brackets [], which means it is an array. You are trying to eval an array. Try to eval the first element of the array, and it should work...
var json = eval("("+data[0]+");");
Also, I would recommend using the JSON.parse() provided here instead of calling eval() directly.
I received a similar error. Took me a while to find out - little did I know that PHP has not (natively) supported JSON since PHP5.2. Critical reminder...
Yesterday at $. Ajax still no mistakes, today is quoted the mistake, some say parsererror jquery version of the problem, what I use is jquery-1.3.2.min.js, yesterday. This edition also done, today is washed-up. Data sources: no change. Don't know what reason be?
It is maybe because your output buffer is not empty, so AJAX receive bytes which don't belong to the JSON.
Try clean buffer with ob_clean() on server side just before output your json with echo or die(). And you don't need to specify contentType, I think for you default value will work correctly.
I had the same problem and it solve it.
Hope to help you.
in my case, the error was caused by a html tag in the json.
INCORRECT (parsererror)
{"msg": "Gracias,< br >Nos pondremos en contacto."}
CORRECT
{"msg": "Gracias, nos pondremos en contacto."}
BROWSER: IE7/IE8
also try this
$.ajax({
url: url,
data:datas,
success:function(datas, textStatus, jqXHR){
var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};
in my case server responds with unknow character before '{'
Don't use an array box, and make sure you format your data properly:
{"account":{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}}

Categories

Resources