0

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.

Huangism
  • 16,278
  • 7
  • 48
  • 74
quarks
  • 33,478
  • 73
  • 290
  • 513
  • Yes that's the reason. *"If so what should I do to make $.post trigger success or failure."* As the message says: "This can be fixed by moving the resource to the same domain or enabling CORS." – Felix Kling Sep 04 '14 at 15:56
  • if chrome, open from the command line with: `chromium-browser --disable-web-security` – Brian Dillingham Sep 04 '14 at 16:10
  • you have a CORS problem. basically that means that you will need to change your backend implementation to return the correct headers. you can refer to this [http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working](http://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working) – arisalexis Sep 04 '14 at 15:58

1 Answers1

0

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) {}
});
Brian Dillingham
  • 9,118
  • 3
  • 28
  • 47