I have an incredibly simple Ajax post which isn't working:
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
var deviceDetails = [];
deviceDetails.project_title = 'project';
//deviceDetails.platform = window.device.platform;
deviceDetails.platform = 'ios';
$.ajax({
url: "http://someserver.com/device_api",
type: "post",
data: deviceDetails,
success: function(){
alert("success");
},
error: function(model, xhr, options){
alert('failed');
console.log('response is : ');
console.log(xhr.responseText);
},
});
</script>
</body>
</html>
The server simply does this:
I can see in the network tab of Chrome that the status of the Post is "cancelled". What am i missing?
Most likely you're suffering from the same origin policy of ajax requests. From the documentation for $.ajax
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
<script>
$(document).ready(function(){
var deviceDetails = [];
deviceDetails.project_title = 'project';
//deviceDetails.platform = window.device.platform;
deviceDetails.platform = 'ios';
var deviceDetailsObject = JSON.stringify(deviceDetails);
$.ajax({
url: "http://push.schoolspace.ie/device_api",
type: "post",
data: deviceDetailsObject,
success: function(){
alert("success");
},
error: function(model, xhr, options){
alert('failed');
console.log('response is : ');
console.log(xhr.responseText);
},
});
})
</script>
You need to convert the array to a JSON object / string ( http://api.jquery.com/jquery.post/ ). The JSON.stringify() function does this for you.
The POST request was being sent, but it wasn't hitting my logger on the server. I changed the url to:
url: "http://push.schoolspace.ie/device_api/"
with a "/" on the end, and this worked. I think it's to do with the .htaccess file on the server.