Problem with jQuery.ajax with 'delete' method in ie - javascript

I have a page where the user can edit various content using buttons and selects that trigger ajax calls. In particular, one action causes a url to be called remotely, with some data and a 'put' request, which (as i'm using a restful rails backend) triggers my update action. I also have a delete button which calls the same url but with a 'delete' request. The 'update' ajax call works in all browsers but the 'delete' one doesn't work in IE. I've got a vague memory of encountering something like this before...can anyone shed any light? here's my ajax calls:
//update action - works in all browsers
jQuery.ajax({
async:true,
data:data,
dataType:'script',
type:'put',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
initializeQuizQuestions();
setPublishButtonStatus();
}
});
//delete action - fails in ie
function deleteQuizQuestion(quizQuestionId, quizId){
//send ajax call to back end to change the difficulty of the quiz question
//back end will then refresh the relevant parts of the page (progress bars, flashes, quiz status)
jQuery.ajax({
async:true,
dataType:'script',
type:'delete',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
alert("success");
initializeQuizQuestions();
setSelectStatus(quizQuestionId, true);
jQuery("tr[id*='quiz_question_"+quizQuestionId+"']").removeClass('selected');
},
error: function(msg){
alert("error:" + msg);
}
});
}
I put the alerts in success and error in the delete ajax just to see what happens, and the 'error' part of the ajax call is triggered, but WITH NO CALL BEING MADE TO THE BACK END (i know this by watching my back end server logs). So, it fails before it even makes the call. I can't work out why - the 'msg' i get back from the error block is blank.
Any ideas anyone? Is this a known problem? I've tested it in ie6 and ie8 and it doesn't work in either.
thanks - max
EDIT - the solution - thanks to Nick Craver for pointing me in the right direction.
Rails (and maybe other frameworks?) has a subterfuge for the unsupported put and delete requests: a post request with the parameter "_method" (note the underscore) set to 'put' or 'delete' will be treated as if the actual request type was that string. So, in my case, i made this change - note the 'data' option':
jQuery.ajax({
async:true,
data: {"_method":"delete"},
dataType:'script',
type:'post',
url:"/quizzes/"+quizId+"/quiz_questions/"+quizQuestionId,
success: function(msg){
alert("success");
initializeQuizQuestions();
setSelectStatus(quizQuestionId, true);
jQuery("tr[id*='quiz_question_"+quizQuestionId+"']").removeClass('selected');
},
error: function(msg){
alert("error:" + msg);
}
});
}
Rails will now treat this as if it were a delete request, preserving the REST system. The reason my PUT example worked was just because in this particular case IE was happy to send a PUT request, but it officially does not support them so it's best to do this for PUT requests as well as DELETE requests.

IE 7 and 8 do not support DELETE and PUT methods. I had a problem where IE7,8 would not follow a 302 redirect and IE would use the DELETE or PUT method for the location that it was supposed to redirect to (with a get.)
To ensure that IE7 and 8 work properly, I would use a POST with the parameters:
data: {'_method': 'delete'}

Take a look at your type attribute type:'delete'
jQuery documentation on type:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
I would instead try and include this with your data and look for it on the server-side, like this:
data: {'action': 'delete'},

Related

Javascript ajax request callback without waiting for response

I know we can make a javascript ajax request from some server and it either receives the response or gives timeout error after some time.
Let's consider this scenario when we don't want to wait for the request rather the server would send a response(or we can say it would be another request from server to client) async at any time after getting the request and then call a javascript CB function with the response.
I am looking for ideas for how to go about it mainly supporting all modern browsers and if possible not relying on any 3rd party plugin except may be jQuery.
The main feature of Ajax is that it IS asynchronous by default, and your program will continue to run without waiting for the response. So unless I'm misreading your question, it is what you need.
If you use jquery, then you pass in a callback function that will execute only when the server sends back a response. You can specify a timeout in the settings, though I'm not sure what the maximum time you can provide without getting a timeout error. But it will be several seconds, at least.
You can even specify different callbacks for success and fail as follows (adapted from the jquery ajax API, but added a timeout of 5 seconds):
var request = $.ajax({
url: "http://www.some.url/",
method: "GET",
data: { some : stuff },
dataType: "html",
timeout: 5000
});
request.done(function( data ) {
console.log( "SUCCESS: " + data );
});
request.fail(function() {
console.log( "Request failed");
});
I came across this question after 4 years. I dont remember in what context I asked this but for anyone who has the same query:
Http is a request/response protocol. Which means the client sends a request and the server responds to that request with some message/data. Thats the end of the story for that request.
In order for the server to trigger something on the clientside we will have to use something that keeps the connection to the server rather than ending the communication after getting the response. Socket.io is bi directional event driven library that solves this problem.
To update a cart (PHP Session storage and reserve the stock of items in database) on my online shop, I simply add a timeout of 100ms after calling it and remove Success/Error callback.
$.ajax({
url: 'http://www.some.url/',
method: 'GET',
data: {
some : 'stuff'
},
dataType: 'html',
timeout: 100
});
Note : It doesn't matter if some requests didn't arrive, because when the order is saved, an update of the whole cart is sent with a callback.
If your query needs acknowledge, don't use that solution !
I believe your question is similar to this
by Paul Tomblin. I use the answer provided by gdoron, which is also marked as the best solution, and also the comment by AS7K.
$.ajax({
url: "theURL",
data: theData
});
NB: No async parameter provided.

Undefined index on ajax call only for one function

I have several different ajax calls on the same php page, but I get undefined index for only one function (createAlbum).
I send exactly the same parameters in each of my ajax calls. It worked fine for a few tests, but now it only works for the other ones, but not for this specific call.
I suspected that the .js file was still in the browser cache, so I cleared it and tried with other browsers, which worked for a few more attempts.
Now, I can't get it working on any browser, and definitely don't understand why.
Here is my ajax call :
$.ajax({
type: "POST",
url: BASE_URL,
data: {
action: "createAlbum",
data: JSONAlbum
},
cache: false,
success: callback
});
My php file handling the request ($_POST['action'] is always undefined with the above request) :
if (isset($_POST['action'])) {
switch ($_POST['action']) {
// Handle the action
// ...
}
} else {
echo 'ACTION : '.$_POST['action'];
}
The header containing the ajax parameters ("data" is a json containing one or more blob images, this might be the problem, but I didn't find anything saying so) :
And finally, the response containing the error :
I really hope this is not a dumb error of mine, but I asked a friend before posting, and he can't find the solution either.
Thanks for your help !
You said that the error not happens all the time (in some call yes, in other no).
The body post is sent, you see it in console. So we can exclude javascript problem.
So the problem is something that happens before or during the process.
PHP has some limitations on input vars, you can see it in php.ini.
I see that you send images in base64, so it's probable that something of these limitations are triggered.
See for example:
max_input_time
max_input_vars
post_max_size

Ajax call keeps getting blocked by browser

I am a bit stuck with an issue.
I am developing a small mobile website. I am trying to call a webservice using an ajax call, but the browser keeps blocking my call. If I start up Chrome using the tags... "--allow-file-access-from-files --disable-web-security​​" Then the call works perfectly. I have no issues whatsoever.
Now my problem is if I host the website, the browser is going to block my ajax call and the user cannot for example login or retrieve information. I present my ajax call below...
$.ajax({
async: true,
beforeSend: function () {
},
complete: function () { },
type: 'POST',
url: 'https://MySecretUrl.com/login?format=json',
contentType: 'application/json',
dataType: 'json',
data: '{"UserId":"mySecretUserId","Password":"mysecretPassowrd"}',
success: function (resultMessage) {
if (resultMessage.WasSuccessful == true) {
alert('YAY');
} else {
alert('Semi Yay');
}
},
error: alert('OOOOPS')
});
Does anybody know a workaround for getting information from the webservice without any browser blocking the ajax call ?
Any suggestions would be greatly appreciated.
Thanks in advance for the help.
EDIT
Hi Guys, Ok so I did some more digging and discovered the following.
When the request is made with browser security, the call changes the POST to a OPTIONS. this is called a preflighted request. One workaround that I have found is if you are making a GET call, then you can use jsonp as your data type. But now my problem is that it is incompatible with POST. Is there any fix that does not require the webservice to be changed ?
Is there any fix that does not require the webservice to be changed ?
No. If changing the webservice isn't an option, your only option is to not use the browser to make this request.
You must either make the server return the data in a format that can be accepted cross-domain, or don't make cross-domain requests with the browser.

Adding a contact using Google Contact API in javascript

I am playing with Google API in javascript. I managed to get a list of my contact with the following code :
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?access_token=' + access_token + '&alt=json',
method: 'GET',
error: function(error) {
alert('An error has occured during contact creation.');
},
success: function(data, status){
console.log(data);
}
});
I tried to add a contact by changing GET to POST and adding my contact data in the request body. But as soon as I add a data attribute, or change GET to POST, the server answers me the really annoying "No 'Access-Control-Allow-Origin" error.
Any idea?
I am following this documentation : https://developers.google.com/google-apps/contacts/v3/?csw=1#creating_contacts
Thanks a lot
It is possible to do this from the browser, although not obvious at all.
Based on this SO answer, we learn that there is method called gapi.client.request that can be used for this (instead of jQuery's $.ajax).
Accordingly, for editing we can do:
gapi.client.request({
method : 'PUT',
path:'m8/feeds/contacts/default/full/<contactId>/<editRevisionFromGET>',
body : {"version":"1.0","encoding":"UTF-8","entry": ...},
callback : function(data) {
console.log(data);
}
});
The important parts for editing in here are:
send back the entire entry you got before from a read
use the current ID given at the end of the URL in the entry.link element with relation type edit (or you'll get a HTTP Status 409 - Conflict)
Side note:
Notice that these requests actually are done to https://content.googleapis.com/ ...
From some quick tests, it seems you can do ?all? requests just to that URL instead of google.com, and then CORS issues disappear.

External server query not working

I am building a jQuery Mobile and PhoneGap application.
Here is some of my code to query data from an external server:
function showDetail(stationID){
$('#itemDetail').load('http://www.mywebsite.com/detailPage.php?stationId='+stationID, function(){
});
It works perfectly on my local machine, WAMP server, however when I compile the script and run on an actual device, Android, it does not work. The same thing applies to this form:
$('#addStationForm').on('submit', function(e) {
$.post( 'http://www.mywebsite.com/add_parser.php', $(this).serialize(), function(response) {
alert( response );
});
// disable default action
e.preventDefault();
});
Also I have whitelisted my server, so that is not the problem.
Any help would be greatly appriciated, thanks.
Are you trying to get data from a server and load it into a dom element?
If so use the .ajax function to perform a http request to get the data from the sever.
Check the following doc with good examples
http://api.jquery.com/jQuery.ajax/
Also provide more info about the type of data you are going to request receive to help you further in the configuration of the ajax call parameters.
You can also use getJSON but depending on your data and needs.
EDIT
Post is a shorthand of the ajax function.
Make sure your PHP does have the correct content-type in the headers. That is very important
Like:
header("Content-Type:text/plain");
or
header("Content-Type:text/html");
depending what you need, want.
Also you can debug the HTTP response using firebug or any other tool out there, and let us know what you got.
Also try to use the verbose option of the function, give it a try. Make sure you specify correctly the dataType and the data parameters.
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "html" // DATA TYPE is ALSO VERY IMPORTANT
})
.done(function() {
alert( "success" );
})
.fail(function( XMLHttpRequest, textStatus, errorThrown ) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
});
Also, when you said "when I compile the script and run on an actual device, Android, it does not work.", what errors you got? use the FAIL function of the http request to print the errors (like in the example above).

Categories