This question already has an answer here:
Closed 6 years ago.
$.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post'
,success:function (data) {
console.log('ok');
},
error:function () {
console.log('error');
}
});
How do I write the same functionality in pure JS?
In this particular case, you aren't making an ajax call at all, instead you're making a JSONP request. Luckily, these are incredibly easy to replicate and work in all browsers.
var s = document.createElement("script"),
callback = "jsonpCallback_" + new Date().getTime(),
url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
// it worked!
console.log(data);
};
s.src = url;
document.body.appendChild(s);
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", 'http://forexplay.net/ajax/quotes.php');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
console.log('Response: ' + xmlhttp.responseText );
}else{
console.log('Error: ' + xmlhttp.statusText )
}
}
}
xmlhttp.send(data);
I'm always forgetting about capital and small letters in XMLHttpRequest