php form not submitting using ajax jquery - php

.on('success.form.bv', function(e) {
// Get the form instance
var $form = $(e.target);
// Get the BootstrapValidator instance
var bv = $form.data('bootstrapValidator');
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
console.log(result);
}, 'json');
});
});
If i comment this code, then form submits.PLease tell me the error.This is the form

Related

Getting $_POST not working after Ajax successful submit in same page

I create a Form after user click on a div, and I submit on same page using Ajax without reloading page.
I see that the form is submitted successfully with data when I check the network tab in dev tools but when I print $_POST or check if isset($_POST["data"]), I get $_POST is empty and the if condition is false, is there any way to get the data in PHP ($_POST) without refreshing the page.
I get no errors in console or php
When using:
form.submit();
The form is submitted and I get $_POST but the page reload, this is why I need to use Ajax
My code on Js page :
function post(path, parameters) {
var form = $('<form id="form"></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", JSON.stringify(value));
form.append(field);
form.append(data);
});
$(document.body).append(form);
$.ajax({
type: "POST",
url: path,
data: $("#form").serialize(),
success: function(data) {
$('.before').hide();
$('.next').show();
}
});
return false;
}
$('.card-container').on('click',function(e){
e.preventDefault();
var page = window.location.href;
var object = {
'array': [
['string1', 'string2'],
['string3', 'string4']
]
};
post(page, object);
});
My code on PHP page :
var_dump($_POST);
if (isset($_POST['array'])) {
$array = json_decode($_POST['array'], true);
print_r("ok");
}
The full code is too long to include it here.

event.preventDefault() doesn't work and form still submits

I want to use event.preventDefault(); but my form still submitts.
and gives me a page with json response. There isn't any error in my console.
Here is my scripts:
$(document).ready(function() {
$('#add_to_cart ').on('submit', function(event) {
event.preventDefault();
var $form = $(event.target);
var data = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function(response, status, xhr) {
var message = response.message;
showToastMessage(message, 'toast-success');
}
}).fail(function(xhr, textStatus) {
var message = "Error.";
if (xhr.responseText) {
var error = JSON.parse(xhr.responseText);
if (error) {
error = error.message;
if (error) {
message = error;
}
}
}
showToastMessage(message, 'toast-error')
});
return false;
});
});
function showToastMessage(message, type) {
var $toastElem = $("#snackbar");
$toastElem.className = "show";
$toastElem.html(message).removeClass('toast-success').removeClass('toast-error').addClass(type).addClass('show');
}
I have seen most of the question about this problom, but I still have problom.
html:
<form action="{{ route('cart.add', $product->id) }}" method="POST" id="add_to_cart">
<a href="javascript:{}" rel="nofollow" data-nid="4165" class="cart-button ripple add-to-cart has-ripple" onclick="parent().submit();";>add</a>
</form>
This is your problem:
<a href="javascript:{}" rel="nofollow" data-nid="4165" class="cart-button ripple add-to-cart has-ripple" onclick="parent().submit();";>add</a>
Submit events are only triggered by the form submission is triggered by standard submission methods (like submit buttons).
Calling the submit() method of the form using JavaScript will bypass the submit event entirely.
Since the event doesn't fire, the event listener function isn't called, so event.preventDefault() is never called.
Use a submit button instead of a link that doesn't go to a useful URL with some JS attached to it.

ajax form validation in laravel 5

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;
}
});

post multipart/form-data with ajax

I want to post my form by ajax, the form contains some text fields and one file field, I used bootstrapValidator to validate the form, here is my code:
ajax:
$('#profile').bootstrapValidator({
// some validations here
}).on('success.form.bv', function(e) {
e.preventDefault();
var $form = $(e.target), // The form instance
bv = $form.data('bootstrapValidator'); // BootstrapValidator instance
var formData = new FormData($form);
$.post('index.php', formData, function(response) {
...
but the post request didn't sent, so where is the error in my code?

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