0

So I've been trying to return a value from a php script back to my javascript file but I cant figure it out. I know I'm supposed to use ajax but I'm not sure how that works. My php file works fine. It searches a database and returns true or false if it finds that value. Now I want a variable in my javascript file equal to either true or false from the php file however I'm not sure how to set that variable equal to the php value. Can anyone help me out?

my php file:

<?php

$username = "z";
$check;

$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "iarenadatabase";

$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);

if (mysqli_connect_error()) {
    die('Connect Error (' . mysqli_connect_errno()) . ')' . mysqli_connect_error();
} else {

    $result = mysqli_query($conn, "SELECT * FROM iarenadbtable
WHERE Username LIKE '%{$username}%'");

    if ($result->num_rows) {
        $check = true;
        echo json_encode($check);
    } else {
        $check = false;
        echo json_encode($check);
    }

    $conn->close();
}

// header('Location: index.html');
exit;
?>

And what little I have of ajax. im not sure what to do with this.

$('#test').click(function () {
  // alert("accessed");
  $.ajax({
    method: 'POST',
    url: 'DBSearch.php',
    data: "",

    dataType: 'json',
    success: function (data) {
      alert(data);
    }
  });
});

Im assuming 'data' should somehow end up equal to either true or false but im not sure how.

edit: nothing will print out within that success function whether I try and use data or just console.log("text"). It seems like that part isnt being accessed?

  • 2
    Indenting your code can be really helpful for debugging. – Ibu Nov 01 '18 at 22:58
  • Do a console.log(data) .. alert will not show you the correct info maybe. That said, when you answer in json, you must use an array exaple: `json_encode(['success'=>true])` – Daniel Nov 01 '18 at 22:58
  • 1
    @Daniel that is incorrect. `true` and `false` are perfectly valid JSON responses – Phil Nov 01 '18 at 22:58
  • It's unclear what your question is. Your code looks fine (except you should really use a [prepared statement](http://php.net/manual/mysqli.quickstart.prepared-statements.php)). If it doesn't work as expected, please explain the details. Check your browser's console for errors. You should also be able to see the AJAX request and response in the _Network_ tab – Phil Nov 01 '18 at 23:02
  • @Phil - Interesting. Never tried that actually. Figured it should be translated by the JSON encoder/decoder. – Daniel Nov 01 '18 at 23:02
  • 1
    @Daniel JSON just has to be a valid string which can include scalar values like numbers, quoted strings, Booleans and `null` as well as objects and arrays – Phil Nov 01 '18 at 23:04
  • Possible duplicate of [How to get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) and [How to get MySQLi error information in different environments](https://stackoverflow.com/questions/22662488/how-to-get-mysqli-error-information-in-different-environments) – Phil Nov 01 '18 at 23:48
  • are you sure you import jquery library? – Ramy Ibrahim Nov 02 '18 at 00:22
  • @RamyMalak yes I'm using jquery in other parts of the javascript file and it works fine. its linked in the main html document and functions as expected. – Christopher Trubey Nov 02 '18 at 00:28
  • can you check your browser logs and paste the logs here – Ramy Ibrahim Nov 02 '18 at 00:31
  • @RamyMalak nothing is printing to the console. I added a console.log before and after the ajax and both of those are printing out but nothing else when I load the html file or when i click the button or when i manually select the php file to run. if i just link straight to the php file from a form it finds and runs it fine as well with the same link/path. – Christopher Trubey Nov 02 '18 at 00:50
  • You say nothing is printing after clicking the button. This behavior may be because you have more than one html element with the id test in your html file. change the id text and try again – Ramy Ibrahim Nov 02 '18 at 00:58
  • @RamyMalak still nothing. the button itself works because i can get it to print out if i use console.log its just not doing anything with ajax it seems – Christopher Trubey Nov 02 '18 at 01:02

2 Answers2

0

if you mean you want in your javascript a boolean variable which represent $check variable in php. then the data variable is already holding this value.

Ramy Ibrahim
  • 656
  • 4
  • 19
  • so then why cant I get anything to print out? i dont get anything from alert or console.log. if i run console.log("test") within that success function nothing is output either despite just trying to output text by itself. it seems like its not accessing the success function. – Christopher Trubey Nov 01 '18 at 23:44
  • 1
    @ChristopherTrubey that means your PHP is not working and producing an error. Try opening `DBSearch.php` directly in your browser and make sure you can [see errors](https://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php). Also consider adding an `error` callback to your `$.ajax()` call – Phil Nov 01 '18 at 23:46
  • 1
    as @Phil said, you may have error in your php script. you can test it by just simple script like this which will always return false please make sure you have an HTML element with the id test and your php file script name is DBSearch.php and located in the same path with the js file – Ramy Ibrahim Nov 01 '18 at 23:56
  • @RamyMalak that script returns false correctly and my php script correctly returns true or false when searching for usernames that are in the database. I have an html button with id test and my php file is in the same folder as my javascript file. – Christopher Trubey Nov 02 '18 at 00:13
-1

The value of $check should be more like

{"success":"true"}