Reputation: 549
I am trying to send some data on button click to a controller and display the response in a content div back in the view. However i am facing problem while sending the data to the controller. Here is what i am trying to do :
test.php
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "1"
},
success: function(response){
$('#content').html(response.first);
}
});
});
$("#btn2").click(function(event){
$.ajax({
type: 'GET',
url: 'get-response',
dataType: 'json',
data: {
"id": "2"
},
success: function(response){
$('#content').html(response.first);
}
});
});
});
</script>
<input type="button" id="btn1" value="Button1 Content" />
<input type="button" id="btn2" value="Button2 Content" />
<br>
<div id="content"></div>
route.php
Route::get('ajax-example', function(){
return View::make('test');
});
Route::get('get-response/{id}', array('as'=>'get-response', 'uses'=>'AjaxController@getResult'));
AjaxController.php
public function getResult($id){
if($id==1){
$content = "Hello";
}
else if($id==2){
$content = "World";
}
return Response::json(array('first'=>$content));
}
Error Can anyone please help me out here. I am a bit confused right now. Thanks :)
Upvotes: 0
Views: 2065
Reputation: 549
ok so i guess i figured it out what was causing the problem.
I changed my route to
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController@getResult'));
and in controller i added
public function getResult(){
$id = $_GET['id'];
Now it seems to working just fine :)
Upvotes: 0
Reputation: 21901
if you need to get the parameter do this,
Input::get('id');
and route
Route::get('get-response', array('as'=>'get-response', 'uses'=>'AjaxController@getResult'));
because your ajax request is something like, host/get-response?id=5
and this is not compatible with Route::get('get-response/{id}'..
, because this route needs something like host/get-response/5
Another way, you can keep your route as u declared and change the ajax request url,
$.ajax({
type: 'GET',
url: 'get-response/'+1,
dataType: 'json',
data: {},
success: function(response){
$('#content').html(response.first);
}
});
Upvotes: 1