Moramu
Moramu

Reputation: 11

Laravel ajax response get values

I have ajax like this:

$(".cq").on("input", function() {
  $.ajax({
    url: "create/reefFormAjax",
    type: "POST",
    data: $(this.form).serialize(),
    success: function(data) {
      callback(data);
    }
  });
});
function callback(response) {
  $(".sum_whl").val(response);
  $(".sum_rtl").val(response);
}

So in my controller I have something like this:

$test = $request->all();
return json_encode($test);

Then I retrieve data back to my view:

  {
    "material": "0",
    "mquantity": null,
    "cq": "2",
    "sum_rtl": null,
    "sum_whl": null
  }

The question is how I can get each value from response ?

I tried $(response).find('cq').val() or filter but I an have error.

Any ideas?

Upvotes: 1

Views: 1622

Answers (4)

Moramu
Moramu

Reputation: 11

I solved this problem, i was using return json_encode instead of return response->json($var); So i grab my values!

Upvotes: 0

John Doe
John Doe

Reputation: 183

The result you get is a JSON response

  var response = 
  {
    "material": "0",
    "mquantity": null,
    "cq": "2",
    "sum_rtl": null,
    "sum_whl": null
  };

If the JSON is in your response variable, you can simply access the element like this

response.material; // should print 0 response.cq; // will print 2

Upvotes: 1

Ali Özen
Ali Özen

Reputation: 1609

console.log(response.data[0]) or console.log(reponse.material) must be work. Because its json object.

Give it a try.

$("#div).html(response.data[0])

$("#div).html(response.material)

Upvotes: 0

Supun Praneeth
Supun Praneeth

Reputation: 3160

When you return a json(or array) from laravel it automatically turn into a js object. so you can access like this:

function callback(response) {
  $(".sum_whl").val(response.sum_whl);
  $(".sum_rtl").val(response.sum_rtl);
}

Upvotes: 0

Related Questions