To catch wantsJson() you need to specify json type in ajax request like dataType: "json" and also you can try to use alias request()->ajax() to catch that ajax.
May 15, 2017
2
Level 1
$request->ajax() is not working
Quiz app, laravel 5.2, I am making a ajax request for a search form and I want to check if it's an ajax request versus a form submit so I'm testing with
QuizController.php
public function search(Request $request){
if($request->wantsJson()){
dd("it wanted json");
}
else{
dd("it didn't want json");
}
if ($request->ajax()) {
dd("its ajax");
}
else{
dd("its not ajax");
}
$query = $request->get('query');
$results = Quiz::where('title',$query)->get();
return response()->json($results);
}
But the ajax() or wantsJson() are not being triggered, but the ajax calls were going thru
$('#query').on('keyup', function() {
if (this.value.length > 1) {
$.ajax({
type:"POST",
url:"quiz/search",
data:$("#searchForm").serialize(),
success:function(data){
console.log(data);
$('#results').removeAttr('hidden');
for(var key in data){
$("#results").prepend("<li><a href='{{route('quiz.show',['id' =>" + data[key].id + " ])}}' >" + data[key].title + "</a></li>");
}
}
});
}
});
form
<form class="navbar-form navbar-left" id="searchForm" method="post" action="{{route('quiz.search')}}">
{{ csrf_field() }}
<div class="form-group">
<input type="text" id="query" class="form-control" name="query" placeholder="Search">
<ul id="results" hidden>
</ul>
</div>
<button id="searchSubmit" type="submit" class="btn btn-default">Submit</button>
</form>
I have tried adding the
use Request; in addition to the use Illuminate\Http\Request;
at the beginning of the Quiz controller file
Please or to participate in this conversation.