I have a general info form. When I click on submit, all values are got using javascript and send it to PHP function using ajax. The PHP function validates the form and returns EITHER form errors as an array OR successful message.
I want to get the array generated by PHP on ajax side and pass it to the form to display the errors on respective form fields.
I have successfully generated the array of errors in PHP. print_r($arrayname) shows all the values as an array. But I don't want to show instead I want to pass it to ajax and retrieve the array in a div and do work on that array.
--------- AJAX ------
function general()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open('POST','addGeneral',true);
var data = new FormData();
data.append('title',document.getElementById('title').value);
data.append('firstname',document.getElementById('firstname').value);
data.append('middlename',document.getElementById('middlename').value);
data.append('surname',document.getElementById('surname').value);
xmlHttp.send(data);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState==4)
{
var status = xmlHttp.responseText;
document.getElementById('responseG').style.display="block";
if(status=='true')
{
document.getElementById('responseG').className="alert alert-success";
document.getElementById('responseG').innerHTML="<p>Successfully Updated</p>";
}
else
{
document.getElementById('responseG').className="alert alert-danger";
document.getElementById('responseG').innerHTML=status;
}
}
}
}
---- PHP FUNCTION ---
public function addGeneral()
{
$status=array();
extract($_POST);
$this->form_validation->set_rules('title','Title','required',array('required' => 'You must provide a %s.'));
$this->form_validation->set_rules('firstname','First Name','required');
$this->form_validation->set_rules('middlename','Middle Name','required');
$this->form_validation->set_rules('surname','Surname','required');
if($this->form_validation->run()===FALSE)
{
$status=$this->form_validation->error_array();
}else
{
$data=array(
'title'=>$title,
'firstname'=>$firstname,
'middlename'=>$middlename,
'surname'=>$surname
);
$this->Manage_employee_model->update_employee($data);
$status=array('true');
}
}