I'm submitting data to my Laravel Controller, and I'm trying to access the returned Json response.
I'm submitting the data with the following:
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: {ingredients: step_ingredients, description: step_description},
dataType:'json',
url: "{{ route('steps.store', ['id' => $recipe->id]) }}",
success: function (data) {
console.log(data);
//alert(data.desc);
$("#ajaxOutput").html('<code>Description output: '+data.desc+'</code>');
// $.each(data, function (key, value) {
// alert(data.ing.ingredient_id);
// });
},
error: function (xhr, ajaxOptions, thrownError) {
console.warn(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
And (for now) the controller is doing the following:
public function store(Request $request)
{
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly',
'ing' => json_decode($request->ingredients),
'desc' => $request->description
] ;
return response()->json($data);
}
I can access the description etc using data.desc
but I'm having trouble looping through the data.ing
array, and accessing the relevant values, eg ingredient 1 name, or ingredient 2 quantity.
try
for laravel
foreach($ing as $data) {
echo "$data->ingredient_name"; //$data is object
}
for javascript
$.each(data.ing, function (key, value) { console.log(value.ingredient_name); })