$.post not triggering function - javascript

I really don't get why alert or console.log is not being triggered in this code:
$.post("http://localhost:8080/mail",
jsonObject,
function(data) {
console.log("Done!");
alert("Thank you for your inquiry. We will get back to you soon.");
alert("Response: " + JSON.stringify(data));
}
);
While I can see the mail API works as I was able to get the email with the values I put in the HTML forms. alert and console.log is not being triggered what could be the reason?
I can see this on the browser log though:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost:8080/mail. This can be fixed
by moving the resource to the same domain or enabling CORS.
Could this be the reason? If so what should I do to make $.post trigger success or failure.

Cross Origin Requests (CORS) is your issue. $.ajax() crossDomain parameter as documented here
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain.
$.ajax({
type: "POST",
url: "http://localhost:8080/mail",
crossDomain : true,
data: jsonObject
...
})
Regarding how to catch a success or failure: You can chain done(), fail(), and always() to $.post
$.post("http://localhost:8080/mail", jsonObject, function(data) {
// alert("success");
}).done(function(){
// alert("success 2");
}).fail(function() {
// alert( "error" );
}).always(function(){
// alert( "finished" );
});
Which also works with $.ajax() or use callbacks within $.ajax()
$.ajax(function(){
success: function (responseData, textStatus, jqXHR) {},
error: function (responseData, textStatus, errorThrown) {}
});

Related

How should I fail gracefully when ERR_BLOCKED_BY_CLIENT? [duplicate]

I'm making an ajax jsonp request, but the failure error handling wont work. If the request is 404 or 500 it won't handle the error.
I've been looking around to find an answer to this, but can't find anything. There seems to be a solution with http://code.google.com/p/jquery-jsonp/, but I can't find any examples on how to use it.
function authenticate(user, pass) {
$.ajax ({
type: "POST",
url: "url",
dataType: 'jsonp',
async: false,
//json object to sent to the authentication url
data: {"u": userid, "p": pass},
success: function (data) {
//successful authentication here
console.log(data);
},
error: function(XHR, textStatus, errorThrown) {
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
})
}
If you check jQuery.ajax() documentation, you can find:
error
A function to be called if the request fails (...) Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
Because of that, you're forced to find workaround. You can specify timeout to trigger an error callback. It means that within specified time frame the request should be successfully completed. Otherwise, assume it has failed:
$.ajax({
...
timeout: 5000, // a lot of time for the request to be successfully completed
...
error: function(x, t, m) {
if(t==="timeout") {
// something went wrong (handle it)
}
}
});
Other issues in your code...
While JSONP (look here and here) can be used to overcome origin policy restriction, you can't POST using JSONP (see CORS instead) because it just doesn't work that way - it creates a element to fetch data, which has to be done via GET request. JSONP solution doesn't use XmlHttpRequest object, so it is not an AJAX request in the standard way of understanding, but the content is still accessed dynamically - no difference for the end user.
$.ajax({
url: url,
type: "GET"
dataType: "jsonp",
...
Second, you provide data incorrectly. You're pushing javascript object (created using object literals) onto the wire instead of its serialized JSON representation. Create JSON string (not manually, use e.g. JSON.stringify converter):
$.ajax({
...
data: JSON.stringify({u: userid, p: pass}),
...
Last issue, you've set async to false, while documentation says:
Cross-domain requests and dataType: "jsonp" requests do not support
synchronous operation.
Two ways to handle error,
There is no error handling for cross domain JSONP requests. Use jsonp plug-in available on Github https://github.com/jaubourg/jquery-jsonp that provides support for error handling.
jQuery ajax Timeout - Timeout after a reasonable amount of time to fire the error callback because it might have failed silently. You may not know what the actual error (or error status) was but at least you get to handle the error
I've been struggling like you for a while trying to handle errors on ajax jsonp DataType requests, however I want to share you my code, hope it helps. A basic thing is to include a timeout on the ajax request, otherwise it'll never enter the error: function
$.ajax({
url: "google.com/api/doesnotexists",
dataType: "jsonp",
timeout: 5000,
success: function (parsed_json) {
console.log(parsed_json);
},
error: function (parsedjson, textStatus, errorThrown) {
console.log("parsedJson: " + JSON.stringify(parsedjson));
$('body').append(
"parsedJson status: " + parsedjson.status + '</br>' +
"errorStatus: " + textStatus + '</br>' +
"errorThrown: " + errorThrown);
}
});
jsfiddle - Handle Errors with jquery ajax call and JSONP dataType - Error 404
I'm building a fragile JS project that uses jquery-jsonp, and came up with a dual-jsonp/ajax approach that handles errors no matter which method ends up being used.
function authenticate(user, pass) {
var ajax = ($.jsonp || $.ajax)({
'url': /* your auth url */,
'data': { /* user, pass, ... */ },
'contentType': "application/javascript",
'dataType': 'jsonp',
'callbackParameter': 'callback' // $.jsonp only; $.ajax uses 'jsonpCallback'
});
ajax.done(function (data) {
// your success events
});
ajax.fail(function (jqXHR, textStatus, errorThrown) {
// $.jsonp calls this func as function (jqXHR, textStatus)
// and $.ajax calls this func with the given signature
console.error('AJAX / JSONP ' + textStatus + ': ' +
(errorThrown || jqXHR.url));
});
}
Since both jquery-jsonp and $.ajax support the jQuery Deferred specification, we can merge the two error handlers together, handling 400 and 500-series errors, as well as lookup timeouts.
Old question but I had the same problem. Here is a solution that worked for me.
If you own the domain you shoot your request at, you can set a variable in the response and check for it on the client side.
Server Side:
SERVER_RESPONSE=true; Callback(parameter1, parameter2);
Client Side:
if(typeof SERVER_RESPONSE === 'undefined'){
console.log('No Response, maybe server is down');
}
else{
console.log('Got a server response');
}

using $ajax to perform GET request from tomcat server always fail jQuery

I have backend webService on tomcat server.always when I perform any request (post, get),code enters on error method.
jQuery code is:
var jqxhr = $.ajax(
{
type:"GET",
url:url
success: function() {
alert("success");
},
error: function() {
alert("fail");
}
});
my url is:
http://"192.168.20.220":6060/NostServices/rest/user/resend_activation_email/mailex#blah.com
error message on log is:
XMLHttpRequest cannot load http://"192.168.20.220":8080/NostServices/rest/user/resend_activation_email/dsgg#sdfkmj.com.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://"192.168.20.220":8383' is therefore not allowed access.
web service server is tomcat.
response of this requset can be 1 for success and -1 for mail not valid
and always enter on fail method and when I try to alert response it output [object object]
thanks you for your help
It's a JSONP request so your server side script needs to return data wrapped in callback:
For example
var url = 'http://example.com/req.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.log(json);
},
error: function(e) {
console.log(e.message);
}
});
And on server side:
jsonCallback({});
As your error says your code is failing because of the cross domain error problem. A very detailed answer is found here:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access
Please put in some effort to google these issues, this is a very common thing your trying and all errors have been encountered before and have been resolved somewhere. People will get very annoyed here if you show no effort to debug it yourself or provide all the required detail such as:
All relevant code
Print out of any variables in the code e.g. URL's
Any error message
A list of things you have tried
On a side note a URL should not have quotes it it. It should not be
http://"192.168.1.1":.........
it should be:
http://192.168.1.1:........

jquery ajax does not complete

I'm having a trouble with ajax requests and server responses:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true,
error: function(){},
success: function(){},
complete: function(){alert('complete')}
});
}
The thing is - sometimes I get succes, when I should get it, but sometimes I can get 500 status, and it is normal and expected.
The same ajax call works for correct requests, but fails for others.
I want to display an error message if I get a 500 server error, but for some reason the ajax does not complete. Thus, neither error: nor complete: work.
Maybe the reason for that is 'jsonp' datatype? Other datatypes do not work though.
Can someone help please?
Or maybe give me an advice on how to detect server status any other way.
jsonp requests do not trigger error callbacks by design, therefore there is no way for you to catch the error with javascript. I suggest instead implementing an error handler on your server that detects a jsonp request and returns jsonp that indicates an error has occured rather than a 500 status code.
Note that error: is deprecated as of 1.8 and is not called for JSONP however I wonder if you might have success using the Promise functionality introduced with 1.5 for deferred http://api.jquery.com/category/deferred-object/ as:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
jqXHR.done(function(data, textStatus, jqXHR) {});
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
Example for your code:
$.ajax({
url: servurl,
dataType: "jsonp",
data: {... },
crossDomain: true
}).done(function(data, textStatus, jqXHR){ //replace success
alert(textStatus);
}).always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { // replace complete
alert(textStatus);
}).fail(function(jqXHR, textStatus, errorThrown) { // replace error
alert(errorThrown);
});
Make sure that you are accessing to your server. Maybe you are requesting in your server for an specific contentType (like application/json) and you are not using that property into your ajax call.
As you requested, to show any message if get a error (400, 404, 500...), you can use my custom function for ajax error responses:
function onErrorFunc(jqXHR, status, errorText) {
alert('Status code: ' + jqXHR.status + '\nStatus text: ' + status +
'\nError thrown: ' + errorText);
}
Usage:
$.ajax({
//some options
error: onErrorFunc
});
Please, show us what error thrown your server.
Thank you all for comments. Jquery .ajax really does not give errors on jsonp requests.
The way to get error messages was to implement the jquery-jsonp plugin:
https://github.com/jaubourg/jquery-jsonp

JQuery Ajax request to http://pastebin.com/raw.php

I try to make a JQuery ajax request to 'http://pastebin.com/raw.php' and using this code:
$.ajax({
url: 'http://pastebin.com/raw.php',
data: "i=VJ29uFnk",
complete: function(jqXHR, textStatus) {
alert('complete');
},
success: function(data) {
alert(data);
},
error: function(xhr, status, error) {
alert('noh!')
}
});
With this I get a status '404' within xhr but the url I can see in firebug looks correct:
http://pastebin.com/raw.php?i=VJ29uFnk
Ideas?
XHR calls are protected under the Same origin policy.
What you can do, however, is call a server side script that bypass this.
You could circumvent the same origin policy by creating a php script that captured the data you want: example.com/getpage.php?url=pastebin.com/raw.php?i=VJ29uFnK.

Check for 404 error status in jquery

I use this code to get some information from twitter via their api:
$.ajax({
url : apiUrl,
cache : false,
crossDomain: true,
dataType: "jsonp",
success : function(html) {
// ...
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
However, if the apiUrl variable provides a correct url, this code work fine, e.i. the success object is executed, but if the url isn't correct, e.i. 404 error is returned from twitter, the error object is never executed. It doesn't log anything in console. How should I check for 404 error status in this case?
From jQuery API ajax docs:
error option
Note: This handler is not called for cross-domain script and JSONP
requests.
http://api.jquery.com/jQuery.ajax/
According to the docs, use statusCode setting in .ajax.
$.ajax({
...
statusCode: {
404: function(){
}
}
});

Categories