简体   繁体   中英

Returning PHP value to Javascript via Ajax

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?

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.

$check的值应该更像

{"success":"true"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM