km6 km6 - 4 months ago 18
Ajax Question

Return POST AJAX value in Javascript

I'm trying to make a Javascript function that gets two arguments, an

URL
and a
data
, posts it to a PHP and returns the server's
response
without jQuery or any library. (Source)

function post(URL, data) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', URL, true);
req.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error('Network Error'));
};
req.send(data);
});
}

<?php
if ( isset($_POST['data']) ) {
echo json_encode(array("Hey {$_POST['data']}" ));
} else {
echo json_encode(array("Error"));
}
?>


So far so good, here's how I'm handling it.

function handle(URL, data) {
post(URL, data).then(function(response) {
return response;
}, function(error) {
return error;
});
}


However, this always returns undefined. Interestingly, if I try to
console.log(response)
it works fine.

I want to be able to do such things like
alert(handle(URL, data));


Is this impossible? If yes how could I get around it?

km6 km6
Answer

I ended up reworking my script to use callback instead.

var AJAX = {
    get: function(a, b) {
        var c = new XMLHttpRequest();
        c.onreadystatechange = function() {
            if (c.readyState == 4 && c.status == 200) {
                b(c.responseText);
            }
        };
        c.open('GET', a, true);
        c.send();
    },
    post: function(a, b, d) {
        var c = new XMLHttpRequest();
        c.onreadystatechange = function() {
            if (c.readyState == 4 && c.status == 200) {
                d(c.responseText);
            }
        };
        c.open('POST', a, true);
        c.setRequestHeader('Content-type',
            'application/x-www-form-urlencoded');
        c.send(b);
    }
};

This is how you call it: AJAX.get('text.txt', function doSomething(what){console.log(what)});