ajax form validation in laravel 5 - php

I am new in laravel and need help.
These are the values I'm getting via ajax, all values are to be stored in db, but how do I validate[check] if there are existing values or not before submitting a form using ajax?
$("#submit").click(function(e){
e.preventDefault();
var url = "{!! URL::to('/') !!}";
var id="{!! #$department->id !!}";
var token = "{!! csrf_token() !!}";
var customer_id = $("#customer_id").val();
var visiting_address1 = $("#visiting_address1").val();
var department_id = $("#department_id").val();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: url+"/customer/"+customer_id+"/popup_store",
data: { '_token':token, 'rest':'true', 'customer_id':$("#customer_id").val(), 'main_address':$("#main_address").val(),'visiting_city':$("#visiting_city").val(),'visiting_address':$("#visiting_address1").val(),'visiting_zip':$("#visiting_zip").val()},
async : false,
success : function(data) {
if(data == "success")
{
$("#addrecords").modal('hide');
}
else
alert(data);
}
});
});

First of all define you Jquery validation for you form like this:
$("#myForm").validate({
// Specify the validation rules
rules: {
name: "required",
},
// Specify the validation error messages
messages: {
name: "Please enter name",
},
submitHandler: function (form) {
// leave it blank here.
}
});
And then in your click button of submit button, write if condition to check validations:
$("#submit").click(function (e) {
if ($('#myForm').valid()) {
// your Ajax Call Code
} else {
return false;
}
});

Related

Js Validator Plugin Remote Rules for Unique Value Checking Without Refresh Page Not Working After Ajax Call

I'm trying to validate an designation name with a remote rules.
On first time form submit by entering test value, form submitted and value bind by ajax. but after second time without refresh page i m trying to submit form by adding same value test which i added. i m not getting error for existing name.
here is the js code
$("#designationaddedit").validate({
rules: {
designation_name: {
required: true,
},
designation_copy_name: {
remote: {
url: base_url + 'Designation/designation_name_exists',
type: "post",
data: {
designation_copy_name: function() {
console.log("1");
return $( "#designation_copy_name" ).val();
}
}
}
},
},
messages: {
designation_name: {
required: "Enter Designation name"
},
designation_copy_name: {
remote: 'Designation name is already exists.'
},
},
});
$(document).on('submit', '#designationaddedit', function(event) {
event.preventDefault();
var designation_id = $('#designation_id').val();
var designation_name = $('#designation_name').val();
var action = $('#action').val();
var table = $('#designationTable').DataTable();
var info = table.page.info();
var currentpage = info.start;
if ($("#designationaddedit").valid()) {
$('.preloader').show();
$.ajax({
url: base_url + 'designation/add',
type: 'POST',
dataType: 'json',
data: { submit: 1, designation_id: designation_id, designation_name: designation_name, action: action },
success: function(response) {
$('.preloader').hide();
if (response.success == 1) {
$("#designation_model").modal('hide');
} else {
}
}
});
}
})
below code fixed my issue. I hope it's help you.
remote: { url: "http:url.com", type: "post", data: { USER_ID: userid }, async: false, // set async = false }

Not showing the Modal

I want to show a notification modal when i submit a form.but unfortunately the modal is not popping up here is the code
$("#submitmodalRetailer").submit(function() {
var FirstName = $('#FirstNameRetailer').val();
var LastName = $('#LastNameRetailer').val();
var QRCodeRetailer = $('#QRCodeRetailer').val();
var prefixNumberRetailers = $('#prefixNumberRetailer').val();
var Retailer7Digits = $('#Retailer7Digit').val();
$.ajax({
type: "POST",
url: "addRetailer.php",
data: $('form.form-modal-retailer').serialize(),
success: function(msg) {
$("#RetailerAdd").modal('hide');
location.reload();
if (msg == 'Valid') {
$("#RetailerAddshow").modal('show');
} else if (msg == 'AlreadyExists') {
$("#BarcodeExists").modal();
} else if (msg == 'Invalid') {
alert('Your Barcode number is invalid. \n User only 100001 to 199999')
}
},
error: function() {
alert("failure");
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You may remove
location.reload();
in Ajax success method to avoid page reload that hinder popup from showing up.
and also you can add
e.preventDefault();
in the button click event to prevent the form submit to cause reloading that may also hinder popup from showing.
and you need to add e as a parameter to event.
$("#submitmodalRetailer").submit(function(e) {.
e.preventDefault();
var FirstName = $('#FirstNameRetailer').val();
var LastName = $('#LastNameRetailer').val();
var QRCodeRetailer = $('#QRCodeRetailer').val();
var prefixNumberRetailers = $('#prefixNumberRetailer').val();
var Retailer7Digits = $('#Retailer7Digit').val();
$.ajax({
type: "POST",
url: "addRetailer.php",
data: $('form.form-modal-retailer').serialize(),
success: function(msg) {
$("#RetailerAdd").modal('hide');
// location.reload();
if (msg == 'Valid') {
$("#RetailerAddshow").modal('show');
} else if (msg == 'AlreadyExists') {
$("#BarcodeExists").modal();
} else if (msg == 'Invalid') {
alert('Your Barcode number is invalid. \n User only 100001 to 199999')
}
},
error: function() {
alert("failure");
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You need to prevent the default action of the submit button.
Use preventDefault().
Read about it here: https://api.jquery.com/event.preventdefault/
$("#submitmodalRetailer").submit(function (e) {
e.preventDefault();
});

How to make PHP action in AJAX

I created a PHP page that Insert into the database the value in the textbox, when someone click on the button it's redirect to the php page, But I want it to make the PHP action without redirecting, So how can I do it in ajax?
Thank you
woz and dragoste are right. Use jQuery to make it happen. you can use this function, it will fit to your requirement.
Here i used jQuery validation library http://jqueryvalidation.org/ to validate the form .
$(function()
{
var form = $("#booking_form").validate();
$('#success').hide();
$('#failure').hide();
$("form#your_form").submit(function() {
if(form.valid())
{
var name = $("#txtName").val();
var email = $("#txtEmail").val();
var phone = $("#txtPhone").val();
$.ajax({
url: "process_form.php",
type: "POST",
data: {
'name': name,
'email': email,
'phone': phone
},
dataType: "json",
success: function(data) {
if(data.status == 'success')
{
$('#your_form').hide();
$('#success').show();
}
else if(data.status == 'error')
{
$('#failure').show();
}
}
});
return false;
}
});
});

Ajax on multi check PHP Codeigniter

i want use ajax for sent to saveKrs and save to database. i'm use codeigniter, when i click submit button, there's no event. please help me
form_checkbox('checkKrs[]',$row->id, FALSE, 'id=checkKrs')
<script type="text/javascript">
$('#save_krs').click(function(){
var id_student= $('#id_student').val();
var id_semester = $('#id_semester').val();
var checkKrs = new Array();
$("input:checked").each(function() {
data['checkKrs[]'].push($(this).val());
})
var data = {
checkKrs:checkKrs,
id_semester:id_semester,
id_mahasiswa:id_mahasiswa,
is_ajax: '1'
};
$.ajax({
url: "saveKrs",
type: 'POST',
data: data,
beforeSend : fnLoadStart,
complete : fnLoadStop,
success: function(msg) {
//$('#form_data').hide();
$('#form_data').html(msg);
//$('#report').show();
}
});
alert('Pengisian KRS tidak boleh kosong');
return false;
});
</script>
Make you sure that you have the right controler and if you form match it.

Custom Form Validation and Submit

I have a form validation run when the submit button is selected but i do not want the default submit function to run. Instead i want to run an ajax post code to store the data in the form along with post the data from server side.
I am having trouble finding where to cancel the default submit and add in the ajax code.
Here is the validate code i have
$("#formEnroll").validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
form.submit();
}
});
And here is the ajax code i want to run instead of the default submission
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
you can call the the ajax function instead of form.submit();
form.submit(); will submit your code using default submission.
$('#formEnroll').on('submit', function(e){
e.preventDefault();
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform();
}
});
})
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
}
You could wrap your validate plugin into a generic form submit function to stop standard execution.
$('#formEnroll').on('submit', function(e)
{
e.preventDefault(); // stop form submission
// Run validation
$(this).validate({
errorElement:"p",
submitHandler: function(form) {
var phoneNumber = form.day_phone.value;
var phoneParts = phoneNumber.split("-");
form.dayArea.value = phoneParts[0];
form.dayPrefix.value = phoneParts[1];
form.daySuffix.value = phoneParts[2];
submitform(); // call your ajax function here
}
});
});
function submitform(){
$.ajax({
type: "POST",
url: "/php/localProxy.php",
data: $('#formEnroll').serialize(),
success: function (response) {
document.location = 'http://www.xxxx.com/thank-you';
},
error: function () {
alert('There was a problem!'); // handle error
}
});
Instead of using the event object e you can also just return false; at the end of the .on function to stop default events from firing.
You can send the data by ajax using the click event in the jquery by clicking the submit button and that function should return false for avoiding the default submission by the way you can send the data using ajax and avoid the default submission.

Categories