jquery .click() not functioning after Ajax 403 response - javascript

I have some ajax that's returning a 403 error message but when it does, the click() function that was associated with the ajax call no longer works. I don't append or add any HTML before or after the ajax call, and if the ajax doesn't receive a 403 error, there are no problems. It's just simply if I receive a 403 error from the ajax POST, then the click() breaks. How can I fix this?
Here is my code:
$( "#add_comment" ).on('click', null, function() {
var data = {token:"{{ Session::token() }}", comment:$('#game_comment_form form textarea').val() };
$.ajax({
type: "POST",
dataType: 'json',
url: '/game/comment/{{$game->id}}',
data: data,
success: function(data){
alert("Success");
},
statusCode: {
403: function() {
alert( "Forbidden" );
}
},
error: function(e){
alert("Error");
console.log(e);
}
});
return false;
});

Why dont you try $.post(); method ?
like this...
$.post('/game/comment/{{$game->id}}',data,function(data){
alert("Success");
}).done(function(data, textStatus, jqXHR) {
// called on success
}).fail(function(jqXHR, textStatus, errorThrown) {
// called on failure
}).always(function() {
// called in both cases
});

Turns out I was completely overlooking the fact that I manually disable the input button and just simply forgot to re-enable it after the 403. I was going to delete this but hopefully someone else possibly realizes their simple mistake as I have and this helps them out.

Related

How to get HTML of a URL which response with a 404 error in jQuery?

Suppose I am trying to fetch page which throws a 404 not found response yet shows an html page. I want to get html elements of that page using jQuery.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
console.log($(data).find('#reviews .card').text());
},
error: function(data) {
console.log($(data).find('.not-found').text());
}
});
I get this message in console window
GET http://example.com/page/2/ 404 ()
Suppose I wanna grab the title from the page which says "Page does not exist." and the JSON object data returned between the <script> </script> of the html of the page, how should I do it?
do you mean this?
jQuery Ajax error handling, show custom exception messages
success: function(){
...
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr); // I believe this returns an object
console.log(xhr.statusText); //"Not Found"
console.log(xhr.status); //404
},
});
I too had this problem:
error: function (err) {
console.log(err); // This will throw the whole error.
console.log(err.response); // This will throw the object you want to modify
console.log(error.response.status); // This will throw the status code you want!
},
Hope this works!
As stated by #RoryMcCrossan I used responseText and rewrote the code again to something like this.
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
var html = $(data);
console.log(html.find('#reviews .card').text());
},
error: function(data) {
var html = $(data.responseText)
console.log(html.find('.not-found').text());
}
});

JQuery AJAX, Deleting from a table when successful and keeping when unsuccessful

$.ajax({
type: "GET",
dataType: 'html',
url: "submitreef" + "?id=" + $id,
timeout: 5000,
cache: false,
success: function(data, status, xhr) {
Materialize.toast('Deleted', 4000);
},
error: function(xhr, ajaxOptions, thrownError) {
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
$error = 'true';
}
});
}
if ($error != '') {
$(this).closest('tr').remove();
}
});
My problem is that when a button is pressed to delete a record from a table it works flawlessly, but when the error function is called it does not delete, I am trying to fix this, and my attempted fix is above, but it didn't work.
If you tried to delete it twice and there were 2 errors, it would then work, but that of course isn't very useful.
I really hope someone could help me out.
Many thanks.
var trToRemove = $(this).closest('tr');
$.ajax({
type: "GET",
dataType: 'html',
url: "submitreef"+"?id="+$id,
timeout: 5000,
cache: false,
success: function(data, status, xhr) {
trToRemove.remove();
Materialize.toast('Deleted', 4000);
},
error: function(xhr, ajaxOptions, thrownError) {
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
}
});
so its basically the problem with asynchronous ajax. your error or success gets called only when it receives a response from server. but your following code gets executed before that.
if ($error != '') {
$(this).closest('tr').remove();
}
so thats why its producing unexpected removal of the element.
as suggested by #MuhammadOmerAslam You must also keep in mind that success callback may get called but your actual data has not been deleted. so its better to return something after you deleted the data on server side and compare it in your success handler before removing the tr element.
if you return "success" after data is deleted on server side then your success function should look something like the following:
success: function(data, status, xhr) {
if(data=='success'){
trToRemove.remove();
Materialize.toast('Deleted', 4000);
}else{
Materialize.toast('Error, we could not delete the campaign, please try again later', 4000);
}
},

Handling HTTP status Ajax response

I am attempting to integrate the Instapaper Simple API into something but I am struggling to understand how to handle the response that the API sends back in Javascript. The article is adding to Instapaper just fine so I know that the submission is working just not my response handlers.
This is the code I have so far and I'm guessing that the success function is not the correct way of handling the response.
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function( data, status ) {
alert("yay");
},
error: function(status) {
alert("oh noes");
}
});
return false;
Instapaper returns a 201 when the article has been added. I can see that in the Google Chrome Network tool that the GET returned a 201 status. Just wondering how I handle that status within the code above.
Thanks.
Edit
When I click the link to activate the code below it pops up the alter under the error function right now even though it has worked.
jQuery.ajax() provides statusCode map for such purposes:
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
statusCode: {
200: function( data ) {
alert("yay");
},
201: function( data ) {
}
},
error: function(status) {
alert("oh noes");
}
});
http://api.jquery.com/jQuery.ajax/
$.ajax({
statusCode: {
201: function() {
alert("201!");
}
}
});
this should work with any http status code

How to handle ajax 201

When making a ajax call see example below success does gets a 201 status retuned. How do you handle these better i.e. 200, 201 within the success function?
$.ajax({
type: "POST",
dataType: "json",
url: "http://api.domain.com/sms",
data: {
// Send value in mobile input field.
mobile: $("#mobile").val(),
},
// On successful AJAX call do the following.
success: function(data) {
$('#messageText').text('SMS successfully sent');
},
error: function(jqXhr) {
data = JSON.parse(jqXhr.responseText);
}
});
Use the statusCode object:
var handle200 = function(data, textStatus, jqXHR) {
alert('200'); // success codes have the success signature
};
var handle201 = function(data, textStatus, jqXHR) {
alert('201'); // success codes have the success signature
// test it if you are in doubt:
console.log(data);
console.log(textStatus);
console.log(jqXHR);
};
var handle404 = function(jqXHR, textStatus, errorThrown) {
alert('404'); // failing codes have the error signature
});
var request = $.ajax({
type: 'POST',
url: '/myresource/posttarget',
data: { name: 'john' },
statusCode: {
200: handle200,
201: handle201,
404: handle404
}
});
This is an old question but I'd like to comment anyway.
I had the same problem and one thing that solved it for me was leaving the "dataType" unsetted. When you do this jQuery will try to guess the data type the server is returning and will not throw an error when your server returns a 201 with no content.
Hope it helps.
We had a similar problem; Looking at the jquery 1.9 source, a 201 status code expects content. If there is no content (or of the wrong content type) returned with the 201, then the fail callback is invoked.
Data inserted successful but jquery still returning error
The answer here appears to be a work around you can use for now. However, if you're using cross-domain, AJAX has some issues with that. Check out this SOF thread on it:
Problems Reading the HTTP Status/Error Code from jQuery AJAX
Instead of
ResponseEntity<?> responseEntity = new ResponseEntity<>(HttpStatus.CREATED);
I used
ResponseEntity<?> responseEntity = new ResponseEntity<>(detailVO, HttpStatus.CREATED);
Where detailVO is my object to rutrun in case of success. Then in browser I got response in success function.

jquery ajax does not send request

I have a problem with the following code.
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: 'sendMail.php',
type : "post",
data: sendJson,
success: function(data){
alert("Comanda dumneavoastra a fost trimisa");
}
});
Seems like data is not sent.... any idea why?
Ok... I know nothing is sent because I monitor requests with firebug.
I get no errors, nothing in console. Checked if it is activated, it is.
Here's what I meant with my comment:
var sendJson = (JSON.stringify(comanda));
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
Note that the ajax request has an error callback now. All requests should have an error callback so you can easily identify when errors are happening (as you've seen, firebug doesn't catch everything).
Another thing that I find helpful sometimes is StatusCodes:
$.ajax({
url: '/resource_url_goes_here',
type : 'POST',
data: sendJson,
statusCode: {
404: function() {
/*implementation for HTTP Status 404 (Not Found) goes here*/
},
401: function() {
/*implementation for HTTP Status 401 (Unauthorized) goes here*/
}
},
success: function(data){
/* implementation goes here */
},
error: function(jqXHR, textStatus, errorThrown) {
/* implementation goes here */
}
});
This will execute a function when a specific status code is returned by the server (404 and 401 in this snippet) and you can have a specific handler for the status codes you need.
You can find more about this here.

Categories