Fill multiple elements with a single jQuery Ajax call
I have this form that validates the fields on submit through ajax (using Codeigniter's Form_Validation Class).
<input type="text" name="field1" id="field1"> />
<span id="field1_error"></span>
....
<input type="text" name="field2" id="field2"> />
<span id="field2_error"></span>
...
<input type="text" name="field3" id=开发者_如何学JAVA"field3"> />
<span id="field3_error"></span>
<input type="submit" name="submit" id="btnPublish" />
On submit, jQuery calls CI's validation method. Which would be the best way to output those validation errors with a single Ajax Call?
Maybe this approach can help you.. its more like a hint than complete solution...
On server side you will do validation and return JSON (for example) - $progress is true/false - depending on validation result and $errors is array(name,translated_error/ or "")
partial php:
$res = array(
'progress' => $progress,
'errors' => $errors
);
$jsonReturn = json_encode($res);
//output result
header('Content-Type: text/html; charset=utf-8');
echo $jsonReturn;
partial jQuery:
var errorFields = $([]).add(field1_error).add(field2_error).add(field3_error),
mainFields = $([]).add(field1).add(field2).add(field3);
$('#btnPublish').button().click(function(event){
mainFields.removeClass('ui-state-error');
errorFields.val();
$.ajax({
type: 'POST',
url: your_url,
data: $('#your_form_id').serialize(),
async: false,
success: function (returned_value){
var obj = $.parseJSON(returned_value);
if (obj.progress==true){
alert('Validation successfull');
}else{
$.each(obj.errors, function(index, value) {
if (value!=""){ //it will skip those fields with no errors
$('#'+index).addClass(('ui-state-error'));
$('#'+index+'_error').val(value);
}
});
}//end return ajax
}//end ajax
});
});
精彩评论