开发者

php - multiple validations

I am making a web form and I am validating the inputs via ajax. For every keypress on an input tag, the value is sent to a php file where its checked for numeric value etc. This was easy, I just have it echo back a error message response which is displayed. On this same keypress, I also want it to check if ALL the input values are != "" so that the person can't leave an entry blank. I am trying to have it control whether or not the submit butto开发者_开发技巧n works. This is where I get stuck. Is there a way to send two things back in an ajax request? I tried using the php session object but it wouldn't work the way I wanted (since ajax isn't updating the entire page.)


Yes you can. Two options:

1 - quick and dirty - you could send a string back with the two items you need. You would need to concatenate the two items you need to send back into one string. Your onSuccess function would then split the string into the two items you want.

2 - elegant solution - you can create a JSON object in the server and send it back. A JSON string is something like foo = { "var1" : "response1" , "var2" : "response2" }. In your client-side script you would reference var1.response1 and var2.response2. See below one example using Mootools (a well-known javascript library) and PHP:

javascript code (client):

var params = "id=123&page=1&product=12"; //anything you need to pass to the server
var myRequest = new request.JSON({url:"url of your server script", onSuccess: function(result) {alert(result.response1); alert(result.response2);}).post(params);

PHP code (server):

 $a["response1"] = response1; //first thing you need to pass back
 $a["response2"] = response2; //second thing you need to pass back
 echo json_encode($a); // this will convert $a array to a json string

I hope this helps. Good luck!


You should use json for this one.

$errors = array('Error1', 'Error2');
echo json_encode($errors);


You could attach an onsubmit handler to the form that returns a boolean for success/failure.


<script>
function myValidation(){
 /*

 Your AJAX validation call here.

 */
 if(valid){
    return true;
 }else{
    return false;
 }
} 
</script>
<form onsubmit="return myValidation();">
    <input type="submit" name="submit" value="Submit" />
</form>

If the validation returns false, the form will not submit. A return of true allows the form to process as necessary.


Why aren't you doing this with straight jQuery? It seems ridiculous to make an ajax call to validate a form through PHP while the user is filling it out. Validate the data after submission with PHP, not during.

That is unless you need to match the input to something in the database, but it doesn't sound like that's the case here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜