Damodar Bhattarai
Damodar Bhattarai

Reputation: 59

How to get PHP array as responseText in ajax to pass it to certain div from ajax later

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');
            }
}

Upvotes: 1

Views: 791

Answers (3)

ppajer
ppajer

Reputation: 3145

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;
        }
    }
}

Upvotes: 1

Balaji Admane
Balaji Admane

Reputation: 26

Print error message on form

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

Upvotes: 0

Igor Ilic
Igor Ilic

Reputation: 1368

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

Upvotes: 0

Related Questions