This is jquery function:
$.get("/url", function(){
//success
}).fail(function(){
//fail <---- how to make code go in there.
});
Problem is how to let program goes into .fail block, I use .Net MVC, However, set break point in Controller doesn't trigger a timeout exception then leads to fail callback.
Don't know how people test this.
Should I start looking at some tools ?
Put this in your Controller method:
return new HttpStatusCodeResult(HttpStatusCode.NotFound);
Use an invalid endpoint URL. You should get 404 - not found http status code error.
Related
I am currently writing stuff back to the database using :
xmlhttp.open("PUT","...",false);
xmlhttp.setRequestHeader("Content-type","application/xml");
xmlhttp.send((new XMLSerializer()).serializeToString(xmlDoc.getElementsByTagName("beanRepresentation")[i]));
I want a alert if this fails, for example the database does not support PUT or something like that. How can I achieve this?
you should start reading more about XMLHttpRequest
To check for errors, you can bind a function to the error event:
xmlhttp.addEventListener('error', errorCallback);
This callback will be fired if any error occurs during the execution of the request (a server error, a connection error, and so on).
When communicating with a server in javascript in my single page browser application, I would like to provide a callback function that is always called after the server replies, regardless of whether the result was a success or some kind of error.
Two cases where I need this:
1) I want to disable a "save" button while waiting for the server's response, and enable it again after the server responds with an error or a success.
2) I have a polling mechanism where I want to prevent stacking of calls when the server for some reason is being slow to respond - I want to wait for one poll call to finish before making the next.
One solution I have right now involves making sure that two functions (success and error) get passed along as options in a long method chain, which feels like a fragile and cumbersome solution (pseudo-ish code):
function doCall() {
framework1.callit({success : myCallback, error : myCallback})
};
framework123.callit = function(options) {
options = options || {};
if (options.error) {
var oldError = options.error;
options.error = function(errorStuff) {
// callit error stuff
oldError(errorStuff);
} else {
// callit error stuff
}
generalCallFunction(options);
}
function generalCallFunction(options) {
options = // ... checking success and error once again to get general success and error stuff in there, plus adding more options
ajax( blah, blah, options);
}
I also have a backbone solution where I listen to the sync event plus an error callback, in similar ways as above.
I'm always scared that error or success functions get lost on the way, and the whole thing is hard to follow.
Any framework or pattern for making this stuff as easy as possible? Is it a weird thing to have general things that should always happen whether the result was an error or a success?
You can use jQuery.ajax({ details here... ).always(callback);
Or, in Backbone
// logic to create model here
model.fetch().always(callback);
This is my first use of Ajax. Here is the script I am trying to run:
$(document).ready(function() {
alert("on document ready");
$(document).click(function(e){
alert("inside click handler");
$.get("runner.php", function(data) {
alert("get method has completed");
});
});
});
The alerts: "on document ready" and "inside click handler" all display correctly but I cannot get the alert inside the $.get method to display. Also, the runner.php file is in the same directory as the JavaScript file. I eventually want to get information from the runner.php file but I cannot even make this $.get method complete.
I'm sure I'm missing something simple here, but this example was taken almost directly from the jQuery manual.
Try placing an absolute url to runner.php, so /js/runner.php or /runner.php whichever directory it's in.
Also if you have firebug installed, you can use it to view what the problem is. If it's telling you 404 Not Found then you will need to place the absolute url as I just mentioned.
Try to follow this pattern:
$.get("runner.php", function() {
alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
Where are these files? Are they on a web server or on your local computer? I had the same problem before and the reason being I was trying to access a file that was located on my local computer so I would always get an error
AJAX request using jQuery does not work
I fixed it by setting up a local web server and the same code worked beautifully :)
If you are using jquery 1.8 or later, then you need to use the fail() function to report errors with your call to your PHP, like this:
.get("runner.php", function() {
alert("success");
})
.fail(function() {
alert("An error happened, check PHP script for problems.");
})
Note: jQuery 1.8 deprecated the error callback and replaced it with the .fail() function.
The most likely cause of nothing happening on the callback is a 404 or 500 error. As with a few other answers, make sure to add a fail listener to your $.get request and you can console.log(data); to determine what's going wrong on the server side.
I've got the following code to call a json web service in a separate functions.js file.
function getMajorGroups(){
var element = $(".item-group-button");
$.ajax({
type:"GET",
url:"localhost:6458/posApplication/getAllMajorGroups",
data:"{}",
contentType:"application/json; charset=utf-8",
dataType:"json",
done:successResult(majorGroups),
fail:errorResult(error)
});
}
function successResult(majorGroups){
var mGroups = response.d;
$("#item-groups").empty();
$.each(majorGroups ,function(){
var h3 = $('h3').append(majorGroups.code);
element.append(h3);
$("#item-groups").prepend(element);
});
}
function errorResult(error){
alert("error");
}
When I run the web page and I use firebug to trace the steps I can see the script is executed. But it does not execute the success or failure code inside the ajax call. Am I doing anything wrong here?
Below is an example of the string which the service return.
{"majorGroups":[{"update":"false","hasMore":"false","status":"A","description":"Beverage","majorGroupId":"48","code":"Beverage"},{"update":"false","hasMore":"false","status":"A","description":"Laundry","majorGroupId":"51","code":"Laundry"},{"update":"false","hasMore":"false","status":"A","description":"Cigarette","majorGroupId":"50","code":"Cigarette"},{"update":"false","hasMore":"false","status":"A","description":"Food","majorGroupId":"47","code":"Food"},{"update":"false","hasMore":"false","status":"A","description":"Health Center","majorGroupId":"52","code":"Health Center"}],"failure":"false"}
$.ajax has no property named failoure. error should be used so it looks like error: errorResult
Besides that check that request is made via Network tab in Chrome dev tools or some similar tool. Check what is in the the raw response and make sure that is what you wanted. If request failed you will see way or at least have error code.
If everything is fine so far then make sure your adding DOM elements when DOM is ready so wrap your stuff with $(function(){ /* your stuff here */ })
Edit:
That's not the way done and fail should be used. jQuery ajax call returns promise.
$.ajax({
url : "..."
/* omitted */
}).done(successCallback).fail(failCallback)
where successCallback can be either function name like your defined succes function or just anonymous function like
.done(function(response){
// do stuff with response
}
I think you should carefully read jQuery documentation.
Also your $.each call is kinda broken - you skipped parameter in function provided to $.each
Occasionally, an ajax request to Flickr's api will fail. I'm not sure if I'm doing something wrong here - or if I'm just not handling things correctly - but the code works over 90% of the time. When it doesn't work, I get the following error message from Firefox's console:
TypeError: jQuery19109306644694293944_1362865216185 is not a function
(I am letting jquery generate the callback, which is why the callback is named like that.)
This is the code that sometimes fails:
function getAppropriateSize(photo){
console.log("In getAppropriateSize");
/** stuff. query is defined here **/
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.getSizes&format=json&api_key='+flickrKey+'&photo_id='+query.id,
dataType:'jsonp',
jsonp:'jsoncallback',
timeout:3000,
success: function(sizes){
console.log("In success - getAppropriateSize");
/**determine the correct size**/
flickrURL = sizes.sizes.size[currVal].source;
},
error: function(xmlhttprequest,textstatus,msg){
console.log("In error - getAppropriateSize");
/* handle error*/
}
});
}
I've checked what's returned when this happens and JSLint says it's valid javascript. flickrURL also gets set to a valid URL. I'm pretty mystified about what's causing this error - any help would be appreciated.
Edit: I was messing around and this time getAppropriateSize just received two separate messages from flickr for one call. The first one was
({stat:"fail", code:1, message:"Photo not found"})
The second one was the a full response from the server that also produced the TypeError mentioned above. However, the second response found the photo and gave me the sizes.