I’m learning web development and am trying to make an ajax request to query a MongoDB database hosted in MongoLab via their REST API. My code is very simple, but I don’t understand why the ajax request always go to the error. Help?
<doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.1.0.min.js"></script>
<title>Data Viewer</title>
</head>
<body>
<form id="the_form" method="post">
<input type="submit" value="Go" />
</form>
<script>
$(function() {
$('#the_form').submit(function() {
$.ajax({
url: 'https://api.mongolab.com/api/1/databases/omnitor-android/collections/logs?apiKey=[some API key in here]',
type: 'GET',
success: function(data) {
alert(data);
},
error: function() {
alert("boom");
}
});
});
});
</script>
</body>
</html>
This is because of you are trying to call a service hosted in different domain.Ajax is not allowing cross domain requests because of the Same origin policy. you cannot use ajax to call external sites. if you really want to use, you have to use JSONP. Or you can use serverside proxy for this. means, call external site in the server side and do ajax call to the that webservice.
For more details on how to do the cross domain ajax requests follow this link.