Display a fail alert when using "PUT" with xmlhttp - javascript

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).

Related

Am having a problem with my JavaScript log out code

I am trying to logout a user using a JavaScript code but it keeps loading without logging out.What have I done wrong?
I have tried changing the function itself but it still wouldn't log out.The loader just keeps on running.
this is the code
logout.html(loader);
$.get("modules/"+role+"/"+role+".php",{
},function(pagedata){
logout.show().html(pagedata);
});
I'm expecting the code to logout and take me back to the login page.
The
$.get()
method requests data from the server with an HTTP GET request.
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
$.get(URL,callback);
so change your code :
logout.html(loader);
$.get("modules/"+role+"/"+role+".php",function(pagedata){
logout.show().html(pagedata);
});

How to test JQuery fail callback?

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.

One entry point for all ajax callbacks for a particular call in javascript

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);

jQuery ajax request to Flickr sporadically fails

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.

No callback executed on `read` and an error received (exception thrown and not caught)

In CRM Dynamics I'm executing the following code. I've tried to put it inside a try-catch statement to catch the allegedly uncaught exception but it makes no difference. I'm guessing that it occurs inside CRM server, C# code or something like that.
var temp = OData.read({
urlOrRequest: "https://myurl/2011/OrganizationData.svc/crmk_CustomEntitySet",
success: function(dataSet) { alert("Yippi!"); },
error: function(errorMessage) { alert("Buuuu..."); },
handler: null,
httpClient: null,
metaData: null
});
Of course, I've tested to execute the https://myurl/2011/OrganizationData.svc/crmk_CustomEntitySet call and it resturns the data as supposed to, so apparently I've got connection and access right in order.
However, I get neither of the callbacks to execute. Everything is just ghostly quiet. As I attempt to close or reload the page, though, I get an error message from CRM Dynamics, the partial contents of which are listed below.
<ScriptErrorDetails>
<Message>Exception thrown and not caught</Message>
<Line>13</Line>
<URL>/%7B634854498230000000%7D/WebResources/crmk_MyResourceWithDataJS</URL>
<PageURL>/userdefined/edit.aspx
?etc=10008&pagemode=iframe&preloadcache=1349853066209</PageURL>
<Function></Function>
<CallStack></CallStack>
</ScriptErrorDetails>
Given my competence level with CRM Dynamics (low) and with DataJS package (loooow), I'm stuck having no clue as to why it doesn't work nor how to trouble-shoot it.
I've checked out every example I could find on their page
You're getting no callback execution because you're not sending in one. You think you do but you don't. You're using the JSON syntax putting the properties (or whatever they're called) in an object. You're intending the following list of inputs.
The URL to organization data.
A function telling what to do if successful.
A function telling what to do if failed.
A bunch of nulls.
But since you package it into a structure, the CRM sees the following (regarding the full signature of the function odata.read(...) as seen in the source file..
An object with some stuff in it, not constituting a parsable URL.
Nothing at all, meaning null, while CRM wants to see a function (success).
Nothing at all, meaning null, while CRM wants to see a function (fail).
Nothing at all, meaning null, while CRM wants to see a function (serialization).
Nothing at all, meaning null, while CRM wants to see a HTTP client layer (whatever that might be).
Nothing at all, meaning null, while CRM wants to see some metadata.
Then a crash occurs inside the CRM server (since you failed to provide a parsable URL to the organization data that you're trying to read) and an exception is being thrown. But you haven't provided a callback function for receiving the notification of such an error, which is the message you've mentioned.
Your try-catch doesn't catch anything since there's no exception to catch. It's already been caught inside CRM Dynamics server. What you see is that it complains that there's no function to be called for notifying you about that.
Try to execute an equivalent to this code and see if you're successful (or at least get another error message).
var temp = OData.read(
"https://myurl/2011/OrganizationData.svc/crmk_CustomEntitySet",
function(dataSet) { alert("Data retrieval successful."); },
function(errorMessage) { alert("Operation failure!"); }
});
I'm assuming that you're using an other URL than what you've shown us in your code sample. It's just an example, right? You can test pasting in the very URL into IE and see if you'll get a reply and what it contains.

Categories

Resources