简体   繁体   中英

PHP Validation using AJAX / JSON

My validation is in my php script encoded in json, I'm not sure how to implement it in my main JavaScript function. I'm using regular expressions to in my php script to validate the form criteria, I need to pass this to the JavaScript file and return a success massage for for each form id.
this is what I have so far.

 $(document).ready(function() { $("#submit").click(function() { // Clear any success or error messages $("#success").html(""); $("#errors").empty(); //make an AJAX call here, and set error or success accordingly $.post('backend.php',{act:'validate'}, function(getData) { //unsure about this function } }); // prevents submit button default behavior return false; }); }); 
 <html> <head> </head> <body> <h1>Form Validation</h1> <form id="PersonForm"> Name: <input id="name" type ="text" name="name"></input> <br><br> Postal Code: <input id="postal" type ="text" name="postal"></input> <br><br> Phone Number: <input id="phone" type ="text" name="phone"></input> <br><br> Address: <input id="address" type ="text" name="address"></input> <br><br> <input type="submit"></input> </form> <div id= "content"></div> <a href="frontend.html">Refresh</a> <a id="InsertDefault" href="#">Insert Default Data</a> <br><br> <p id='msg'></p> <ul id="errors"></ul> <p id="success"></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="main.js" type="text/javascript"></script> </body> </html> 

<?php
if ($_REQUEST['act'] == 'validate')
{
  $validateData = array();
  if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
  else $validateData['name'] = 0;

  if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
  else $validateData['phone'] = 0;

  if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/", $_REQUEST['postal'])) $validateData['postal'] = 1;
  else $validateData['postal'] = 0;

  if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/", $_REQUEST['address'])) $validateData['address'] = 1;
  else $validateData['address'] = 0;

  echo json_encode($validateData);
}
else echo "Should not happen";
?>

Well, this would be better suited for an actual ajax call set up like this (Not Tested)

// Set values
var values = {};
values.act = "validate";
values.name = $('[name="name"]').val();
values.phone = $('[name="phone"]').val();
values.postal= $('[name="postal"]').val();
values.address= $('[name="address"]').val();

$.ajax({
    type: 'POST',
    url:'backend.php',
    data: values,
    dataType: 'JSON',
    success: 
    function(result)
    {
        // Here you can access the json object like this and
        // do whatever you like with it
        console.log(result.name);
        console.log(result.phone);
        console.log(result.postal);
        console.log(result.address);    
    }
});

I'm not 100% sure on what you're looking for, but does this work for you? Basically we stringify the object (see my comment about parseJSON) and look for any 0's and submit the form if there aren't any. If there are any 0's we iterate through each key/value pair and push the errors in to an array, then do something with each error, like drop them in the error area. Does that work for you?

var getData = {
    name:1,
    phone:1,
    postal:0,
    address:1
}
//if your info isn't looking like this, you may need to look in to $.parseJSON here http://api.jquery.com/jquery.parsejson/

if (JSON.stringify(getData).indexOf('0') == -1) {
    alert('all good!');
    //$('#PersonForm').submit();
}
else {
    var errorArr = [];
    $.each(getData, function(k, v) {
        if (v == 0) {
            errorArr.push('theres a problem with '+k);
        }
    });
    for (var i = 0; i < errorArr.length; i++) {
        alert(errorArr[i]);
    };
}

Good luck!

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