questions

PHP Cannot get post data from form

Rate this post

I want to submit a form that user fill up their information to an api. I have created a wordpress plugin to do it. The problem that I am currently facing is when I call $_POST["registerId"] or $_POST["password"] it is empty value.

The following code is all belong to the same page. This function consist of the form and it will call javascript to do validation.

function registration_form_layout() {

    ?>

    <h2>Registration Form</h2>

    <script type="text/javascript">function validate() {

            // Prevent trigger and initialize error
            event.preventDefault()
            var error=""
            var isError = false

            // Retrieve value of the uid, password and confirm password field
            var uid = document.getElementById("form-uid").value;
            var password = document.getElementById("form-password").value;
            var confirmPassword = document.getElementById("form-confirm-password").value;

            // Field declaration
            var uidField = "form-uid"
            var uidErrorField = "error-message-uid"

            var passwordField = "form-password"
            var passwordErrorField = "error-message-password"

            var confirmPasswordField = "form-confirm-password"
            var confirmPasswordErrorField = "error-message-confirm-password"

            var firstUIDCharacter = uid.charAt(0)


            initializeField();

            if ( uid === "" || uid.length < 6 || uid.length > 15 || (firstUIDCharacter >= '0' && firstUIDCharacter <= '9') ) {
                error = "Please enter correct UID"
                generateErrorField(uidField, uidErrorField, error)
                isError = true
            } 

            if ( uid.match(/\d{3,}/) ){
                error="UID last three characters cannot be all numbers"
                generateErrorField(uidField, uidErrorField, error)
                isError = true
            }

            if ( password === "" || password.length < 6 ) {
                error = "Please enter correct password"
                generateErrorField(passwordField, passwordErrorField, error)
                isError = true
            } 

            if ( confirmPassword === "" ) {
                error = "Please enter correct password"
                generateErrorField(confirmPasswordField, confirmPasswordErrorField, error)
                isError = true
            }

            if ( password !== confirmPassword ) {
                error = "The two inputs must be consistent"
                generateErrorField(passwordField, passwordErrorField, error)
                generateErrorField(confirmPasswordField, confirmPasswordErrorField, error)
                isError = true
            }

            if ( password.length > 5 && ( password.match(/^-?\d+$/) || password.search(/[a-zA-Z]/) === -1 ) ) {
                error = "Password must contain both letters and numbers"
                generateErrorField(passwordField, passwordErrorField, error)
                generateErrorField(confirmPasswordField, confirmPasswordErrorField, error)
                isError = true
            }

            if (isError) {
                return false
            } else {
    
                var result = "<?php echo submit_registration(); ?>"
                console.log(result)
                
            }
        }

    </script>
    <p id="php_code"></p>

    <form method="POST" id="registration-form" onsubmit="return validate()">
        <label>UID</label>
        <br/>
        <input type="text" name="registerId" id="form-uid" class="form-control" placeholder="Please enter your login ID"/>
        <p id="error-message-uid" class="error"></p>

        <label>Password</label>
        <br/>
        <input type="password" name="password" id="form-password" class="form-control" placeholder="Please set the new password"/>
        <p id="error-message-password" class="error"></p>

        <label>Confirm Password</label>
        <br/>
        <input type="password" name="confirm_password" id="form-confirm-password" class="form-control" placeholder="Please confirm the new password"/>
        <p id="error-message-confirm-password" class="error"></p>
        <br/>

        <br/>
        <input type="submit" name="form_submit" id="submit-registration" class="form-control" value="Next"/>
        <br/>
    </form><?php
}
add_shortcode('register_form','registration_form_layout');

This part of the code will trigger the api and use the $_POST data to submit the data to the api.

function submit_registration() {

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL,"https://localhost/testing/register");
    curl_setopt($ch, CURLOPT_POST, 1);

    $payload = json_encode( 
        array( 
            "Password"=> $_POST["password"], 
            "RegId"=> $_POST["registerId"], 
        ) 
    );

    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload );
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    $server_output = curl_exec($ch);
    $error    = curl_error($ch);
    $errno    = curl_errno($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $test = json_decode($server_output, JSON_PRETTY_PRINT);

    echo '<pre>UID: '.$_POST["registerId"].'Password: '.$_POST["password"].'Server Output:'.status_message($test['Status']);

    curl_close ($ch); 
}

Update: I am required to use curl because if i use ajax. cors origin error will keep appearing.

 

✔️Solution:

As mentioned in the comments, You cannot mix JavaScript and PHP like this. The structure has to be rewritten completely.

First, create a PHP file called submit_registration.php, under the plugin directory, contents are as follow:

<?php
// TODO: Add POST isset check and data cleansing
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"https://localhost/testing/register");
curl_setopt($ch, CURLOPT_POST, 1);

$payload = json_encode( 
    array( 
        "Password"=> $_POST["password"], 
        "RegId"=> $_POST["registerId"], 
    ) 
);

curl_setopt($ch, CURLOPT_POSTFIELDS, $payload );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);
$error    = curl_error($ch);
$errno    = curl_errno($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$test = json_decode($server_output, JSON_PRETTY_PRINT);

echo '<pre>UID: '.$_POST["registerId"].'Password: '.$_POST["password"].'Server Output:'.status_message($test['Status']);

curl_close ($ch); 
?>

Then, in your registration form, change the <form> tag to the following:

<form action="<?php echo plugins_url( 'submit_registration.php', __FILE__ ); ?>" method="post" onsubmit="return validate()">

and in the validate() JS function, you can just return true or false based on the validation result. Don’t submit a form inside the function.

Side Notes:

  • Your HTML structure has problems too
  • in cURL request, the json_encode() is optional
  • You should refer to WordPress plugin development guideline to construct your plugin.

Leave a Reply

Your email address will not be published.

Back to top button