Decode JSON package from PHP using AJAX
I am building a simple login system. I do not want the page to reload when the user submits the form, in case there is an error, and I need to seamlessly display an error message (Like wrong password). When the users submits the data, AJAX passes it onto the submit.php script. This script validates the data and then sets a JSON object to a number 1-3 based on what is wrong or right with the submitted credentials. I don’t know how to have the AJAX call, decode the JSON, and then have some if
statements that decide what to do based on the value of that JSON.
Below is the code I am using for the form.
HTML:
<form method="post" id="myForm"> <h1 class="title" unselectable="on">Login</h1> <input placeholder="Username" type="text" name="username" class="form" id="username"/> </br> <input placeholder="Password" type="password" name="password" class="form" id="password"/> </br> <input class="button" type="button" id="submitFormData" onclick="SubmitFormData();" value="Submit"/> </br> </form>
JS/AJAX (Same page):
function SubmitFormData() { var username = $("#username").val(); var password = $("#password").val(); $.post("submit.php", { username: username, password: password}, function(data) { $('#results').html(data); $('#myForm')[0].reset(); }); }
Next is the PHP (submit.php). The PHP will look at the incoming data from the AJAX script, and then assign an error number to a JSON object depending on what is wrong with the credentials.
$username = mysqli_real_escape_string($connect, $_POST["username"]); $password = mysqli_real_escape_string($connect, $_POST["password"]); $query = "SELECT * FROM users WHERE username = '$username'"; $result = mysqli_query($connect, $query); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_array($result)) { if(password_verify($password, $row["password"])) { $Obj->error = "three"; $myJSON = json_encode($Obj); } else { $Obj->error = "two"; $myJSON = json_encode($Obj); } } } else { $Obj->error = "one"; $myJSON = json_encode($Obj); } //error one=user not found //error two=wrong password //error three=all detials are correct
Now, the trouble I am having is back at the main page where the user is. I want the JS to look at the $myJSON variable and decide what to do based on that. I have written some pseudo code below, but I don’t know if or how I can do this in JS or AJAX.
decode JSON package if error=one, do something if error=two, do something else if error=three, run a php script that sets some session variables. (Is it possible to run php inside of JS?)
Any help accomplishing these results would be greatly appreciated.
This is a vanilla javascript solution:
const xmlhttp = new XMLHttpRequest; xmlhttp.onreadystatechange = function() { if (this.readyState === 4 && this.status === 200) { //passes results to a function start(JSON.parse(this.responseText)); } } xmlhttp.open("POST", "PHP WEBSITE URL", true); //sends the request with a FormData object based on the form xmlhttp.send(new FormData(document.getElementById("myForm"))); function start(object) { alert(object); }
For this to work, your PHP script will have to echo
your result object. Example:
if ($_POST["username"] === "correctUsername" && $_POST["password"] === "correctPassword") { //echo javascript object echo json_encode(['success'=>true]); } else { //echo javascript object echo json_encode(['success'=>false]); }
Obviously it needs to be more complex but this is the idea.
I have made login pages before and instead of returning a success I used the current PHP page as the main one and echoed the info to fill the page as well as credentials that can be used with AJAX requests. Hopefully this helps.