By Strohhut

2019-05-15 16:08:55 8 Comments

I want to get data from a MySQL-database using JS and PHP (without jquery or ajax) But I keep getting the "undefined Return Value Error".

It's my first time programming in JS and PHP.

url: "../PHP/Kassensystem.php?productname="+productname


function getProduct(url) {

let product;

var request = new XMLHttpRequest();"GET", url, true);
request.onload = function () {
    if (request.status == 200) {
        product = request.responseText;

return product;


$productname = $_GET['productname'];
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'allgolddb';

$conn = mysqli_connect($servername, $username, $password, $dbname);
$prodctInfos = array();

$sql = "SELECT * FROM products WHERE name = '$productname'";

$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
  $prodctInfos[] = $row;

$json_array = json_encode($prodctInfos);
return $json_array;


@1565986223 2019-05-15 16:49:17

In your open method you've set 3rd param to true so your request.send will be executed asynchronously. And as with every asynchronous JavaScript, by the time your code execution reaches return product product is still undefined and hence the error.

You can set the 3rd param to false to make it synchronous and your code will work (atleast working in firefox so far):"GET", url, false);

However the sync option is deprecated. From MDN

Synchronous requests on the main thread can be easily disruptive to the user experience and should be avoided; in fact, many browsers have deprecated synchronous XHR support on the main thread entirely. Synchronous requests are permitted in Workers.

As for working asynchronously, you'll have to consume within the callback to onload method:

request.onload = function () {
  if (request.status == 200) {
    product = request.responseText;
    console.log(product) // consume here

You could also use Promise, optionally with async/await. More here to work with asynchronous code.

Related Questions

Sponsored Content

40 Answered Questions

39 Answered Questions

[SOLVED] How do I return the response from an asynchronous call?

52 Answered Questions

45 Answered Questions

[SOLVED] Detecting an undefined object property

30 Answered Questions

[SOLVED] How can I determine if a variable is 'undefined' or 'null'?

46 Answered Questions

[SOLVED] Sort array of objects by string property value

73 Answered Questions

[SOLVED] How can I get query string values in JavaScript?

46 Answered Questions

[SOLVED] How can I check for an empty/undefined/null string in JavaScript?

54 Answered Questions

13 Answered Questions

[SOLVED] event.preventDefault() vs. return false

Sponsored Content