I want to know more about fetch API or await promise to send user data to server and receive data from server based on data sent to the server. The server response will be custom built to enable user identify the errors and how to solve it. I know the jQuery method, it works fine but don't want to mix jQuery with reactjs.
The server response to the user is any of these strings:
Access denied, 0, ok
Based on my troubleshooting I suspect my error is how I pass the user data to the server. I may be wrong in my conclusion. Below are the PHP file, jQuery and js codes
<?php
require '../server_conn.php'; // holds the test_input()
//This is where the code stops, response sent to user: Access denied
if (empty($_POST["user"]) || empty($_POST["request"]) || empty($_POST["code"])) {
echo "Access denied";
die;
}
$user = test_input($_POST["user"]);
$request = test_input($_POST["request"]);
$code = test_input($_POST["code"]);
$sql = "SELECT code FROM requests WHERE user = '$user'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// code is not available
echo 0; die;
}
mysqli_free_result($result);
$sql = "INSERT INTO requests (user, request, code) VALUES ('$user', '$request', '$code')";
if (!mysqli_query($conn, $sql)) {
echo 0;
die;
}
$id = mysqli_insert_id($conn);
session_start();
$_SESSION["id"] = $id;
echo 'ok';
mysqli_close($conn);
?>
//using js fetch API: This is not working. I want to know why
const submitHandler = async (event) => {
event.preventDefault();
const userData = {user, request, code,};
await fetch('php/sign_in/signup.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(userData),
})
.then(res => res.json())//I also tried res.text()
.then(res => {
console.log(res); //For json() & text(), server response: Access denied
res == 'ok' ?
alert('Your request has been approved') :
alert('Access denied due wrong/expired code');
})
.catch(err => console.log(err));
};
//using jQuery: This works fine
const submitHandler = async (event) => {
event.preventDefault();
const userData = {user, request, code,};
$.post('php/sign_in/signup.php', userData, (data) => {
console.log(data);
data == 'ok' ?
alert('Your request has been approved') :
alert('Access denied due wrong/expired code');
});
};
I expect the response from the server to be in line with the PHP file. This is what jQuery does. With js however, the PHP code stops at when it checks if any of the input params is empty/null. I suspect it is the way I pass on the user data. I need to be corrected on this.