0

I have an ajax request that looks like the following:

$.ajax({
    url: 'https://api.imgur.com/3/image',
    type: 'post',
    headers: {
        Authorization: 'Client-ID XXXXXX'
    },
    data: {
        image: img,
        title: 'test'
    },
    dataType: 'json',
    success: function(response) {
        if(response.success) {
            url = response.data.link;
            return url;
        }    
    }
});

However, this is dependent on jQuery. I would like to know how to write a pure javascript implementation of this.

I have the following code so far, but I'm not sure what to do next...

xmlhttp.open("POST","https://api.imgur.com/3/image",true);
xmlhttp.setRequestHeader("Content-type","application/json");

How can I integrate the data and the callbacks into this?

Thanks

MrCode
  • 63,975
  • 10
  • 90
  • 112
mjkaufer
  • 4,047
  • 5
  • 27
  • 55

4 Answers4

1

Use xmlhttp.send(data) to make the request, and xmlhttp.readystatechange to handle loading. Something like this:

xmlhttp.onreadystatechange = function()
{
 if (xmlhttp.readyState==4 && xmlhttp.status==200)
 {
  alert("loaded");
 }
}

xmlhttp.send({
    image: img,
    title: 'test'
}); // data here
geedubb
  • 4,048
  • 4
  • 27
  • 38
1

The data goes into the send. The callback is handled by listening to the onreadystatechange even.t

xmlhttp.onreadystatechange = function(){

   // Ready states
   // 0: request not initialized 
   // 1: server connection established
   // 2: request received 
   // 3: processing request 
   // 4: request finished and response is ready

   if (xmlhttp.readyState === 4) {

         if(xmlhttp.status ===200){
            // Success
         }
         else if(xmlhttp.status === 404){
            // Not found etc.
         }
   }
};

// Send Data

xmlhttp.send(data);
1

This is a complete conversion from your jQuery code to plain JavaScript.

xmlhttp=new XMLHttpRequest();

xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var response = JSON.parse(xmlhttp.responseText);
        if(response.success) {
            var url = response.data.link;
            // do something with url
        } 
    }
};

xmlhttp.setRequestHeader("Authorization","Client-ID XXXXXX");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.open("POST","https://api.imgur.com/3/image",true);
xmlhttp.send('img=' + encodeURIComponent(img) + '&title=' + encodeURIComponent('test'));

Notes:

  • You are not sending JSON so don't set a content type of JSON. The Content-type header refers to the data you send, not what you receive. Because you are sending URL/form encoded key value pairs, you should set the Content-type to application/x-www-form-urlencoded.

  • Your jQuery sends an Authorization request header, which you need to include using setRequestHeader().

  • Setting the jQuery dataType as json means that jQuery will automatically parse the JSON. Plain JavaScript won't do this, so you need to manually parse using JSON.parse().

  • To send POST data, you must pass the string to send(). It does not accept a plain object like jQuery does, you need to do the format and encoding yourselfRemember to use encodeURIComponent() around the values so prevent special characters from breaking the URL encoded format. If you want to define your POST data in an object, then you can use the function in this answer, which will convert a plain object into URL encoded key/value pairs.

  • You used return url inside the jQuery success handler, this won't do anything. The ajax is asynchronous so you can't return from the success handler because the code that initiated the request will have long completed before the response is received.

  • In the above example I directly called XMLHttpRequest() to get the object. If you want to be cross-browser, you should create it like in this question. The reason for this is that Internet Explorer uses an ActiveX object instead (although usage is the same as XMLHttpRequest).

Community
  • 1
  • 1
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Assuming you have a good reason to do this, for example you don't have control to add a reference to jquery in your application, might this tutorial help?

http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp

This is an extract from the tutorial:

xmlhttp.open("GET","ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
msteel9999
  • 305
  • 2
  • 15
  • It doesn't address the whole question. I want to know how to send the extra data, i.e. the `img` and `title`. – mjkaufer Apr 13 '14 at 13:21