5
$.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?

Ehsan
  • 1,937
  • 1
  • 17
  • 30
user2231356
  • 95
  • 1
  • 2
  • 8
  • You use XMLHttpRequest. Lots of examples on how to do this out there. Here's one: http://codeislife.org/javascript/pure-javascript-ajax-190 Just search the google for "pure javascript ajax" – joelmdev May 16 '14 at 18:30
  • Why is Ajax superior or so much more common? – dcclassics May 16 '14 at 18:37
  • I tried this code. But it throws an error, as well as all 'Error in request' – user2231356 May 16 '14 at 18:45
  • JSONP and `POST` - am I missing something? JSONP is actually a way to (cross site) request data by a `script` tag that's injected to the page DOM (naturally leading to a `GET` request), executing the function call defined in the Javascript response to handle the data. From this point @Kevin B's answer is perfectly correct. Your API looks strange. – try-catch-finally May 16 '14 at 19:11
  • 2
    @joelmdev ironically, this question pops at the top of the results for me. – rr- Jan 03 '15 at 13:57

2 Answers2

8
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

Hasse Björk
  • 1,431
  • 13
  • 19
desu
  • 455
  • 2
  • 18
7

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);
Kevin B
  • 94,570
  • 16
  • 163
  • 180