Oh I just used very simple routes for the example:
Route::get('testjq', 'DogController@testjq');
Route::get('testc', 'DogController@testc');
Also to convert an object to array for the response, this works:
public function testc() {
$dogid = Request::input('somevar');
$dog = DB::table('dc_dogs')
->where('dogid', '=', $dogid)
->first();
$dogarray = (array)$dog;
return Response::json($dogarray);
}
I found this tip in a stackoverflow post about 8th answer down: https://stackoverflow.com/questions/19495068/convert-stdclass-object-to-array-in-php
An alternative solution:
For a simple ajax response, you can just get an array by setting:
$sth->fetch(\PDO::FETCH_ASSOC);
So here is how that looks:
public function testc() {
$dogid = Request::input('somevar');
$sql = "SELECT * FROM dc_dogs WHERE dogid = :dogid";
$params = ['dogid' => $dogid];
$sth = DB::getPdo()->prepare($sql);
$sth->execute($params);
$dog = $sth->fetch(\PDO::FETCH_ASSOC);
return Response::json($dog);
}
For some simple responses this solution works great.
A quick eloquent solution
Here returning more than one row, but just quick example:
Controller:
public function testg() {
$dogid = Request::input('somevar');
$dog = Dog::select('dogname', 'comments')
->where('dogid', '<', $dogid)
->get()
->toArray();
return Response::json($dog);
}
Jquery script
<script>
$(function () {
$("#testme").click(function (event)
{
event.preventDefault();
var somevar = '3'; // Usually a variable generated by you
// for demo hard coded
$.ajax({
url: 'testg',
type: 'GET',
data: 'somevar=' + somevar,
dataType: 'json',
success: function (data) {
$.each(data, function (index, item) {
alert(item.dogname);
// loop and do whatever with data
});
},
error: function (err) {
alert(err);
}
});
});
});
</script>
Notice the
->toArray();
That is needed for a json response.
Later I will post an Ajax post request example.
