1

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');
            }
}
1
  • what's your expectation ? Commented Jul 4, 2019 at 6:39

3 Answers 3

1

Once a PHP script finished running and the browser receives the end of the HTML response, it's over, you can't directly modify the output already sent with more PHP. What you can do it use AJAX to get the data and render it on the client side using JS, or render it on the server side and just inject the result with JS.

Client rendering

For this you just need your PHP script to return the data, then loop over it and append each item to your div in JS. It's a bit awkward to render things with native JS but this approach keeps the presentation in one place instead of having HTML code on your backend.

Server side

$data=array(
    'title'=>$title,
    'firstname'=>$firstname,
    'middlename'=>$middlename,
    'surname'=>$surname
);

echo json_encode($data);

Client side

xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState==4) {
      var data = JSON.parse(xmlHttp.responseText);
       document.getElementById('responseG').style.display="block";
             if(data.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";
            for(var i = 0; i < data.length; i++){ 
                document.getElementById('responseG').innerHTML+= '<p>'+data[i]+'</p>;
            }
        }
    }
}

Server rendering

Here we use PHP to generate the HTML string on the backend, send it back via AJAX and just append it to the div on the client side. The disadvantage here is mixing HTML templates with your backend code.

Server side

$data=array(
    'title'=>$title,
    'firstname'=>$firstname,
    'middlename'=>$middlename,
    'surname'=>$surname
);
$html = '';

foreach ($data as $key => $item) {
    $html += '<p>'.$item.'</p>';    
}

echo json_encode(array('html' => $html));

Client side

xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState==4) {
      var data = JSON.parse(xmlHttp.responseText);
       document.getElementById('responseG').style.display="block";
             if(data.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 = data.html;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In your php code after you have done all the checks and populated your response array just do a simple echo to return that data to ajax.

Example in php: echo json_encode($status);

The best place to put this code is under your if statement

4 Comments

I have received the array in ajax. I want to pass that ajax array to a div in PHP. And use that ARRAY as foreach($array as $row){ echo $row; }
You can't just use an array as a string, you will need to loop trough that array to get each error message and display it in a div.
In order to do that in javascript: var js = JSON.parse(status); for(var x = 0; x < js.length; x++){ document.getElementById('responseG').innerHTML+= js[x]; ] Something like this will do
var array= xmlHttp.responseText -- I have got array in var array I have a div in php file as <div id="response"> </div> where the array is got and splited. My question is how to pass that json array to PHP now
0

Print error message on form

                <?php  
            if(!empty(validation_errors())) {echo 
                validation_errors();}
            ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.