简体   繁体   中英

Handling Ajax Form Validation with PHP

So this is going to sound like a very noob question but I am just beginning with ajax and need some help.

When an Ajax post sends values to a PHP script for validation and the validation fails, due to say an invalid password, must that PHP script then post back the values of the error messages with another ajax post?


Okay I think I phrased this question very incorrectly so I am just updating it to make it more understandable.

I have a wordpress plugin which creates a contact form and then validates all the data through javascript before making an ajax post to a separate PHP script for validation. What I seem to be not understanding is if the data fails validation in the PHP script, how then do I post back to the main page with error messages?

You have to make some kind of HTTP response.

That response won't be very useful if it doesn't tell the client what the errors with the request were.

There's nothing Ajaxy about the response as far as PHP is concerned, it is just a standard HTTP response.

For sure php should return a json response to the client.

You can place the messages in the response

<?php echo json_encode(array("valid" => false, "message" => "Invalid User")); ?>

or just place status codes and have the client side handle the error messages.

<?php echo json_encode(array("valid" => false)); ?>

<script>

   // I'm using jQuery here

   ...

   function(result) {

      var response = $.parseJSON(result);

      if(!response.valid){alert('Invalid User')}

   }

</script>

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