lonerunner
lonerunner

Reputation: 1322

Submit form POST to another page but validate before redirect and keep on same page if validation fails

Is there a php way to validate a form that goes submitted to another page before submitting and stay on same page if fields are not valid or if everything valid send post data to another page?

Example would be: I am on page somesite.com/orderitems and there would be form like

<form method="post" id="orderform" action="somesite.com/shoppingcart">
   <input type="number" name="numitems" id="numitems" value="1">
   <input type="date" name="date" id="date">
</form>

So google chrome for example already knows to validate if you put in input field required value and to validate date and number fields. I have also a jquery datepicker so user can select date easily, and also jquery validator to validate fields before submit, but all this can be overridden and/or fail at some point.

So end point would be validation in php when form is submitted.

But what i am stumbled upon is that i can't use GET request in getting data on somesite.com/shoppingcart so i must send POST to that page, but if some of the field fail to validate, like wrong date or wrong date format, than i shouldn't even go (redirect or post) to somesite.com/shoppingcart, instead i should stay on the page somesite.com/orderitems and display the errors.

So is there a solution to something like this, what suggestions would you recommend. Can i post form to the same page and validate fields if, all is good than redirect to another page and pass POST data, or stay on same page and display error?

Upvotes: 2

Views: 4248

Answers (2)

Giulio Bambini
Giulio Bambini

Reputation: 4755

I will show you how this can be done via JavaScript/Ajax and PHP. I think it won't be difficult to learn doing it from this tutorial, but if some questions arise I am ready to help you.

JavaScript/Ajax request

First of all, we need to add "Submit" button to form and set "sendData()" function as its "onclick" listener. Which means each time you click on "Submit" button, "sendData()" function will execute. Also, we need to add 'class' attribute to 'number' and 'date' input elements, to get their values in more cleaner way.

<form method="post" id="orderform" action="somesite.com/shoppingcart">
   <input type="number" class='myForm' name="numitems" id="numitems" value="1">
   <input type="date" class='myForm' name="date" id="date">
   <input type="Submit" value="Send" onclick = sendData(); return false;"/>
</form>

<script type="text/javascript">

function sendData()
{
    var formElements = document.querySelectorAll(".myForm"); // We use 'class' attribute to get form elements (number and date).
    var formData = new FormData(); // we create FormData object with which we can send data to "PHP" script (server side).
    for(var i = 0; i < formElements.length; i++)
    {
        formData.append(formElements[i].name, formElements[i].value);
    }
    //AJAX Starts Here
    var xmlHttp = new XMLHttpRequest(); // Create "ajax" object
        xmlHttp.onreadystatechange = function() //This is to wait for response from your PHP script
        {
            if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //And when status is OK use result
            {
                var responseText = xmlHttp.responseText; //here you save your response from server side.
                if(responseText["Status"] === "OK") //if you send from server side that "Status" is OK, then you can go to that page
                {
                    window.location.href = "somesite.com/shoppingcart";
                }
                else //otherwise you refresh page
                {
                    window.location.reload();
                }
            }
        }
        xmlHttp.open("POST", "somesite.com/shoppingcart"); //set page value, where you want to send form values
        xmlHttp.send(formData); //send actual data
}

</script>

PHP validation (to avoid manipulation/override on client-side)

When you validate values in server-side, set $_SESSION["Status"] = "OK". After that if someone tries to "hack" your page and "change" your JavaScript functions to navigate to somesite.com/shoppingcart page, you will check:

somesite.com/shoppingcart

<?php
    if($_SESSION["Status"] === "OK"])
    {
       //give permission
    }
    else 
    {
        return false;
    }
?>

Upvotes: 5

TarangP
TarangP

Reputation: 2738

i am also facing this problem. and i solve it by doing this

UPDATE

$(document).ready(function () {
    
    $('#orderform').validate({
        rules: {
            numitems: {
                required: true,
                number: true
            },
            date: {
                required: true,
                date: true
            }
        }
    });

    $('#orderform input').on('keyup blur', function () {
        if ($('#orderform').valid()) {
           $("#button1").removeClass("submit");
           //TRIGGER FORM 
           //$('#orderform').submit();
        }
    });

});
.submit{
  user-select: none;
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

<form method="post" id="orderform" action="somesite.com/shoppingcart">
   <input type="number" name="numitems" id="numitems"><br/>
   <input type="date" name="date" id="date"><br/>
   <span class="submit" id="button1">SUBMIT</span>
</form>

i Hope it helps.!

Upvotes: 0

Related Questions