loumadev
loumadev

Reputation: 369

XMLHttpRequest to jQuery Ajax

I have this code and I want it using jQuery Ajax.

var input = document.getElementsByTagName("input")[0], file, target, i, len;
input.addEventListener("change", function(e) {
    target = e.target.files;

    for (i = 0, len = target.length; i < len; i += 1) {
        file = target[i];
    }
    var fd = new FormData();
    fd.append('image', file);
    console.log(fd);


    var xhttp = new XMLHttpRequest();
    xhttp.open('POST', "https://api.imgur.com/3/image", true);
    xhttp.setRequestHeader('Authorization', 'Client-ID xxxxxxxxxxxxxxx');
    xhttp.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 300) {
                var response = '';
                try {
                    response = JSON.parse(this.responseText);
                } catch (err) {
                    response = this.responseText;
                }
                console.log(response);
            } else {
                throw new Error(this.status + " - " + this.statusText);
            }
        }
    };
    xhttp.send(fd);
    xhttp = null;
});

I already tried it make myself but it did not work.

Code I have tried:

$.ajax({
      url: "https://api.imgur.com/3/image",
      method: "POST",
      headers: {
            'Authorization':'Client-ID xxxxxxxxxxxxxxx'
      },
      data: fd,
      success: function(response) {
            console.log(response);
      }
});

But logs error:

Uncaught TypeError: Illegal invocation

It worked if I delete data: fd, but data is required.

Upvotes: 0

Views: 1365

Answers (1)

cagri
cagri

Reputation: 828

$.ajax({
    url: 'https://api.imgur.com/3/image',
    method: 'POST',
    data: fd,
    processData: false,
    headers: { 'Authorization': 'Client-ID xxxxxxxxxxxxxxx' },
    success: function(data){
        //do your parsing here
    }
});

Upvotes: 1

Related Questions