JQuery getJSON - ajax parseerror - javascript

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>"}}

Related

Json returns the object as undefined

The similar questions didnt work for me. I have a AJAX GET request. When I show the entire json in the console log it works, but I cant select a single object from it.
My JS
$.ajax({
type: "GET",
url: "http://localhost:8092/api/getdata",
dataType: "json",
success: function (data) {
console.log(data["date"]);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
This code returns undefined but if I only use console.log(data) it shows everything. Not sure what to do from here.
This is the output when I use console.log(data)
{
"date": "04-06-2020",
"id": 4
}
SS when I use console.log(data)
SS when I use console.log(data["id"])
It seems you didn't show us the complete output of console.log(data) in your question, there are square brackets ([ ]) missing around it! According to your console screenshot, you get an array, with one object in it.
So the structure is:
[
{
"date": "04-06-2020",
"id": 4
}
]
Therefore, you need to access the first array element (using [0]) to get the object itself, and from there the property date, like this:
console.log(data[0].date)
(Of course, data[0]["date"] works too, but in my opinion the dot-based property access looks cleaner.)
data["date"] is used for object which has date attribute. But in your response is an array
you need to say data[0]["date"] or data[0].date

Ajax doesn't get to success function. Always error function. It fails to post data to another file

Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.

jQuery AJAX response JSON get child node

i am trying to take the responseJSON from an AJAX call and just extract one element to the variable formDigestValue. I have tried about a dozen ways of trying to return the response, using JSON.parse(), $.parseJSON() and some others, but there are 2 main issues that i cant seem to figure out. I put in a check for if (data.lenght > 0){do something}, response.length, responseJSON, jqXHR, XHR, i cant seem to find the variable that holds the data that would end up sent to success function. I've tried just setting the ajax call to a variable (var y = $.ajax()...) and manipulating it that way.
I just keep reading different articles and trying different ways, but nothing seems to quite get it right and it seems to be fairly simple, but i feel like im just missing something simple on this.
$(document).ready(function () {
var siteURL = "xxx";
var formDigestValue = "";
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(){
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.FormDigestValue;
}
});
...
any advice would be greatly appreciated. For reference, the JSON returned looks like the below. i am trying to figure out if i also need anything extra to get at child nodes, as it looks like it comes back buried a bit (i broke it out with indents just to show the depth):
{
"d":
{
"GetContextWebInformation":
{
"__metadata":
{
"type":"SP.ContextWebInformation"
},
"FormDigestTimeoutSeconds":1800,
"FormDigestValue":"0xADC9732A0652EF933F4dfg1EF9C1B75131456123492CFFB91233261B46F58FD40FF980C475529B663CC654629826ECBACA761558591785D7BA7F3B8C62E2CB72,26 Jun 2015 21:20:10 -0000",
"LibraryVersion":"15.0.4631.1000",
"SiteFullUrl":"http://example.com/",
"SupportedSchemaVersions":
{
"__metadata":
{
"type":"Collection(Edm.String)"
},
"results":["14.0.0.0","15.0.0.0"]
},
"WebFullUrl":"http://www.example.cm"
}
}
}
edit 6/27
Alright, I think between the comment on accessing the child nodes and the rest on passing the argument to success function, ive almost go it. My main thing is, I cannot seem to pass it as an argument. I tried to say it initially, but dont think I write the explanation properly. I tried:
Success: function(responseJSON)...
As well as
Success: function(data)...
But the data never seems to actually enter the function, its null values. I know the json returned, but having issues passing it into success function
Here is a look at firebug when this runs:
Try to add dataType option with json value and don't forget the callback success function take at least one parameter which is the data returned by the server.
jQuery.ajax({
url: siteURL + "/_api/contextinfo",
type: "POST",
dataType: 'json',
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: function(data){
console.log(data);
}
});
Posting from my iPhone, so, it's hard. From the first look, you're not capturing the returned result in success. Try the following.
success: function(responseJSON) {
contextHeaders = $.parseJSON(responseJSON);
if that block of json is what you get returned by $.parseJSON(responseJSON) then you're right, you just need to dig a bit deeper:
contextHeaders = $.parseJSON(responseJSON);
formDigestValue = contextHeaders.d.GetContextWebInformation.FormDigestValue;
hope that helps :)

get json data with jquery

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.

jsonp, just not working.. always error

I have read and read and read.. I am trying to pull a feed I have followed ever last answer i can google. I don't get what the issues are here cause firebug is fine with finding and parsing the darn json.
so try one
var url='http://images.wsu.edu/javascripts/tracking/configs/pick.asp';
$.getJSON(url+'?callback=?', function(data){
alert('true');
$.jtrack({
load_analytics:{account:GAcode},
trackevents:data // this can be hard codded here or set do be feed in like so
});
});
FAIL yet i see it in
so
var url='http://images.wsu.edu/javascripts/tracking/configs/pick.asp';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
jsonp : "callback",
success: function(data){
alert('data');
//data=jQuery.parseJSON(data);
$.jtrack({
load_analytics:{account:GAcode},
trackevents:data // this can be hard codded here or set do be feed in like so
});
},
error: function(e, xhr){
alert('error');
alert(e);
}
});
And again FAIL .. so.. um think error would tell me yet.. nothing.. so.. lets be real and test the output it's self cause sure as hell it finds the url and I'm invoking jsop and and and.. well lets validate the output cause surely that is the issue.
So.. well I don't know.. I have hit every darn thread here from bangkok. One one know what the deal is?
Checkout this link:
JSON Example using Callback
I think the JSON returned needs to put the callback in the returned JSON. In the example above, it's placed at the front like:
CALLBACKVALUE([{"id":"4","name":"FICTION","parentid":"3","getfullname":"BOOKS > FICTION"},{"id":"5","name":"NON-FICTION","parentid":"3","getfullname":"BOOKS > NON-FICTION"})
Just make pick.asp get the value of the callback url parameter (called <some string> from now on), which gets generated by jquery and sent like this pick.asp?callback=<some string> to the server. Then use that value to build your response like this:
<some string>(<your json>);
this alerts "#null"
var url = 'http://images.wsu.edu/javascripts/tracking/configs/pick.asp';
$.getJSON(url + '?callback=?', function(data) {
alert(data[0].element);
});
here is what comes back:
callback([
{
"element":"#null",
"options":{}
},{
"element":"a#hover",
"options":{
"category":"hover",
"label":"function(ele){ return ( ($(ele).attr('title')!='' && typeof($(ele).attr('title')) !=='undefined' ) ? $(ele).attr('title') : $(ele).attr('href') ) }"
}
},{
"element":"a[href$='.jpg'],a[href$='.gif'],a[href$='.png'],a[href$='.ppt'],a[href$='.pdf'],a[href$='.doc'],a[href$='.docx']",
"options":{
"category":"download",
"label":"function(ele){ return ( ($(ele).attr('title')!='' && typeof($(ele).attr('title')) !=='undefined' ) ? $(ele).attr('title') : $(ele).attr('href') ) }"
}
},{
"element":"a:not([href*='mailto('])",
"options":{
"category":"email"
}
},{
"element":"a:not([href*='wsu.edu'])",
"options":{
"category":"outbound"
}
},{
"element":"a[href*='wsu.edu']",
"options":{
"category":"internal",
"noninteraction":"true"
}
}
])
I think the problem is that you are not returning JSONP content - just JSON. You need to prepend the callback parameter to the start of the JSON you are currently serving and also wrap it in parenthesis. e.g. you are currently returning:
[{
"element":"#null",
"options":{}
},
...
]
and you need to be returning:
value_of_callback_param([{
"element":"#null",
"options":{}
},
...
]);
The trailing ; is optional. See this link which describes how it's supposed to work.
In addition I think application/javascript should be used for the content type instead of application/json, since you will be returning valid JavaScript instead of just a JSON object/array. Also, the jQuery docs for the $.ajax function states that the error callback should not called for JSONP requests.

Categories

Resources