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

JS:

function getProduct(url) {

let product;

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

return product;
}

PHP:

<?php
$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;
?>

1 comments

@1556089774 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):

request.open("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

34 Answered Questions

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

23 Answered Questions

[SOLVED] How to determine if variable is 'undefined' or 'null'?

41 Answered Questions

[SOLVED] Sort array of objects by string property value

52 Answered Questions

13 Answered Questions

41 Answered Questions

[SOLVED] How to check empty/undefined/null string in JavaScript?

16 Answered Questions

[SOLVED] How to check for "undefined" in JavaScript?

  • 2010-08-02 17:53:29
  • random65537
  • 2039022 View
  • 2139 Score
  • 16 Answer
  • Tags:   javascript undefined

29 Answered Questions

73 Answered Questions

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

41 Answered Questions

[SOLVED] Detecting an undefined object property

Sponsored Content