0

I need to pass data from controller to view this is code :

Controller :

function requete()
{
    $id = Str::random();  
    return view('Demo.requete', compact('id'));
}

View :

$(document).ready(function() {   
    $.ajax({
        url: "{{ route('support.requete') }}",
        method: "get",
        data: data,
        dataType: "json",
        success: function(data)
        {
            $('#code').html(data.id);//nothing happens here
        }
    });
});

I keep getting this error :

enter image description here

4 Answers4

3

You can do :

return view('Demo.requete', compact('id'));

Then you can use {{ $id }} directly in the blade file.

Update :

You are using ajax so you will need a json response :

return response()->json(compact('id'), 200);

Then you can do in ajax success :

$('#code').html(data.id);
Mihir Bhende
  • 8,677
  • 1
  • 30
  • 37
  • Uodated muy answer – Mihir Bhende Feb 25 '19 at 12:52
  • You don’t really need to pass “data” and “dataType” since you aren’t doing anything with it sever side. And if you are trying to access data.id you need to return a JSON response from the server instead of a view. See my answer below on how to do that. – balistikbill Feb 26 '19 at 12:50
2

You shouldn’t return a view with an Ajax request, that should be a different route to hit with the $.ajax get request. Laravel can then return JSON responses and you can use that in your success callback.

Yo

return response()->json([‘id’ => $id]);
0

You shouldn't use echo in the view. You shouldn't use ajax to get the view (unless you want to receive HTML and it does not seem the case here) You should have a different endpoint for your ajax request if you want to fetch the data asynchronously otherwise you can just return the view with all the data you need.

Alaa Saleh
  • 177
  • 1
  • 2
  • 14
0

In case of ajax, try returning response json

function requete()
{
    $id = Str::random();
    return response()->json([
     "id" => json_encode($id)
   ]);
}
Vipertecpro
  • 3,056
  • 2
  • 24
  • 43