I am trying to insert data to database through Ajax And Laravel. But when I click the submit button, nothing happens at all. I tried to see if the javascript is reachable at the first using “Alert” and yes it is. But the part of $ajax is not reachable at all.
Here is the code:
Html:
<div class="form-group"> <input type="hidden" name="_token" id="csrf" value="{{Session::token()}}"> <label for="email">Name:</label> <input type="text" class="form-control" id="name" placeholder="Enter Name" name="name"> </div> <div class="form-group"> <label for="email">Email:</label> <input type="email" class="form-control" id="email" placeholder="Enter Email" name="email"> </div> <div class="form-group"> <label for="email">Phone:</label> <input type="text" class="form-control" id="phone" placeholder="Enter Phone" name="phone"> </div> <div class="form-group"> <label for="email">City:</label> <input type="text" class="form-control" id="city" placeholder="Enter City" name="city"> </div> <button type="submit" class="btn btn-primary" id="butsave">Submit</button> </div>
Javascript:
$(document).ready(function() { $('#butsave').on('click', function() { alert("hello"); var name = $('#name').val(); var email = $('#email').val(); var phone = $('#phone').val(); var city = $('#city').val(); var password = $('#password').val(); if(name!="" && email!="" && phone!="" && city!=""){ /* $("#butsave").attr("disabled", "disabled"); */ $.ajax({ url: "/userData", type: "POST", data: { _token: $("#csrf").val(), type: 1, name: name, email: email, phone: phone, city: city }, cache: false, success: function(dataResult){ console.log(dataResult); var dataResult = JSON.parse(dataResult); if(dataResult.statusCode==200){ window.location = "/userData"; } else if(dataResult.statusCode==201){ alert("Error occured !"); } } }); } else{ alert('Please fill all the field !'); } }); });
for the controller code:
public function create() { return view('userData'); } public function store(Request $request) { $request->validate([ 'name' => 'required', 'email' => 'required', ]); UserData::create($request->all()); return json_encode(array( "statusCode"=>200 )); }
The browser debugging shows this error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Advertisement
Answer
Try this one…
First of all set meta tag in your blade file’s html head tag.
<head> <meta name="csrf-token" content="{{ csrf_token() }}"> </head>
Define ROUTES like this
Route::get('/userData', [YourControllerHere::class, 'create'])->name('userData.get'); Route::post('/userData', [YourControllerHere::class, 'store'])->name('userData.post');
Then change your button type if you are not using FORM to submit the data.
<button type="button" class="btn btn-primary" id="butsave">Submit</button>
Then add this script.
<script> $(document).ready(function () { var getUserDataUrl = {!! route('userData.get') !!}; var postUserDataUrl = {!! route('userData.post')!!}; $('#butsave').on('click', function () { alert("click"); var csrf_token = $('meta[name="csrf-token"]').attr('content'); var name = $('#name').val(); var email = $('#email').val(); var phone = $('#phone').val(); var city = $('#city').val(); var password = $('#password').val(); if (name != "" && email != "" && phone != "" && city != "") { $.ajax({ url: postUserDataUrl, type: "POST", data: { _token: csrf_token, type: 1, name: name, email: email, phone: phone, city: city }, cache: false, success: function (dataResult) { console.log(dataResult); // to view your response from controller in webbrowser's console if (dataResult.statusCode == 200) { window.location.href = getUserDataUrl; // if you want to show console data comment this line } else if (dataResult.statusCode == 400) { alert("Error occured!"); } } }); } else { alert('Please fill all the field !'); } }); }); </script>
Now change your controller’s store function.
public function store(Request $request) { $request -> validate([ 'name' => 'required', 'email' => 'required', ]); $userObj = UserData::create($request->all()); //the create method only create user in database when there are fileds match in UserData model and request->all() otherwise you have to manipulate request data $data = []; if(!empty($userObj)){ $data['statusCode'] = 200; $data['userObj'] = $userObj; } else { $data['statusCode'] = 400; } return response()->json($data); }