I can't through the $request->ajax(), I can get and dd($data), but it always return false, what's wrong with my code.could anyone help me? thanks.
Route::post('test', 'BlogController@test');
<form method="POST" id="form-ajax" action="/test">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name1">Name1</label>
<input type="text" class="form-control" name="name1" id="name1">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="test_btn">
Submit
</button>
</div>
</form>
public function test(Request $request)
{
$data = $request->input('name1');
if ($request->ajax()) {
$response = array(
'name' => $data,
'status' => 'success',
);
return response()->json($response);
} else
return response()->json(['msg' => 'false']);
}
$(document).ready(function() {
$('#test_btn').click(function() {
$.ajax({
url: '/test',
type: 'post',
data: {'_token': $('input[name=_token]').val(), 'name1': $('input[name=name1]').val()},
success: function(data) {
console.log(data);
},
headers: {'X-Requested-With': 'XMLHttpRequest'},
dataType: 'json'
});
});
});
If you dig in the code, you will find out that $request->ajax() method relies on this logic (see vendor/symfony/http-foundation/Request.php):
$this->headers->get('X-Requested-With');
jQuery does set this header by default. First action you should do – see how your AJAX call looks in the Developer Tools in your browser. You can see full HTTP headers there – do the headers contain this X-Requested-With line?
If it's not there (unlikely but who knows), you could manually add it to your AJAX data object, eg: "X-Requested-With":"XMLHttpRequest".
Also, I would advise to replace $data = $request->get('name1'); with
$data = $request->input('name1');
Which is more correct way to get an input variable (get() method doesn't even exist in the documentation).