0

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?

Community
  • 1
  • 1
km6
  • 2,191
  • 2
  • 15
  • 18
  • Your second function should return Promise, if you want to use your handle function as an async function – Alex Jun 24 '16 at 21:07
  • Yes, but for some reason unbeknownst me it doesn't do it. I feel like there's something that I don't quite get about async functions, but then again it doesn't explain why it works with the console and why it doesn't work with returns. – km6 Jun 24 '16 at 21:20

1 Answers1

0

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)});

km6
  • 2,191
  • 2
  • 15
  • 18