AJAX form submission, submitting another form even thought using $(this) - php

I have two forms on my page.
One is in the footer and is a contact page, but the other is my main form called "product-form". I am doing some validation in PHP:
foreach( $_POST as $field => $val ) {
if ($val == '') {
echo $field . "- no val <br>";
}
}
The issue is that I am seeing fields being validated that are in my footer form...
Here is my AJAX:
$('body').on('submit', '.product-form', function(e){
e.preventDefault();
var thisForm = $(this);
$.ajax({
url : '/wp-content/themes/theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
}
});
});
How is this submitting the data from two forms?
Both forms have their tags properly closed off, with different class's too.
Have to use WordPress for this project, normally much more at home with Laravel validation so this is a bit of a throwback!
Requested form HTML:
Form I want:
<form method="post" class="product-form">
<li class="object field">
<label for="full name">Your full name <span>*</span></label>
<input class="req" autocomplete="off" type="text" name="full name" id="full name" placeholder="e.g. John Doe">
</li>
</form>
And the footer form:
<form class="footer-form small">
<li>
<button class="object button large" type="submit">Get in touch</button>
</li>
</form>

Please change it like this:
$( ".product-form" ).submit(function( e) {
e.preventDefault();
var thisForm = $(this);
$.ajax({
url : '/wp-content/themes/theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
}
});
});

Related

Sending Multiple Dynamix TextField Values Through Ajax

I have already submitted forms using ajax,
i have a query with my dynamic text fields I need to pass their value through ajax. i have done this trough PHP, but I need to use ajax function to do that.
Below is my PHP code how i did it.
<form>
<h3>Day 1 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 2 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 3 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 4 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<!------- button for adding more textfields for day deatils--->
<button name="" onclick="somefunctiontoaddmoretextfield">
</form>
this is my php code. i use foreach for my dynamic textfield as i have a button to add as many Day details i need.
but my conern is how can i pass this multiple textfield values in the ajax.
i have tried many thing and also search on stack but never found any answer.please help me with this how i can post this data using ajax.
<?php
foreach($_POST['b_destinations'] as $p_destination) {
$pdata[] = preg_replace("/[^A-Za-z0-9?! ]/","",$p_destination);
}
$pData[] = $pdata;
$b_destinations = json_encode($pData);
foreach($_POST['b_nights'] as $p_nights) {
$pdata1[] = filter_var($p_nights,FILTER_SANITIZE_NUMBER_INT);
}
$pData1[] = $pdata1;
$b_nights = json_encode($pData1);
?>
this is my ajax code. what needs to done here
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'destinations' : $('input[name=b_destinations]').val(),
'nights' : $('input[name=b_nights]').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});

wizard-form tow button different call ajax

I apologize for the ease of this question for you.
But I looked at your beautiful site for an answer to my problem, but I was not lucky.
I'm trying to build my own,form-wizard for student registration, in easy steps as a graduate project for university.
I use PHP, JQuery and AJAX to send data .
My problem:
I have a single form and to button ,
The first three input are searched in the database via the submit button and it is worked good ,
then automatically form-wizard moves to the next fieldset and then displays the inpust field to
student to enter his information .
finally thir is button to save data to database
by AJAX and this button is my problem .
the php say undefined index .
this is code for html wizard-form
$('form').on('submit', function(e) {
var $formInput = $(this).find('.fi');
$formInput.each(function(i) {
if (!$(this).val()) {
e.preventDefault();
$(this).addClass('input-error');
return false;
} else {
if ($formInput.length === i + 1) {
var id_high_school = $('[name="id_high_school"]').val();
var SEC_SCHOOL_YEAR = $('[name="SEC_SCHOOL_YEAR"]').val().toString();
var sum_high_school = $('[name="sum_high_school"]').val();
alert(SEC_SCHOOL_YEAR);
$.ajax({
url: "select_for_modal_serch.php",
method: "post",
data: {
id_high_school: id_high_school,
SEC_SCHOOL_YEAR: SEC_SCHOOL_YEAR,
sum_high_school: sum_high_school
}
}).done(function(datas) {
$('#studint_detail').html(datas);
$('#dataModal').modal("show");
}).fail(function() {
alert('fail..');
});
}
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<form name="mainForm" action=" <?php echo $_SERVER['PHP_SELF'] . '#form1' ?> " id="form1" method="POST" enctype="multipart/form-data">
<!-- condetion for regster -->
<fieldset>
<iframe src="license.html"></iframe>
<input class="form-check-input" id="check_qury" type="checkbox" value="yes">
<div class="wizard-buttons">
<button type="button" class="btn btn-next">التالي</button>
</div>
</fieldset>
<fieldset>
<!-- 3 <input type = text > to search for data from mysql -->
<!--her is the submit button and is get data by ajax -->
<input type="submit" class="form-control btn btn-primary view-data" id="submit_high_school" value="بحث" name="submit_high_school" />
<!-- by ajax is work and then is go to the next filedset -->
</fieldset>
<fieldset>
<!-- mor data <input type = text > to search for data from mysql -->
<button type="button" id="sava_data_to_tables" name="sava_data_to_tables" class="btn btn-next">
<!-- this is the button of my problem cant send this form data to mysql -->
</fieldset>
I doing this code to solve the problem but nothing work :
$('#sava_data_to_tables').on('click', function (event) {
var form_data = $(this).parents('form').serialize();
var colage = $('[name="colage"]').val();
var spichelest = $('[name="spichelest"]').val();
// and rest of input type
$.ajax({
url: "insert_into_info_contact.php",
method: "POST",
data: form_data,
success: function (data) {
alert(data);
}, cache: false,
contentType: false,
processData: false
});
});
and my PHP :
<?php
// isset($_POST['sava_data_to_tables'])
//$_SERVER['REQUEST_METHOD']==='POST'
// !empty($_POST)
if ($_SERVER['REQUEST_METHOD']==='post')
{ echo "you submit data"
;}
else {
echo "its not work" ; }
?>
I found some help from a friend ..
He just change this :
var form_data = $(this).closest('form').serialize();
to this :
var form_data = new FormData($(this).closest('#form1').get(0));
He solved my problem.
I honestly did not understand what the problem was, but he told me I had sent a different kind of data >> Thanks every One . :)

submit form on click of a link and send to multiple email ids

I have formatted my form using uniform jquery plugin. Also for submitting the form i am using a link as i have added some effect to it and if I use input type submit for this it will get formatted with uniform .
<form>
<ul>
<li><label>Your Name:</label><input type="text" name="name" size="40"/></li>
<li><label>Your Email:</label><input type="email" name="email" size="40"/></li>
<li>
<label>Gender:</label>
<select name="gender">
<option>Male</option>
<option>Female</option>
</select>
</li>
<li><label>Subject:</label><input type="text" name="subject" size="40"/></li>
<li><label>Write your letter here:</label><textarea name="message" cols="60" rows="15"></textarea></li>
OR ELSE<br/><br/>
<li>
<label>Upload your letter:</label>
<input type="file" />
</li>
<li>
<a id="mylink" class="button" href="#">
<img src="button.png" alt="" />Send</a>
</li>
</ul>
</form>
Now i want to submit this form using the link and also want to email it to two email ids simultaneously. What javascript code can i use. I am using the following code to submit the form and then in send.php I am sending the mail.
a.onclick = function() {
$(this).parents('form:first').submit();
send.php;
return false;
}​
Is it possible to call send.php like this?
Do you mean:
If you have action="send.php" in your form, then
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$(this).closest('form').submit();
});
});
Or, you can set action for the form and submit, like
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
var myFrm = $(this).closest('form');
myFrm.get(0).setAttribute('action', 'send.php');
myFrm.submit();
});
});
OR, using ajax
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "send.php",
data: {your data to post here},
succes: function(resp) {
//your response here
}
});
});
});
Is it possible to call send.php like this?
Like this? No, you need to use ajax request:
$.ajax({
url :"send.php"
});
Extra tip: change:
$(this).parents('form:first').submit();
To:
$(this).closest('form').submit();

jquery fancybox login box not load external php file

i am trying to use fancybox to display login form like bellow
<div style="display:none">
<form id="login_form" method="post" action="">
<p id="login_error">Please, enter data</p>
<p>
<label for="login_name">Login: </label>
<input type="text" id="login_name" name="login_name" size="30" />
</p>
<p>
<label for="login_pass">Password: </label>
<input type="password" id="login_pass" name="login_pass" size="30" />
</p>
<p>
<input type="submit" value="Login" />
</p>
<p>
<em>Leave empty so see resizing</em>
</p>
</form>
</div>
the java script for that is
$("#login_form").bind("submit", function() {
if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
$("#login_error").show();
$.fancybox.resize();
return false;
}
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "login.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
the html is
<a id="tip5" title="Login" href="#login_form"><?php echo "Login" ; ?></a>
when i click on login link, it shows the login popup but when i click on submit button it close the popup and refresh the page.
actually it should check the data and display data on popup not refresh page.
Thanks
There could be more problems:
Fancybox is probably cloning the original HTML to put it into the popup. Therefore You need to use function live instead of bind.
It is possible that Fancybox could alter the form's ID in some way (check that with some DOM Inspector like FireBug for FireFox) and assure that the form's ID within a popup is the one You'd lived the submit event for.
I also prefer to use event.preventDefault() instead of returning false... My JS code would then be:
$("#login_form").live("submit", function(e) {
e.preventDefault();
if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
$("#login_error").show();
$.fancybox.resize();
return false;
}
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "login.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
});

jQuery / php - Multply forms on page, submit only one

I have two forms on my website, and I use jQuery to submit them, to my PHP script.
These are the forms:
<form method="post" class="settings-form" id="passwordSettings">
<label id="npasswordbox" class="infoLabel">New Password: </label>
<input type="password" name="npassword" size="50" value="" >
<div class="move"></div>
<label id="cnpasswordbox" class="infoLabel">Confirm: </label>
<input type="password" name="cnpassword" size="50" value="" >
<button class="btn" name="passwordSetings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
And the next:
<form method="post" class="settings-form" id="normalSettings">
<label id="npasswordbox" class="infoLabel">New Username: </label>
<input type="text" name="username" size="50" value="" >
<div class="move"></div>
<button class="btn" name="normalSettings" style="margin-left:185px" type="submit">Save </button>
</form><!-- end form -->
Here is the jQuery I have written for these two forms:
$(function() {
$('form#passwordSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
function proccessPWData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
$(function() {
$('form#normalSettings').submit(function(){
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#normalSettings').serialize(),
function (data) {
proccessData(data);
}
);
return false;
});
});
function proccessData (data) {
$('#status').hide().html('');
if(data=='success'){
$('form#normalSettings').fadeOut();
$('html, body').animate({scrollTop:0});
$("#status").removeClass();
$('#status').addClass('alert alert-success').html('You have successfully changed your personal settings.<br />').slideDown().delay(5000);
redirect("/account");
}
else {
$('html, body').animate({scrollTop:0});
$('#status').removeClass().addClass('alert alert-error').html(data).fadeIn();
setTimeout(function(){
$('#status').slideUp("slow");
},7000);
}
}
And then the PHP code:
if(isset($_POST['normalSettings']))
{
$username = inputFilter($_POST['username']);
if(!$username){
$error ="no username";
}
if(!$error){
echo "success!";
}
}
if(isset($_POST['passwordSettings']))
{
$password = inputFilter($_POST['npassword']);
if(!$username){
$error ="no pw";
}
if(!$error){
echo "success!";
}
}
My problem is, that whenever I submit one of these forms, I see the form with my $error in the #status div.
How can I have multiply forms on one page, but submit the correct ones?
$(function() {
$('form#passwordSettings').submit(function(e){
e.preventDefault(); // prevents the default action (in this case, submitting the form)
$('#status').hide();
$.post(
'index.php?i=a&p=s',
$('form#passwordSettings').serialize(),
function (data) {
proccessPWData(data);
}
);
return false;
});
});
or you could just give an hidden input-field with it
<input type="hidden" name="_normalSettings">
and check in your PHP
if (isset($_POST['_normalSettings']) // ...
This is basically just answer to your question: "How can I have multiple forms on one page, but submit the correct ones?"
I have many dynamically generated forms on a single page and I send them to process file one by one. This is one form simplified:
<form name="form" id="form">
<!--form fields
hidden field could be used to trigger wanted process in the process file
-->
<input type="hidden" name="secret_process_id" value="1" />
<a class="button_ajax">Send form</a>
</form>
<div id="process_msg<?php echo $id; ?>"></div>
And here's the form submit function:
$(document).ready(function() {
$('.submit_ajax').click(function() { //serializes the parent form
//alert($(this).serialize());
dataString = $(this).parent().serialize();
//if you want to echo some message right below the processed form
var id = /id=\d+/.exec(dataString);
var id = /\d+/.exec(id);
$.ajax({
type: 'post',
url: '_process.php?ajax=1', //some or none parameters
data: dataString,
dataType: 'html',
success: function(data) {
$('#process_msg' + id).fadeIn(400);
$('#process_msg' + id).html(data);
}
}); //end of $.ajax
return false;
});
});
All you need is a process file/function and you are ready to go. Works just fine with one or dozens of forms. There you can do something like this:
if ($_POST['secret_process_id']==1){
//do something
}
if ($_POST['secret_process_id']==2){
//do something else
}
//etc.

Categories