1

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);
}

Console Log of data response

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.

1 Answer 1

2

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); })

Sign up to request clarification or add additional context in comments.

3 Comments

I've used the following: $.each(data.ing as $data) { console.log($data->ingredient_name); //$data is object }; and a few iterations of it, and keep getting "Unexpected identifier 'as'. Expected ')' to end an argument list."
try $.each(data.ing, function (key, value) { console.log(value-> ingredient_name); });
I had to change it to value.ingredient_name, but that's working. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.