0

I'm trying to call ajax request without using jquery. By using ECMA Script6:

var promise1 = new Promise(function(resolve, reject) {
        var xhr = new XMLHttpRequest();
        var url = urls.urlListChapters.replace(0, specificationId);
        xhr.open('GET', url, true);
        xhr.responseType = 'json';
        xhr.onload = function() {
            if (xhr.status === 200) {
                alert(xhr.response);
                resolve(xhr.response);
            } else {
                reject(new Error(xhr.statusText));
            }
        };
        xhr.onerror = function() {
            reject(new Error("Network error"));
        };
        xhr.send();
    });
    promise1.then(function(data) {
        alert('Your public IP address is: ' + data);
    }, function(status) {
        alert('Something went wrong.');
    });

I get as response "null". However, with my ol jquery method, I do get the list of objects.

$.ajax({
        url: urls.urlListChapters.replace(0, specificationId),
        dataType: 'json',
        method: 'GET',
    })
    .done(function(data) {
        var data = JSON.parse(data);
        console.log(data);
        alert(1)
    })
    .fail(function(jqXHR, textStatus, errorThrown){
        console.log(jqXHR);
        alert('WHAT!');
    });

Is there something I'm missing?

Ruben
  • 1,065
  • 5
  • 18
  • 44
  • check the browser developer tools network tab to see what is being sent/received for the request – Jaromanda X Mar 01 '17 at 23:23
  • `xhr.response` will be an Object if you set `responseType='json'` - though, Internet Exploder does not support that responseType - so in that case `response` will be a string - you're better off (if you need to support IE) not setting responseType, and then executing `resolve(JSON.parse(xhr.response))` – Jaromanda X Mar 04 '17 at 03:50
  • Met the same problem when porting jQuery code to this solution: https://stackoverflow.com/questions/30008114/how-do-i-promisify-native-xhr/30008115 – Anton Kochkov Dec 18 '18 at 12:02
  • 1
    You should use the fetch API and a polyfill instead. There's no reason to promisify XHR manually. – slikts Dec 18 '18 at 12:12

0 Answers0