-2

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Olu
  • 63
  • 1
  • 9
  • Why you are using `then` if you are `awaiting fetch`? Here is how to use fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – CodeThing Jul 21 '23 at 07:40
  • Noted and thanks. But still doesn't move the needle. Jquery method works fine using the same php file. So why isn't the js fetch or await doing same? What error is in the code that prevents execution of php fle to the end? – Olu Jul 21 '23 at 10:34

1 Answers1

-1

I just found a solution to above again through stackoverflow How do I post form data with fetch api? (many thanks). This solution works whether html form is used or not. And the solution is to use Formdata to post to server. This method works fine with the php file. Below is the code:

const submitHandler = async (event) => {
event.preventDefault();
let formData = new FormData();
formData.append('user', user);
formData.append('request', request);
formData.append('code', code);

fetch("php/sign_in/signup.php", {
    body: formData,
    method: "post"
})
//use text for alphanumerical response. json() does not recognize (string) 'ok'
.then(response => response.text()) 
.then(data => {
    console.log(data);
    if (data == 'Access denied') alert('Error connecting to server');
    if (data == 0) alert('Wrong/expired code');
    if (data == 'ok') alert('Great. U just made it');
})
.catch(err => console.log(err));    

};

Olu
  • 63
  • 1
  • 9