简体   繁体   中英

Show form submitted data values with PHP validation without refresh

I'm trying to figure out how to make some data available for editing right after submission when it is submitted via HTML form and stored as a cookie...

On top, form validation:

<?php
//check if form was sent
if(isset($_POST['send'])){
  //some basic validation
  if(strlen($_POST['myname']) > 2){ 
    //set the cookie if passed
    setcookie('myname', $_POST['myname']);
  }
} 
//set error if didn't pass validation
else {
  $error[] = 'Your name is required!';
}
?>

So if a user posts data it will catch it and store it in a cookie. and If not, an error will be given:

<?php
  //check for errors
  if(isset($error)){
    foreach($error as $error){
     echo '<p style="background: red;">'.$error.'</p>';
    }
  }
?>

The HTML form with PHP:

<form method="post">
  <input name="myname" type="text" value="<?php if(isset($_COOKIE["myname"])){ 
  echo $_COOKIE["myname"];} ?>" placeholder="Your Name">
  <input name="send" type="submit" value="send">
</form>

This used for collecting data and sending it to pass PHP validation in order to set a cookie. if the cookie is already set, I want it to show the value with the inline PHP code.

What happens is when the form is submitted the cookie is stored but the user will can see it only after refreshing the page, I could add header("Refresh:0"); but it doesn't solves the problem since the error massage will not show when refreshed.

I need to use it for few of those forms so currently I'm looking for a fast and simple solution in PHP but it can also be a suitable Jquery/AJAX snippet.

You can do this only via jquery, ajax

to get cookie value -

Jquery var ckVal= $.cookie("cookiename")

javascript -

function readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') c = c.substring(1, c.length);
                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
            }
            return null;
        }

1st : As you mentioned in comment Both form and php code in same page so simple submit the form like this . No need ajax .

2nd : if any error means you simple show the error message and place the submited value in value attribute like this

value="<?php if(isset($_POST['myname'])){ echo $_POST['myname']; } ?>"

PHP :

<?php

if(isset($_POST['send'])){

  if(strlen($_POST['myname']) > 2){ 

   // here you can do whatever you want 
   // header('Location:next_page.php');

  }else{

     $error[] = 'Your name is required! and it should be minimum three character ';
  }


}  

  if(isset($error)){
    foreach($error as $error){
     echo '<p style="background: red;">'.$error.'</p>';
    }
  }
?>

The HTML form with PHP:

<form method="post">
  <input name="myname" type="text" value="<?php if(isset($_POST['myname'])){ 
  echo $_POST['myname']; } ?>" placeholder="Your Name">
  <input name="send" type="submit" value="send">
</form>

In Web2, We can do this by using AJAX. Simply hit ajax on form sumbit and

$('#submit_btn').on('click', function (e) {
    e.preventDefault();
    var $this = $('#form_id');
    $.ajax({
        url: 'setcookie.php',
        data: $this.serialize(),
        dataType: 'html',
        type: 'POST',
        beforeSend: function () {
            // show loader
        },
        success: function (html) {
            // Show success message
            // Set value of input elements by reading cookie in JS
        },
        error: function () {
            // Show ValidationError
        }
    }); });

In cookie.php put server side validation on form input.You can make ajax on same page also if you wanna put code on same page.

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