How to get callback error to alert in JavaScript? - javascript

I am building app with PhoneGap. It working fine on my PC. But when I installed it as android app it did not work. It fire alert('Oppps...something went wrong').
I have following code...
function getFloors(url, callback){
var data = $.ajax({
type: 'GET',
url: "http://example.com/all_test/get_floors.php"
}).done(callback).error(function(e){
alert('Oppps...something went wrong')
});
return data;
};
Let assume there is no page like http://example.com/all_test/get_floors.php.
Then you can find error in console like GET http://example.com/all_test/get_floorss.php 404 (Not Found).
I need to display that error as alert. I mean I need to print real error instead of alert('Oppps...something went wrong'). So I can find what is issue in mobile.
How should I get that error (what display on the console) for a alert.

Look at this documentation
http://api.jquery.com/jQuery.ajax/#jqXHR
the e on error(function(e) returns a jqXHR object which returns following properties that you can print at your disposal
readyState
responseXML and/or responseText - when the underlying request responded
with xml and/or text, respectively
status
statusText
I think you are trying to find the e.responseText or e.responseXML

Related

$.ajax() returns syntax error: Unexpected end of json input

So I'm working on a website where I have to implement a chat, currently the whole thing is running on localhost.
I'm getting this error:
SyntaxError: Unexpected end of JSON input
and can't figure out why. I have googled a little but can't find an answer, that actually works. I actually did this yesterday, on another computer and that worked super, but today it won't work and I can't figure out why.
Thank you for the great answers.
$(function() {
updateChat("updateChat", null);
$(".chat-form").submit(function(event) {
event.preventDefault();
if ($(".chat-form input").val() != "") {
updateChat("sendMessage", $(".chat-form input").val());
}
});
setInterval(function() {
updateChat("updateChat", null);
}, 3000);
function updateChat(method, message) {
$.ajax({
type: "POST",
url: "action/chat.php",
data: {
function: method,
message: message
},
dataType: "json",
success: function(data) {
console.log(data);
},
error: function (request, status, error) {
console.log(error);
}
})
}
})
Most likely there's an error or warning in your PHP code being displayed, and because you are expecting only json, that causes the syntax error.
There are a few ways to find out what's going on:
open the developer console in your browser and see what the response is the network tab
check your PHP error log
temporarily change your dataType to html and you'll see your console.log(data)
I was getting this error due to my backend php function NOT returning a response as it should have been. It was returning nothing. My parent function that should have been returning the response was calling a child function that WAS returning a response, but the parent function wasn't passing that child return back to the ajax call.
Another possible culprit for these type of errors could be an improper python "shebang" on your back-end (server side) script.
In my particular case I had ajax call to python cgi script via Apache web server and I could not find a more descriptive error message at front-end debug tools. However, Apache logs indicated that the back-end script had problems importing a one of the python scripts because the interpreter did not recognize it. After checking the "shebang" of that back-end script sure enough it had the wrong interpreter specified because I just copied a template file over and forgot to modify it..
So, check your "shebang" at the top of your script to make sure it points to correct interpreter. Example:
For MVC controller you must return a valid JsON
return new JsonResult() { Data = new { test = 123 } };
instead of
return new JsonResult();

ActionResult returns as an error in the ajax call

So, I am trying to return an xml file from my controller:
[HttpGet]
public ActionResult GetXml(int id)
{
var xmlBytes = _context.GetXml(id);
if (xmlBytes == null) return View("NotFound");
return File(new MemoryStream(xmlBytes), "application/xml", "file.xml");
}
This Action is perfectly called from this ajax call:
$.ajax({
type: 'get',
url: url,
success: function(data) {
window.location = url;
},
error: function(error) { //error.responseText contains the actual xml string!
alert("failed to download xml");
}
});
However, instead of calling success, it goes directly to the error property. One interesting thing is that the responseText property from the error object contains the xml that I am looking for.
Could someone explain me what am I doing wrong and point me in the right direction to properly download the xml stream?
Thanks
This is classic issue where the status is 200 and the responseText has the output, but it is an error. Seems strange, but there is a reason for it.
If you were to look at the responseXML you are not going to see the xml document since it can not be parsed by the browser for some reason. Now jQuery auto detects the content type and sees it is XML, it sees the responseXML as null and throws it into the error state. If you log the arguments you will see the error message.
Now to debug this you can either copy the responseText from the console or inspect the response from the network panel. Putting it into your favorite XML validator and see if it picks up the errors. Common issues is the server sticking in hidden characters into the response which chokes the parser or the server returning junk before the xml document.

JQuery AJAX request show AJAX and PHP errors

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

Verify the existence of a twitter account using AJAX/JSON

I am trying to build a simple check that will accept a string and check to see if a twitter account exists by that string.
I have successfully managed to get a positive result, but I can't seem to get a negative one. $.ajax() has an error element, but it is not firing.
Working Example
Code:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(){
alert("username is valid");
},
error: function(){
alert("username is valid");
}
})
}
​
You are using the JSONP transport. In this transport, the requested URL is simply added as a <script> tag in the document. If the URL returns a non-200 status code, the browser won't execute it: that's why you can't see negative responses.
One solution is to use the suppress_response_codes parameter, so that the API always return a 200 status code.
See Things Every Twitter Developer Should Know:
suppress_response_codes: If this parameter is present, all responses will be returned with a 200 OK status code - even errors. This parameter exists to accommodate Flash and JavaScript applications running in browsers that intercept all non-200 responses. If used, it’s then the job of the client to determine error states by parsing the response body. Use with caution, as those error messages may change.
BTW, Twitter is suppressing non-authenticated access to the API, so JSONP access may be suppressed too.
Just a summarize of arnaud576875's answer:
Add a suppress_response_codes=1 parameter
Check for ID returned
So, the result will be something like this:
var testTwit = function(username){
$.ajax({
url: 'http://twitter.com/statuses/user_timeline.json?suppress_response_codes=1&screen_name='+username+'&count=1&callback=?',
dataType: 'json',
success: function(d){
if (d && d.id)
$('span').html('username is valid!');
else
$('span').html('username is not valid.');
}
});
}
Usually API's always returns a response when a request is received. That's why no error is given. You should parse the response coming from the API to find out if a user exists or not.
Errors are not triggered when using JSONP-requests. Read more at jQuery Forums.

How can I stop jQuery.ajax() from logging failures to the console?

I am using the following jQuery JSONP request to check the status of a resource by URL. When the resource is not available or the server is down, my ajaxFail() function updates the display.
function fetchServerStatus(service, host)
{
var port = serverStatus[service].port;
$.ajax({
url: "http://" + host + ":" + port + "/admin/server/status",
dataType: "jsonp",
timeout: 1000,
error: ajaxFail,
fail: ajaxFail,
success: ajaxDone,
done: ajaxDone,
complete: ajaxAlways,
always: ajaxAlways
});
}
The problem I'm having is that despite declaring handlers for fail and error, which do not log anything to the console, jQuery always logs the failed request in the console. If the resource is unavailable for a long time, this builds up a huge console log, eventually crashing the browser process (Chrome in my case).
Is there any way to stop it from doing this?
The logging entry in chrome's console is a behaviour of chrome when any HTTP request is handled, not a problem with jQuery or ajax(XMLHttpRequest), even an <img> or <link> tag could cause this issue.
Your only choice is to fix your server-side code not to trigger an error for ajax (eg. 404 not found or wrong content-type), so based on the content logged to console, maybe a better solution could be found, please provide accurate logging message in your console.
put this in the top of your page:
<script>
$(document).ready(function() {
jQuery.migrateMute = true;
})
</script>
its temporary - but worked for me. Beats having to scroll through 45 lines of nonsense to debug js errors.

Categories

Resources