Can't seem to get Prototype AJAX form validation to work in conjunction with Codeigniter
Is there some kind of trick involved? Here's how I would envision it working:
User tries submitting the form
Event.observe captures this and sends an AJAX request to a special validation URL (PHP using Codeigniter)
If no errors were returned, continue submitting the original form
If errors were found, cancel form submission and display
Mostly, I can't seem to get a separate AJAX validation request to work as the form continues submitting. I could use Event.stop(event)
, but have not found a way to re-start the process if no validation errors exist from the validation call. I'd post code, but I have about 15 examples of things I've tried and it would just clutter this question.
Any ideas? I didn't think form 开发者_开发技巧validation would be this difficult.
Finally got this figured out! Here's my final JS code. While the form itself submits to "/search/result/keyword" as the default action, validation is an entirely different "/search/validate/searchkeyword" URL.
<script type="text/javascript">
Event.observe(window, 'load', function()
{
Event.observe('searchkeyword', 'submit', function(event)
{
Event.stop(event);
new Ajax.Request('/search/validate/searchkeyword',
{
method: 'post',
parameters: $('searchkeyword').serialize(true),
onSuccess: function(t)
{
var response = t.responseText || "ERROR|An error has occurred.";
var responsearray = response.split('|');
if( responsearray[0] == 'ERROR' ) { document.getElementById('searchkeywordvalidate').innerHTML = responsearray[1]; }
else { $('searchkeyword').submit(); }
},
onFailure: function() { document.getElementById('searchkeywordvalidate').innerHTML = 'An error has occurred.'; }
});
});
});
</script>
I am little confused with the description of your process. The user submits the form. Your javascript captures the onlcick, and then sends and ajax request to the server. i.e. an HTTP request object has been sent. Now the server does some processing (validation using Codeignitor). You say if no errors are returned, does this mean to the client or no errors are returned from the validation? You should not be returning to the client if no validation errors occurred. You just continue on with the server side processing at this point. So there is no need to "resubmit" the form for submission. The server already has everything it needs in the POST array.
If there are errors then yes you would return an HTTP response object with some type of HTML or JSON, etc that the javascript could then parse and display back to the user. Then they would need to reclick the submit button starting the process all over again.
精彩评论