I am making a small search functionality where i have placed .ctp files into elements so that i can achieve ajax post without reloading the entire page and only render the element.
The element is very simple, it creates a li item with request data passed from the controller.
<li class="span2">
<a class="pull-left" href="">
<img class="media-object" src="<?php $img_path = $result['Person']['profile_image']; echo $img_path;?>">
</a>
<div class="media-body">
<label class="person-media">
<?php
$firstName = ucfirst($result['Person']['first_name']);
$lastName = ucfirst($result['Person']['last_name']);
echo $firstName;
echo "<br>";
echo $lastName;
?>
</label>
</div>
In my search action, i want to keep the entire skeleton (header, footer, search div holder) and just render the list items in the unordered list. But on search click, the entire page loads
Here i am attempting to set the data
//transform POST into GET
if($this->request->is("post")) {
$url = array('action'=>'manage');
$filters = array();
if(isset($this->data['searchFor']) && $this->data['Search.name']){
//maybe clean up user input here??? or urlencode??
$filters['Search.name'] = $this->data['Search.name'];
}
//redirect user to the index page including the selected filters
$this->redirect(array_merge($url,$filters));
}
$conditions = array();
//
// filter by name
//
if(isset($this->passedArgs['Search.name'])) {
$conditions["Person.first_name LIKE"] = "%".$this->passedArgs["Search.name"]."%";
}
//paginate as normal
$this->paginate = array(
'conditions' => $conditions,
'order' => array('Person.first_name ASC'),
'limit' => 12
);
$this->layout = "main";
$this->set("results",$this->paginate("Person"));
**$this->render('manage');** // rendering on the element loads everything
After finding my results from the query, manage.ctp loads everything.
</div>
<ul id="students-list" class="students-ist">
<?php
if(!empty($results)){
foreach($results as $result){
echo $this->element('singleuser', array('result' => $result));
}
}
?>
</ul>
How can i using Ajax and form submission load just an element inside a div without reloading the entire page on every search.
There are several ways to get part of a full page from server and place only parts of it into page in browser.
Following is submit handler for search form that will make AJAX call. WIthin the AJAX complete callback will replace student list items with new ones
Once you get Cake controller returning just the LI’s you want, you can dump response straight into the list: