简体   繁体   中英

Using PHP cURL to POST JSON data

I am working on a three-tiered login system for school and am having trouble sending and receiving messages using JSON + POST. I have a front-end which accepts a username and password:

<div id = "login form" style="text-align: center">
    <input type="text" id="username" name ="username"><br>
    <input type="password" id="password" name ="password"><br>
    <button id="login"> Login</button>
<div>

and then POSTS it using AJAX to the "back of the front" - a PHP script. The PHP script on the front end simply shuttles the same message along to the middle, which shuttles it to the back-end which would query a database and return a result. I made the following PHP script for the front end:

header('Content-type: application/json');

    $middle_url = "https://myurl.edu/";
    $username = $_POST['username'];  //extract credentials
    $password = $_POST['password'];

    // load new array
    $credentials = array(
      'username' => $username, 
      'password' => $password
    );

    $ch = curl_init();  // curl handle 
    curl_setopt($ch, CURLOPT_URL, $middle_url . "test.php");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);  // load credentials to POST
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  // set return type to string
    $middle_reply = curl_exec($curl);  // execute curl and store response
    curl_close($ch);

    echo $middle_reply;

My issue is that when I run my HTML file, I get an empty string as a result and I'm not sure why.

I created a test file in which I hard-coded a return like so:

<?php
    header('Content-type: application/json');

    $response = array(
      'role' => 0
    );

    echo (json_encode($response));

?>

If I connect my HTML directly to this test file, I get the array that I am expecting, but when I try to route through my front-end PHP file first, I keep getting returned an empty string. Please someone help me.

EDIT: In case it's helpful, this is how I am POSTing the data from my HTML file:

<script>

        const form = {
          username: document.getElementById('username'),
          password: document.getElementById('password'),
          login: document.getElementById('login'),
        };

        form.login.addEventListener('click',validate);


        function validate() {

            var ajax = new XMLHttpRequest();

            ajax.onload = function() {
              if (this.status == 200) {
                console.log(this.responseText);
                const response = JSON.parse(this.responseText);

                if(response['role'] == 1){ 
                  location.href = 'teacher.html';
                }
                else if (response['role'] == 0)  {
                  location.href = 'student.html';
                }
              }
            };     

            const postData = `username=${form.username.value} password=${form.password.value}`;
            ajax.open('POST','login.php',true);
            console.log(postData);
            ajax.send(postData);
        }

</script>

You need to specify the format of the data you want to send in your ajax request.

It seems like you are close to the form urlencoded format, so you need to add this header:

ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
ajax.send(postData);

And your parameters must be separated by an ampersand & , not by a space:

const postData = `username=${form.username.value}&password=${form.password.value}`;

Additionally, you may want to escape your data with encodeURIComponent() , because at the moment, if your login or your password contains an ampersand, it will break the POST data format:

const username = `${form.username.value}` ;
const password = `${form.password.value}`
const postData = 'username=' +  encodeURIComponent(username) + '&password=' +  encodeURIComponent(password);

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