Can’t get data from controller with ajax request
Trying to get products
from productController
with category_id
As seen blow. Codes are basic ajax request codes, there is no complicated things. But my result is allways null.
ROUTE
Route::post('urun-listele', 'ProductController@listele');
CONTROLLER
public function listele(Request $request)
{
$category_id = $request['category_id'];
$urunler = Product::where('category_id', $category_id)->get();
#var_dump($urunler);
return json_encode([
'urunler' => $urunler
], JSON_UNESCAPED_UNICODE);
}
AJAX
function urunListele(kategori_id) {
var kapsayici = $('#product-info');
$.ajax({
url: 'urun-listele',
type: "POST",
data: {category_id: kategori_id},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
var urunler = data['urunler'];
for (var i = 0; i < urunler.length; i++) {
kapsayici.append('<div class="col-md-3 product-detail-item b-white br-10px"><p>' + urunler[i]['title'] + '</p></div>');
}
}
});
}
As i said, can’t get any data.
var urunler = data['urunler'];
for (var i = 0; i < urunler.length; i++) {
kapsayici.append('<div class="col-md-3 product-detail-item b-white br-10px"><p>' + urunler[i]['title'] + '</p></div>');
}
console.log(urunler);
allways return 0 object. Where is the problem? Thanks in advance.
EDIT:
i got Cannot read property 'length' of undefined
when try return $urunler;
$category_id = $request['category_id'];
can’t get anything i think.
For example if i change $category_id = 5
it return [object Object],[object Object]
i have 2 object with $category_id = 5
.
is problem here? $category_id = $request['category_id'];
EDIT2:
$category_id = $request->get('category_id');
$urunler = Product::whereCategoryId($category_id)->get();
return response()->json([
'urunler' => $urunler
]);
Controller changed like this and its working right now.
from Laravel Questions and Answers https://laravelquestions.com/php/cant-get-data-from-controller-with-ajax-request/
via Lzo Media
No comments:
Post a Comment