The jQuery.ajax() function I use works correctly most of the time. However sometimes it is not returning any data. Instead the error() function is called.
$.ajax({
[...]
, error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
I can see in there that in those cases textStatus is 'error' and errorThrown is '' (empty).
The jQuery documentation just lists the possible values of textStatus ("timeout", "error", "abort", and "parsererror"). However it does not describe, what 'error' means.
jqXHR returns an object but it does not seam to reveal any additional insights.
How can I investigate what the source to this issue is?
Found out it happens, whenever Reload is pressed in the browser, while the ajax request was still running.
This post helped me implement a solution.
I would suggest you to use fiddler to monitor the request and analyze what you are getting in response.
Another thing to try is to compose your ajax request in fiddler composer. This way you can figure out whether your are passing all required headers or not.
You will find more details in fiddler.
As KidA said in the comment try this:
console.log(jqXHR.status);
Also, just make sure you are pulling from the right destination (url, listname, etc.) along with the proper data type pull (POST, GET, UPDATE, DELETE, etc.)
Related
So I've been working on getting the .POST method for AJAX to run for a local host program.
The idea is that a user clicks on a row in a table, the col[0] of that row, which corresponds to a ID, gets saved and sent to database to retrieve the rest of the data associated with that ID. The clicking works, the ID does get saved as 'alias', but the POST always fails.
I've tried different datatypes, JSON.stringifying the data, adding content-type, and nothing has worked. I have a feeling something is wrong with my URL, but I'm just not familiar enough with this stuff to know what. Before, I was using 'http://localhost:5000/GetTestPoint.php' but that threw an invalid syntax error, so I used the IP address instead. This got rid of the syntax error, but POST still fails and I think I would have to change the IP address every time the program is run on a different computer, so I don't think that is a long term solution either. Also as a side note we don't have internet access on the work pcs so any solutions that would require that are not possible, unless the only solution is to add another package or something.
A few things to note:
alias looks like this : 420060300100
Also, for the console.log results:
jqXHR.status returns 0.
textStatus returns error.
and errorThrown returns
{"notifyType":"consoleItemLog","message":{"message":"","styles":"","hasFormatString":true,"filURL":"http://localhost:5000/TestPoints","lineNumber":37832, "columnNumber":21}}
To be honest I have no clue what the errorThrown response means, it just seems to be backend code? The line # is the line of console.log(errorThrown) but that's about the extent of I understand from it.
So my main questions are, would there be any reason that .POST doesn't work for localhost? Is my syntax correct? Is there something wrong with my url? Any help would be appreciated!!
$.ajax({
type: "POST",
url: "10.20.100.91:5000/TestPoint.php",
data: alias,
dataType: 'text'
})
.done(function() {
alert("success"); })
.fail(function( jqXHR, TextStatus, errorThrown ){
alert("failed");
console.log(jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
})
GetTestPoints.php
<?
echo $_POST["alias];
?>
There's barely anything in there, I just wanted to confirm .POST would work before I added more code to it.
I am using a Jquery $.post request to get a JSON response that is generated by PHP. When the request is complete, a success or error message is displayed. During development however, I sometimes have PHP errors which end up being returned instead of the JSON. When this happens, I just get the error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The code I have now looks like this:
var request = $.post(url, data, null, "json");
request.fail(on_failure);
var on_failure = function(jqXHR, text_status, error_thrown)
{
$("#text_status").empty().append(error_thrown);
};
I would like to be able to show the PHP error if one is returned rather than just indicate that there is a PHP error (just to speed up debugging). Obviously, if a non-JSON parsing error such as HTTP 404 occurs, I still want to display that. I found a method here that indicates that I can detect this error with something like this
$.ajaxSetup({
error: function(jqXHR, exception) {
if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
}
}
});
But it doesn't seem like that helps me because it runs for every request rather than individual requests and (as far as I know) it does not allow access to the error message in the returned data.
No sure what version of jquery are you using. Anyway, did you try to remove the json dataType?
var request = $.post(url, data, null);
Doing this jQuery will guess the dataType for you.
I hate to steal mkross1983's credit, but he has not responded to my request to turn his comment into an answer. mkross1983 said:
Have you tried using Firebug under the "Net" tab to see the results of the requests? Sometimes errors can be seen there that can give some clues to the problem
The Firebug "Net" tab has proved to be a valuable debugging tool. This way I can see exactly what request was made and the response sent to it. It even allows me to see the headers and cookies that were sent with the request.
Thank you mkross1983
I'm pretty sure this is a bug in chrome as it doesn't happen in IE 10 and it just started recently, but basically when making an AJAX call to a URL and the user refreshes the browser during the request, all requests to the same url will fail after that. Even if I refresh the browser again, the request fails. The only way I could get around it is by adding a timestamp to make every request unique but this seems like a hack. Am I missing something here?
If you have an aborted request, this will never work again:
$.getJSON("realTimeActivity/GetRealTimeData",
function (result) {
// Do stuff
}
).fail(function (jqXHR, textStatus, errorThrown) {
// No error message comes back
})
Yet this works every time:
$.getJSON("realTimeActivity/GetRealTimeData?u=" + (new Date).getTime(),
function (result) {
// Do stuff
}
).fail(function (jqXHR, textStatus, errorThrown) {
// No error message comes back
})
I could just leave it but I'd like to understand why this is and not need this hack.
It is because of cacheing, and because the URL is the same as it was before, hence why it ignores it. By appending a timestamp, makes the URL different, and each request goes through.
Another option is setting cache to false (with .ajax()) which interestingly enough, simply appends a timestamp for you.
.ajax() docs
$.ajax({
/* ... */
cache: false
});
$.ajax({
type: "POST",
url: "/find",
data: {coupon_name:value},
success: function(response) {
alert("success")
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
What do I "echo" within my PHP page to throw an error? Basically I'm using the ajax function to count the number returned, if <1 it needs to throw an error back to the JS.
The jQuery specification defines .error() as:
A function to be called if the request fails.
A failure HTTP code is one in the 400s or 500s, so a CakePHP equivalent of:
<?php
http_response_code(500);
?>
should trigger it.
That said, I'm not sure that throwing an error is necessarily correct in your circumstances - your query hasn't actually errored, it just has returned zero results. So you may be best handling this within the .success() function anyway.
I suggest you leave the error for the real HTTP-related emergencies, and handle your code logic in your response. The easiest approach is making the response into JSON, returning an error component in the JSON if you encounter an error, and manually checking for its presence.
That said, you can use $this->controller->response->statusCode(400) (in CakePHP) or similar to send a status code that will trigger an error clause. But I recommend against it.
My problem happens to be the error, I am attempting to produce an error, in this case the error being hiding the loading symbol and showing a refresh button in order for the user to reload the page to see if the data loads this time.
$(document).ready(function () {
$('#busy').show();
$(document).bind('deviceready', function () {
var today = $('#todaysong');
$.ajax({
url: 'my url',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
$.each(data, function (i, item) {
var song = '<name>' + item.name + '</name>' + '<artist>' + item.artist + '<br></artist>';
$('#busy').hide();
today.append(song);
});
},
error: function (error) {
$('#busy').fadeOut();
$('#reload').fadeIn();
}
});
});
});
This is my code, could someone advise on what I am doing wrong, I've tried a few things and cannot seem to get it to work, also would I make it so said button was able to refresh this individual piece of code?
Thanks a lot.
In order to debug your code:
Are you generating an error on your own? Is it really an error? Track your request via Firebug or ...
Be sure about running the error function. Again try Firebug or such things to set break points.
Check the JavaScript console for being sure there is no any of damn JavaScript error. And again Firebug error console.
Without seeing other details it is difficult to suggest.
Still I'm trying.. Check the IDs of the elements you have mentioned is same as they are in HTML. Check in HTML that one id is not assigned to more than one element.
In the AJAX code remove jsonp: 'jsoncallback', for a while and test if it is working.
error(jqXHR, textStatus, errorThrown)
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
Where the important part in this case is;
Note: This handler is not called for cross-domain script and JSONP
requests.
Quote from the API documentation of jQuery.ajax.
You should instead be using jsonpCallback.