Ajax with laravel

24 0 0 0

Last Updated : 2020-12-03 16:30:51

this snippet will explain how to create ajax requests with laravel specially with forms

to use ajax with laravel you must follow these steps 


1- add csrf meta tag to head in your html file


<meta name="csrf-token" content="{{ csrf_token() }}"> 

2- create your route to use it in the form like this


Route::post("sendMessage", ['uses'=>'MessageController@store', 'as'=>'sendMessage']);

3- create your form and assign your route to form action and specify form method like this


<form class="p-5 bg-white" id="messagingForm" action="{{ route('sendMessage') }}" method="post">  // assigned action and method here            
@csrf

<div class="row form-group">
<div class="col-md-12 mb-3 mb-md-0">
<label class="text-black" for="fname">الاسم <span class="text-danger">*</span></label>
<input type="text" name="mes_name" id="name" class="form-control rounded-0">
</div>
</div>

<div class="row form-group">

<div class="col-md-12">
<label class="text-black" for="email">البريد الالكترونى <span class="text-danger">*</span></label>
<input type="email" name="mes_email" id="email" class="form-control rounded-0">
</div>
</div>

<div class="row form-group">

<div class="col-md-12">
<label class="text-black" for="subject">عنوان الرسالة</label>
<input type="subject" name="mes_subject" id="subject" class="form-control rounded-0">
</div>
</div>

<div class="row form-group">
<div class="col-md-12">
<label class="text-black" for="message">الرسالة <span class="text-danger">*</span></label>
<textarea name="mes_message" id="message" cols="30" rows="7" class="form-control rounded-0" placeholder="اكتب رسالتك هنا ..."></textarea>
</div>
</div>

<div class="row form-group">
<div class="col-md-12 text-right">
<button type="button" value="ارسال" id="sendMessageBTN" class="btn btn-primary mr-2 mb-2">ارسال</button>
</div>
</div>
</form>

4- create ajax request like this


$("#sendMessageBTN").click(function () {
// get form and its dependences
var theForm = $("#messagingForm"); // here specify the form
var formAction = theForm[0].action; // specify action of this form
var formMethod = theForm[0].method; // specify method of this form
var formData = theForm.serialize(); // specify data of this form
//console.log(formData); // you can console log form data before moving to the next step
//console.log(formAction); // you can console log form action before moving to the next step
//console.log(formMethod); // you can console log form method before moving to the next step

$.ajax({
url: formAction ,
method: formMethod ,
data: formData ,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: "json",
success: function(data){
if (data['messages_errors']) {
console.log(data['messages_errors']) ;
} else {
console.log(data['messages_success']) ;
}
},
error: function(){
alert("failed .. Please try again !");
}
}) ;

});

5- create function in controller like this


public function store(Request $request) {           
$mes_name = $request->input('mes_name');
$mes_email = $request->input('mes_email');
$mes_subject = $request->input('mes_subject');
$mes_message = $request->input('mes_message');

$rules = [
'mes_name' => 'required',
'mes_email' => 'required|email',
'mes_message' => 'required',
];

$messages = [
'mes_name.required'=>"برجاء ادخال الاسم" ,
'mes_email.required'=>"برجاء ادخال البريد الالكترونى" ,
'mes_message.required'=>"برجاء كتابه الرسالة المطلوبه" ,
];

$validator = Validator::make($request->all(), $rules, $messages);

$errors = $validator->errors();

if (count($errors) > 0) {
return response()->json(['messages_errors'=>$errors]);
} else {
$newmessage = new Message();
$newmessage->name = $mes_name;
$newmessage->email = $mes_email;
$newmessage->subject = $mes_subject;
$newmessage->message = $mes_message;
$success = $newmessage->save();

if ($success) {
return response()->json(['messages_success'=>'تم ارسال الرساله بنجاح']);
} else {
return response()->json(['messages_errors'=>'حدث خطا ما ... برجاء المحاولة لاحقا']);
}
}

}

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.