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?