I have created a form to submit the data into the database. This is working fine when I don't use AJAX.
Even after adding ajax it takes me to another page and displays the text, what I have returned in the controller.
My controller function
public function newAppointment(Request $request){
// Validate the request...
$this->validate($request, [
'name' => 'required',
'email' => 'email|required',
'mobile' => 'numeric|required',
'date' => 'date|required',
'time' => 'required',
]);
$otp = rand(100000, 999999);
$schedule = new \App\Schedules;
$schedule->name = $request->name;
$schedule->email = $request->email;
$schedule->mobile = $request->mobile;
$schedule->date = $request->date;
$schedule->time = $request->time;
$schedule->save();
$id = $schedule->id;
$verify = array('otp'=>$otp, 'id'=>$id);
echo json_encode(array('verify'=> $verify));
}
Ajax Script
<script type="text/javascript">
$(document).ready(function (e){
$("#newAppointment").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "appointment",
type: "POST",
data: {name: $("#name").val, email: $("#email").val, mobile: $("#mobile").val, date: $("#date").val, time: $("#time").val },
contentType: "application/json",
cache: false,
processData:false,
success: function(data){
alert("Success");
},
error: function(data){
alert(data.error->first());
}
});
}));
});
</script>
When I click on the Submit button, I get a some text as output, i.e. what I have returned in the controller, in a new page.
How can I be on the same page after submitting the form.
{"verify":{"otp":847042,"id":44}}