Reputation:
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 :
Upvotes: 0
Views: 524
Reputation: 96
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]);
Upvotes: 2
Reputation: 9045
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);
Upvotes: 3
Reputation: 3274
In case of ajax, try returning response json
function requete()
{
$id = Str::random();
return response()->json([
"id" => json_encode($id)
]);
}
Upvotes: 0
Reputation: 187
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.
Upvotes: 0