jQuery how to read this JSON string from responseText - javascript

I have tried almost everyway here on stack overflow, but somehow I cannot read JSON string data returned from a success function call in jquery ajax. my success function receives following JSON string:
Object {
readyState = 4, responseText = "{"
Response ":200,"
Data ":"
6 ","
Message ":"
6 "}", status = 200, statusText: "OK"
}
This is my success callback:
success: function(response, msg, responseText) {
if (response.Response == 200) {
console.log("Data was submitted");
var obj = responseText;
console.log(typeof obj);
} else if (response.Response == 400) {
console.log("there was some error");
}
}
When success function is fired and checks for status code, it executes console.log("Data was submitted"); statement successfully, however, I am not able to access the "Data":"6" key/value pair.
So far I have tried doing this:
var obj = responseText;
console.log(obj.Data);
and
console.log(obj.data[1]);
and numerous other ways, but either it says "undefined" or gives and error. However, when I console.log(obj), in console it shows 'obj'. which means I am getting a JSON object.
Please note that I have also tried:
obj = jQuery.parseJSON(responseText);
which gives me an error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
What to do in this situation? I want to be able to extract the value of a key name "Data": and and assign its value ="6" to a variable.

The first parameter of the success callback is what you need, not the third. The first parameter will represent the body of the response as returned from the server. Also you don't need to be checking for anything different than 200 status code in a success callback. That's what the error callback is designed for because the success callback will never be fired if your server returns 400 status code.
So:
dataType: 'json',
success: function (response) {
console.log("Data was submitted");
console.log(response.Data);
},
error: function() {
console.log("there was some error");
}

The success callback is success: function(data, textStatus, jqXHR )
So the 1st, data will contain the data returned to the success function.

Related

.done not fired on ajax call

I have a function that makes a ajax call. The .done doesn't seems to be firing. I checked for the error on my console. It says
function getIncidentInfo() {
$.ajax({
type: "GET",
url: "../../page_components/statsboard/stats.php",
data: $(this).serialize(),
dataType: "json",
}).done(function(response) {
incidentAr = response;
for (var i in incidentAr) {
var zaNorth = parseInt(incidentAr[i].zaNorth);
......
}
}).fail(function(xhr, status, error) {
console.log("Status: " + status + " Error: " + error);
console.log(xhr);
});
}
I asked my friend to try the same piece of code and it works.
The script in stats.php is throwing an XDebug error and is returning HTML describing the error instead of the JSON you are expecting. Loading the stats.php page in a browser, or check your PHP logs to find out what the error is.
Check .always(response) instead of .done(response). Some services return non 200 codes with a response body to describe the error.
Check response.responseJSON, response.responseText, and response.responseXML. You may have to state response.responseJSON = eval(respaonse.responseText).
However, I see that the responseText is of HTML type, so my guess (and I say this because you're getting a 200 status and not a 404 or 500) is that you are getting a more generic server error that is rendering a response from a route you did not intend to query.

Javascript redirect on Ajax success

I have a quiz type application. Each question has two answers with a value of 1 or 2. When the quiz is complete, if they have a score lower than 10, they get redirected to a page.
This is my code for this part.
while (n < numResults) {
increment = minScore + (interval * n);
if (totalScore <= increment) {
if(totalScore <= 10) {
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
})
.done(function( msg ) {
window.location.href("www.page2.html");
});
}
return;
} else {
n++;
}
}
I have a few things I am trying to solve. Firstly, before the redirect, some data (answers and url) is posted to PHP so I can process it. One thing I pass is the current window url. The reason I do this is because the
url has a format like
www.page1.com?a=1&b=2&c=3
In PHP, I parse this url and grab the values.
My first problem is that although the data is successfuly sent to PHP and handled, and returns a response of Success, the done function never seems to fire, therefore no redirect occurs (I put an alert in this function
to ensure it is not firing). In PHP, after I process the data, I do this
var_dump($response); //Outputs Success
return json_encode($response);
The second thing I am trying to work out is the redirect url (page2.html). Within this page, I have a button. This button has a standard link, and then I need to give it some params from the initial url.
So this pages button might be something like
www.externallink.com?a=1&c=2
How can I get the original URLs params into a button on the redirected url?
Thanks
USE below function insted of done:
$.ajax({
method: "POST",
url: "handleData.php",
dataType: "json",
data: { answers: ansArray, page: window.location.href }
success:function(data){
window.location.href("www.page2.html");
});
})
For your 1st part:
Try putting the error function of jQuery ajax call. Sometimes when the return type of result does not match with the expected datatype of ajax call, then result comes in the response of error.
error: function (data, status, e) {
}
For your 2nd part:
Attach click event for the button in the handler and read the current URL query string using window.location.search and then redirect using
window.location = newURL + "extra query params";
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function(data, textStatus, jqXHR) {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) {
alert( "complete" );
});
If you .done() callback never invoked, try to set debuggers or alerts inside .fail() or .complete() callback functions. Check if you have an error during ajax call and at all if the call has complete statement.
Here more information: http://api.jquery.com/jquery.ajax/

Uncaught TypeError: Cannot read property 'results' of undefined

I'm a complete newby to JS. Trying to use SharePoint REST API to display a link list in a footer. Keep getting this error no matter what I do. It is for this line LoadFooterLinks(results.d.results);
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
LoadFooterLinks(results.d.results);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}
A few things:
How do you know you have an "error"?
Is is a Javascript Exception?
WHAT IS the error or Exception?
How do you know the error isn't with your LoadFooterLinks() function?
Most likely your results are NOT what you are expecting. You're obviously:
Successfully making a connection and request
But, you can't be sure what's coming back. It could be:
empty string
null
malformed
Hitting F12 in most browsers will bring up that browser's Developer mode/built-in JS console
My code changes below should help you debug by outputting to the console for you.
Things to NOTE about the code changes:
The difference between:
catching a JavaScript runtime exception/error using try-catch vs.
outputting the string variable arbitrarily named "error" in the failure callback method of the $.ajax object
Print an exception to to the console doesn't require console.err()
If you want to show a string as an error in the console use console.err(), not console.log.
Null is an object, not a datatype or primitive like the other ones in JavaScript. For Example,
boolean
string
undefined
number
New Code
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl +
"/_api/lists/getbytitle('Footer Links')/items/?
$orderby=Display_x0020_on_x0020_Homepage"
;
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (results) {
if (!results) { // should handle null and empty strings
try{
LoadFooterLinks(results.d.results);
}
catch (e){ // catch any JavaScript runtime exception (error)
console.log(e); // print the error to the console
// (hit F12 in most browsers to see
// the console BEFORE you refresh
// the page to run your code)
}
}
else {
var msg = "The 'results' variable is ";
var varType = typeof(results);
if (varType == "object") {
msg += "NULL";
}
else {
msg += varType;
}
}
},
error: function (error) {
// this 'error' variable can be named
// anything you'd like and is a string
// description of the AJAX error.
// This description comes from $.ajax -
// which is part of jQuery (a JS library).
// This "error" is not a native JS
// exception; therefore, you wouldn't
// use a TRY-CATCH. Also, since it's
// only a string, if you want to show it
// as an error in the console, you should
// use `console.err`, not `console.log`.
console.err("Error in getting List: (0)", error);
}
});
}
What you are basically doing is making a request to the "/_api/lists/getbytitle" method.
When that method returns a response, it will do so as an object named "results", as you can see under the "success" callback.
What you are doing afterwards is reading a property called "d" and within "d" you are trying to obtain the value of property called "results".
What the error is saying is that "d" is undefined therefore it cannot retrieve the value of "results" from "d".
I suggest you check what is inside the object "results" of the success callback.
For SharePoint API result, you would need to parse the JSON response to convert it to Javascript object. I've modified your code a bit to make it work in this case.
function GetFooterLinks() {
var url = _spPageContextInfo.siteAbsoluteUrl + "/_api/lists/getbytitle('Footer Links')/items/?$orderby=Display_x0020_on_x0020_Homepage";
$.ajax({
url: url,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: function (response) {
var svcData = JSON.parse(response.data).d.results;
LoadFooterLinks(svcData);
},
error: function (error) {
console.log("Error in getting List: " + listName);
}
});
}

String comparison in javascript fails

Hi i have a problem when comparing two strings. the problem is that when i compare the equality of status variable with "success" string literal it returns False, However when I check the value of the success via alert or console.log I get "success".
when I use status.valueOf() == "success" I get an error which says Can not call method 'valueOf' of undefined but when checking
// this is a callback function used in jQuery.post(url, data, callback)
this.callback = function(data, status, jqXHR) {
alert(status); // shows that status is equal to "success"
console.log("STATUS: " + status);
console.log("STATUS CONSTRUCTOR: " + status.constructor);
console.log("STATUS TYPE: " + (typeof status));
if(status.valueOf() === "success") {
var data = JSON.parse(data);
if(data.errors) {
this.success(data.message);
} else {
this.failure(data.message, data.errors);
}
} else {
alert("WTF");
}
};
UPDATE 2:
This is what i get after logging some attributes of the status:
>>>console.log("STATUS: " + status);
STATUS: success add_poll.js:34
>>>console.log("STATUS CONSTRUCTOR: " + status.constructor);
STATUS CONSTRUCTOR: function String() { [native code] } add_poll.js:35
>>>console.log("STATUS TYPE: " + (typeof status));
STATUS TYPE: string add_poll.js:36
STATUS: undefined add_poll.js:34
Uncaught TypeError: Cannot read property 'constructor' of undefined add_poll.js:35
(callback add_poll.js:35)
(callback add_poll.js:41)
(fire jquery.js:1037)
Can not call method 'valueOf' of undefined
The error message says, valueOf is called on undefined. It means that the status is undefined. So, you might want to drop the valueOf and simply do
if (status === "success") {
A better way of checking might be,
if(status.toLowerCase() === "success")
First check what you server code is returning, if it is ok, try this
if (status === "success")
or you can do this
if (data=== "success")
The method you are using for jQuery ajax is almost deprecated.
As already mentioned in comment, there is no need of using valueOf method with status
So, this should do
$.ajax({
url: 'url2ajax.php',
dataType: 'datatype returned by the url ajaxed maybe json',
data: {//list of key-value pairs to be send },
success: function( oData ) {
//call back to perform on a successful ajax.
//Data returned from ajaxed url available as argument, oData
},
error: function( ojQXhr, strStat, strErr ) {
//callback to perform on a failed ajax request
//jQuery XHR object, status string and error message available as argument
}
});
Refer to jQuery.ajax for details
I finally found the problem. The problem is that I defined the callback function as a property of an object this.callback = function(){...}; I changed it and defined a normal javascript function and it worked. Actually I don't know why? Anyone knows why I can't use an object method as a callback function for $.post(url, data, callback)?

javascript ajax returned value "stolen" in browser console

I've got following javascript code that I execute in the browser:
function run(request) {
var res;
$.ajax({
url:'http://custom-host:8080/',
type: "POST",
async: false,
data: request
}).done(function(data, textStatus, jqXHR){
console.log(textStatus);
res = data;
});
return res;
}
It just asks my custom server for a response that it gets. The Chrome Console log looks like this:
> var a = run({command:'version'}); // executing custom function
success dev.pycached-admin/:14 // this is the console log
undefined // this is the console returned value
> a // ask for value a
"1.1" // value a (returned from ajax)
The question is: how come undefined is returned in the console, when actual value of '1.1' is returned afterwards (the value is correctly assigned)?
If I add debugger statement inside the done function:
}).done(function(data, textStatus, jqXHR){
console.log(textStatus);
debugger;
res = data;
});
then I can see Apple's code which probably maintains the chrome console (VM files in the script tab). Anyway, the AJAX call is synchronous, so why is the value not returned for the first time?
...so why is the value not returned for the first time?
It is, but var is a statement, not an expression, and so it cannot have a result for the console to display. You can see this if you just do this:
> var a = "foo";
undefined
> a
"foo"
So just do this:
> var a
undefined
> a = run({command:'version'});
...which should give you:
success dev.pycached-admin/:14 // this is the console log
"1.1"

Categories