I am new to Ajax and I am using laravel, now i want to have a delete button that will send the id of the item that i want to delete to controller. Here is my code.
Views
<div class="row">
@foreach($photos as $photo)
<div class="col-xs-3 col-md-1">
<button onclick="removeItem({{$photo->id}}); return false;">Delete</button>
</div>
@endforeach
</div>
Here is my script
<script type="text/javascript">
function removeItem($myvar) {
$.ajax({
type : "POST",
url : "deletephoto",
);}
}
</script>
I want to send this to this route
Route::post('deletephoto','GamefarmsController@deletephoto');
on my Controller I want to do this just to test if its working
public function deletephoto()
{
dd($myvar);
}
You have to add your variable $myvar to the data-property of the $.ajax() function:
$.ajax({
type: "POST",
url: "deletephoto",
data: { myvar: $myvar }
})
Then in your controller you can get the value of this variable with:
Input::get('myvar'); // for Laravel 4.x
Request::input('myvar'); // for Laravel 5
Try this:
<script type="text/javascript">
function removeItem(myvar) {
$.ajax({
type : "POST",
url : "deletephoto",
data: { 'myvar' : myvar },
success: function(res) {
console.log(res);
}
)};
}
</script>
In your routes.php file:
Route::post('deletephoto', array(
'as' => 'deletephoto',
'uses' => 'GamefarmsController@deletephoto');
));
In your controller:
public function deletephoto() {
//dd($myvar);
return Input::get('myvar');
}
This will return whatever the variable passed through was, and send it back to the AJAX call, and then output in the console.
And finally:
<button onclick="removeItem({{$photo->id}});">Delete</button>