Send AJAX Call From Static HTML to Laravel
There are some basic steps to follow:
Create HTML form
Receive form data when click on submit button using Jquery
After receiving form data send ajax call to laravel Project or url
When Request received in Controller /method it send's Response
That Respose will be in success or failure
Let's start
Create HTML form
Create index.html in which we need to make a form
We need to add form id= "contact_report" intput name as name , number , course and also add id="btn-submit-report" in submit input field
Receive form data when click on submit button using Jquery
After footer tag we need to write jquery
<script src="js/jquery.min.js "></script>
<script src="js/jquery.validate.js "></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js "></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js "></script>
<script type="text/javascript">
$('.loading-icon').hide();
$('#error-message-report').hide();
$("#btn-submit-report").click(function(e) {
$("#data").empty();
var ab = $("#contact-report").valid();
if (ab) {
e.preventDefault();
var name = $("input[name=name]").val();
var number = $("input[name=number]").val();
var course = $("input[name=course]").val();
$('.loading-icon').show();
$("#btn-submit-report").attr("disabled", true);
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/en/api/diploma",
data: {
name: name,
number: number,
course: course,
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
if (data.success == true) {
$("input[name=name]").val('');
$("input[name=number]").val('');
$("input[name=course]").val('');
var newUrl = 'http://127.0.0.1:8000/admin/' + data.diploma.user_file;
$('#view_file').attr("href", newUrl);
$('#view_file2').attr("href", newUrl);
$('#numb').text(data.diploma.number);
$('#exampleModalCenter').modal('toggle');
}
if (data.success == false) {
$('#error').text(data.error);
$('#numb2').text(data.diploma);
$('#exampleModalCenter2').modal('toggle');
$('#error-message-report').addClass(alert.danger);
}
$('.loading-icon').hide();
$("#btn-submit-report").attr("disabled", false);
}
});
}
});
</script>
Let figured out jquery step by step
When use click on submit button id="btn-submit-report" will run click( ) function inside click ( ) we are validating our form using contact_report id with the help of jquery.validation.js
if form has no validation then we'll recieve form data and make an ajax call as our required url with request data name , number and course
Now its time to view the api Route
And Here is the Controller in which we are receving the ajax Request data and send back as a respose
Here is the last step of sending ajax call using html and laravel
That Respose will be in success or failure if there is success the we'll show success modal other wise error modal. Thank you
Comments
Post a Comment