I’m using cakePHP 1.3 and would like to use AJAX from my search view to the search action in my controller. I was using prototype and scriptaculous and it was working fine, but need to use purely jQuery.
The search action basically looks as follows:
public function search() {
if (empty($this->data)) {
} else {
$request = $this->data;
$this->set('data', $this->Event->search($request['Event']['search']));
}
}
The view currently looks like:
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var searchString = $("#search_box").val();
var data = searchString;
if(searchString) {
$.ajax({
type: "POST",
url: "/events/search",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
<div id='container'>
<h1>Corporate Events</h1>
<form method="post" action="search">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
<div id="searchresults">Search results :</div>
<ul id="results" class="update">
What is the best way to make the ‘data’ variable available to $this->data in the controller? I checked the other threads with similar questions, but was unable to see how to do this.
Thanks!
Send it as POST ( refer to http://api.jquery.com/jQuery.post/ ) or url_encode (google “javascript url encode”) the string and append it to the url. Not sure which was is better, both should work and be easy to implement.