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.
Related
I have the following code.
$(".likeBack").on("click", function(){
var user = $(this).attr("user");
var theLikeBack = $(this).closest(".name-area").find(".theLikeBack");
$.ajax({
type: "POST",
dataType: "json",
url: "processes/rewind-knock.php",
data: "user="+user+"&type=likeback",
success: function(json){
alert("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown){
alert("XHR: " + jqXHR + " | Text Status: " + textStatus + " | Error Thrown: " + errorThrown);
}
});
});
Here, everything is functional. Network tab shows request and response well received as required. However, the success part is not getting executed. I tried adding beforeSend and complete and both are getting executed but success part (nothing inside the success blog is getting executed). I don't understand the reason why.
UPDATE
Add error part. It returns:
XHR: [object Object] | Text Status: parsererror | Error Thrown: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
UPDATE 2
Screenshot
give data in ajax like this and check,
data : {'user':user,'type':'likeback'},
In your Php code when you return the data, place all data in a array then use this,
echo json_encode($arr); //return the array in json form
now in your success function use
console.log(JSON.parse(json));
hope may help you. Thank you
I have the following view in django:
def update_card(request):
return HttpResponse(status=400, message="You cannot call this method").
And in jquery:
$.ajax({
url: "{% url 'update_card' %}",
type: 'POST',
success: function(data){
console.log('OK!')
},
error: function(err){
var response_message = err.responseText;
alert(err.responseText)
}
});
But for whatever reason, this is triggering the success method unless I do something like raise Exception(200, "You cannot call this method"). Why? Am I not allowed to return a HttpResponse object to jquery?
There are many types of responses that you can send. Also, you don't need to send status codes.
HttpResponseBadRequest('error message') // status code 400
HttpResponseServerError("error message") // status code 500
raise SuspiciousOperation('error message') // exception
raise Exception('error message') // Status code 500
Your javascript code will remain the same. Thanks
You have it in the reverse order. It needs to be:
return HttpResponse("You cannot call this method", status=400)
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.
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/
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);
}
});
}