Subhasish Saha
Subhasish Saha

Reputation: 13

Searching data using Ajax in CakePHP

I am using CakePHP 2.3.6. In one of my projects, I have to implement the Searching feture, using AJAX. Normally, this is working, but I want that the page won't reload, the result table will be immediately updated with the data.

This is the Controller code:

public function searchData(){
    $this->set(............);
    $this->set(............);
    $this->set(............);
    if($this->request->is('post')){
$this->layout='ajax';
$this->autoRender=false;
       if(!empty($data)){
          $data=$this->request->data;
          // Generating options
          .
          .
          .
          $result=$this->ModelName->find('all',$options);// "$options" is generated options
          if(!empty($result)){
$this->set(compact($result));
$this->set('_serialize',array('result'));
print_r(json_encode($result));
             $this->Session->setFlash("Searching Applicants Successful");
             $this->set('result',$result);
          }else
             $this->Session->setFlash("No data found");
       }else
          $this->Session->setFlash("You didn't give any info to search for");
    }
}

My View file(search_data.ctp) :

<h3>Search Result</h3>
<?php
    echo $this->form->create();
    echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
    echo $this->Form->submit('Search');
    echo $this->Form->end();
<div id="searchResult">
<?php if(!empty($result)){?>
       <table class="table table-striped table-bordered table-hover">
           <thead>
              <th>Field 1</th>
              <th>Field 2</th>
              <th>Field 3</th>
              <th>Field 4</th>
           </thead>
           <tbody>
<?php foreach($result as $applicant){?>
               <tr>
                  <td><?php echo $result['ModelName']['field1'];?></td>
                  <td><?php echo $result['ModelName']['field2'];?></td>
                  <td><?php echo $result['ModelName']['field3'];?></td>
                  <td><?php echo $result['ModelName']['field4'];?></td>
               </tr>
<?php }?>
           </tbody>
       </table>
<?php
     }else
        echo "No data found";
?>
</div>

Here, what I want is, when I submit the form, the "result" div will immediately appear, with the result data, organized in the table. I want to use Ajax here, so that users will get the result immediately, it'll improve the performance and user experience.

I've seen some youtube videos, where they load another page with the result, and shows that page in a div (it is called "success" div most of the time :) ), using Ajax. I can do it. But, I just want to do everything in 1 page, I don't want to use 2 pages to do it.

I tried this for ajax request and update my "result" div(in my search_data.ctp file) :

$this->Js->get('.search-form')->event('submit',$this->Js->request(array('controller'=>'cntrlr_name','action'=>'searchData'),array('async'=>true,'update'=>'#searchResult')));

And when I run the page, this is the output :

[{"Applicant":{"id":"3","name":"Name 2","email":"[email protected]","mobile":"9082730572","contact_phone":"3465360980","office_phone":"2437845693","correspondence_address":"Correspondence Address 2","permanent_address":"Permanent Address 2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"},"ApplicantAcademicQualification":[{"id":"2","applicant_id":"3","level":"Bachelor(Pass)","degree_title":"B.A.","passing_year":"1999","institution":"Institution 2","result":"4.2","major":"Bengali Literature","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantEmploymentHistory":[{"id":"2","applicant_id":"3","employer":"Employer 2","position_held":"Position 2","industry":"Industry 2","department":"Department 2","major_responsibilities":"Responsibility 2","job_location":"Local","key_achievement":"Achievement 2","served_from":"1999-08-15","served_till":"2010-02-12","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantOther":[{"id":"2","applicant_id":"3","academic_activities":"Academic Activities 2","non_academic_activities":"Non Academic Activities 2","main_reason_for_applying":"Reason 2","worked_before":"0","last_position":"","work_location_constraint":"1","ready_to_join_on":"2008-08-14","expected_salary":"30k+","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantProfessionalQualification":[{"id":"2","applicant_id":"3","name_of_certificate":"Certificate 2","institute":"Institute 2","from":"2002-10-17","to":"2007-10-12","location":"Local Ins.","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantTraining":[{"id":"2","applicant_id":"3","title":"Title 2","institute":"Institute 2","training_year":"1995","location":"In Company","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}]},{"Applicant":{"id":"2","name":"Name 1","email":"[email protected]","mobile":"715414918934","contact_phone":"2357295090","office_phone":"083656987398","correspondence_address":"Address 1_1","permanent_address":"Address 1_2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"},"ApplicantAcademicQualification":[{"id":"1","applicant_id":"2","level":"Secondary","degree_title":"S.S.C","passing_year":"2009","institution":"Institute 1","result":"4","major":"Science","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantEmploymentHistory":[{"id":"1","applicant_id":"2","employer":"Employer 1","position_held":"Position 1","industry":"Industry 1","department":"Department 1","major_responsibilities":"Responsibilities 1","job_location":"Local","key_achievement":"Achievements 1","served_from":"2005-03-12","served_till":"2007-11-26","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantOther":[{"id":"1","applicant_id":"2","academic_activities":"Academic Activities 1","non_academic_activities":"Non Academic Activities 1","main_reason_for_applying":"Reason 1","worked_before":"1","last_position":"Last Position 1","work_location_constraint":"1","ready_to_join_on":"2008-07-10","expected_salary":"20k-25k","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantProfessionalQualification":[{"id":"1","applicant_id":"2","name_of_certificate":"Certificate 1","institute":"Institute 1","from":"2011-10-11","to":"2012-09-11","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantTraining":[{"id":"1","applicant_id":"2","title":"Title 1","institute":"Institute 1","training_year":"2013","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}]}]

Is it possible ? How can I do it ? Please help me.

Thanks.

Upvotes: 0

Views: 3938

Answers (2)

decodingpanda
decodingpanda

Reputation: 594

update your function searchData:

  public function searchData(){
      //just empty for showing the form only
  } 

add ajax function:

  public function ajax_search(){
   $this->layout="ajax";
   $result = array();
   $field1 = $_POST["field1"];
   $field2 = $_POST["field2"];
   $field3 = $_POST["field3"];
   $field4 = $_POST["field4"];
   if( $field1 &&  $field2 &&  $field3  &&  $field4 ){ //change this depending on your queries
         $data=$this->request->data;
         // Generating options
         .
         .
         .
         $result=$this->ModelName->find('all',$options);// "$options" is generated option
    }
    $this->set("result", $result);
   }

add view ajax_search.ctp:

  <?php if($result):?>
  <table class="table table-striped table-bordered table-hover">
          <thead>
             <th>Field 1</th>
             <th>Field 2</th>
             <th>Field 3</th>
             <th>Field 4</th>
          </thead>
          <tbody>
         <?php foreach($result as $applicant){?>
              <tr>
                 <td><?php echo $result['ModelName']['field1'];?></td>
                 <td><?php echo $result['ModelName']['field2'];?></td>
                 <td><?php echo $result['ModelName']['field3'];?></td>
                 <td><?php echo $result['ModelName']['field4'];?></td>
              </tr>
          <?php }?>
          </tbody>
      </table>
   <?php else:?>
      No results.
  <?php endif;?>

update you searchData.ctp:

 <h3>Search Result</h3>
 <?php
    echo $this->Form->create("Search",array("default"=>false, "id"=>"SearchForm"));
    echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
     echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
    echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
    echo $this->Form->submit('Search');
   echo $this->Form->end();
   <div class="result">
;?>

<script type="text/javascript">
 $(document).on('submit','#SearchForm',function(){
     $.ajax({
   type: "POST",
   data:{
      field1:$("#SearchField1").val, // the ids of your input or you can modify these if you have assigned ids to the input
         field2:$("#SearchField2").val,
         field3:$("#SearchField3").val,
         field4:$("#SearchField4").val
  },
      beforeSend: function(){
        $("#result").html("loading...");
      }
  url: "<?php echo $this->base;?>/{insert your controller name here}/ajax_search/",
  success:function(data) {
         $("#result").html(data);
      }
   });              
}); 
</script>

Upvotes: 1

Salines
Salines

Reputation: 5767

Here are the steps:

Here is an example of how to use jQuery templates, and here it's documentation

Here is another approach

UPDATE

simple return json results from your search method:

public function searchData(){
$this -> layout = 'ajax';
$this -> autoRender = false;
if($this->request->is('post')){
   if(!empty($data)){
      $data=$this->request->data;
      // Generating options
      ...
      $result = $this->ModelName->find('all',$options);// "$options" is generated options
      $this -> set(compact($result));
      $this -> set('_serialize',array('result'));
      echo json_encode($result);
    }
  }
}

Use and loop JSON results data

Upvotes: 0

Related Questions