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
Route::post('test', 'BlogController@test');
view
<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>
controller
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']);
}
js
$(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'
});
});
});