Reputation: 1361
I'm currently creating a function that makes a POST request to an application. I have my JSON string correctly set up, but when I use the debugger and monitor network activity, I never see any request being sent from my browser. Here is a breakdown of my code. I had to do some trickery, as this is a PoC code, and it originally dealt with a jsp page.
$(document).ready(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var myJsonObject = new Object();
//set up my object and stringify it into myString
sendDataToServer(myString);
});
function sendDataToServer(jsonString) {
$.ajax({
type: "POST",
data: jsonString,
contentType: "application/json; charset=utf-8",
url: "https://my.target.server.com"
dataType : 'json',
processdata: true,
success: eval("successMessage"),
error: eval("failureMessage")
});
}
function successMessage() {
alert("Post was successful");
}
function failureMessage() {
alert("Post failed");
}
});
Now, my ajax call fails (still dealing with credential issues and certs), but I can't even see any request being sent from the start. Is my ajax call wrong, or is there some other problem? If I am denied access to the server due to cert issues, would it fail when trying to set up a connection to the server before sending any request?
And for some extra info, I do see the failureMessage() alert when I submit my form, so I know it is at least calling the ajax function.
Upvotes: 1
Views: 1041
Reputation: 19945
See this to illustrate what I meant with closures. I also integrated the answer the others gave.
function sendDataToServer(jsonString) {
$.ajax({
type: "POST",
data: jsonString,
contentType: "application/json; charset=utf-8",
url: "https://my.target.server.com"
dataType : 'json',
processdata: true,
crossDomain: true,
success: function() {alert("Post was successful")},
error: function(){alert("Post failed")}
}
}
Upvotes: 0
Reputation: 2128
This may be because of cross site domains. By default it is set to false. If url is a different domain you need to switch it to true.
As per JQuery documentation
crossDomain (default: false for same-domain requests, true for cross-domain requests)
Type: Boolean
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. (version added: 1.5)
Hope this be of some help Happy Learning :)
Upvotes: 0
Reputation: 3129
You can not send cross-domain AJAX requests.
Seems like "https://my.target.server.com" is a different domain than the one where your script is running.
Other popular solutions would be JSONP
, iframe
or flash
. Or using your back end as a proxy.
See this and this. If target server is also owned by you, you may want to examine Cross-Origin Resource Sharing.
Upvotes: 1