Jquery, PHP and Ajax form without refreshing - javascript

I try to prepare simple contact form with jquery, ajax and php without refresh. Everything works fine besides event.preventDefault();
That's my files:
contact_engine.php
<?php
$name = $_POST['name'];
...
$from = 'from';
$to = 'to';
$subject = 'subject';
$human = '4';
$body = ".........";
if ($_POST['submit'] && $human == '4') {
if (mail ($to, $subject, $body, $from)) {
echo '<p>Thanks</p>';
} else {
echo '<p>Error</p>';
}
} else if ($_POST['submit'] && $human != '4') {
echo '<p>You answered the anti-spam question incorrectly!</p>';
}
?>
Ajax/jQuery
$('form').on('submit', function(event){
event.preventDefault();
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
}
});
});
PHP
<form method="post" action="<?php bloginfo('template_directory'); ?>/contact_engine.php">
<div class="box">
<input type="text" name="name" class="pola formbg name" placeholder="Name" />
.
.
.
.
<p><input id="form-button" type="submit" name="submit" value="Send" /></p>
</div>
<br style="clear: left;" />
</form>
When I remove event.preventDefault(); everything is ok, I receive a message from form but site are refreshing and I see 'thanks' message.
I used Wordpress as you probably seen.

Yeah, in this kind of instance why have a form/submit button.
Remove the form and change the input from a submit button to a standard button.
Put the function on the button, job done.
$('#form-button').on('click', function(event){
$.ajax('.../contact_engine.php', {
type: 'POST',
data: $('form').serialize(),
success: function(result) {
//do something with the return code
}
});
});

Give your form an ID - I think the problem is your submit handler does is not firing:
$( "#myForm" ).submit(function( event ) {...
and then change your jQuery to read:
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
...
See http://api.jquery.com/jquery.post/

Related

How to handling validation with ajax request for woocommerce form

I am creating my custom form-edit-account.php template. This contains a form that allows users to change their name, surname, password and other info. Originally the form does not perform ajax requests, you click the save changes button, the data is saved and the page is reloaded. The required fields and their validity are managed by the file https://woocommerce.github.io/code-reference/files/woocommerce-includes-class-wc-form-handler.html#source-view.218
What I did was create ajax request for the form in order to save the fields without the page refresh. The fields are edited and updated correctly, so it works. However, handling validation not working.
Somehow I need field handling validation but I don't know how to proceed I'm stuck at this point. I have two ideas I could work on:
Try somehow to make the original handling validation work.
Create a custom handling validation with js or php separately from the original file, but I don't know if this is correct.
How could I handle field validation? I hope someone can help me understand how I could do this, I appreciate any help and thank you for any replies.
Example of My-Form
<form name="Form" class="mts-edit-account" action="<?php echo admin_url('admin-ajax.php'); ?>" method="post" enctype="multipart/form-data" <?php add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );?> >
<!-- Fist & Last Name Field -->
<div class="row name_surname">
<div class="form-row">
<label class="t3" for="account_first_name">Nome *</label>
<input type="text" placeholder="Inserisci il tuo nome" class="field-settings" name="account_first_name" id="account_first_name" value="<?php echo esc_attr( $user->first_name ); ?>" />
</div>
<div class="form-row">
<label class="t3" for="account_last_name">Cognome *</label>
<input type="text" placeholder="Inserisci il tuo cognome" class="field-settings" name="account_last_name" id="account_last_name" value="<?php echo esc_attr( $user->last_name ); ?>" />
</div>
<!-- Save Settings -->
<p style="margin-bottom: 0px!important;">
<?php wp_nonce_field( 'save_account_details', 'save-account-details-nonce' ); ?>
<button type="submit" class="edit-account-button" name="save_account_details" value="<?php esc_attr_e( 'Save changes', 'woocommerce' ); ?>"><?php esc_html_e( 'Salva modifiche', 'woocommerce' ); ?></button>
<input type="hidden" name="action" value="save_account_details" />
</p>
</div>
</form>
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) { //form onsubmit ecent
e.preventDefault(); // the preventDefault function stop default form action
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success: function(data) {
alert('Form Inviato');
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'wp_ajax_nopriv_save_account_details', 'save_account_details' );
add_action('woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
// A default response holder, which will have data for sending back to our js file
$response = array(
'error' => false,
);
// Example for creating an response with error information (This not working)
if (trim($_POST['account_first_name']) == '') {
$response['error'] = true;
$response['error_message'] = 'Name is required';
if (trim($_POST['account_first_name']) == '') {
$response['status'] = false;
$response['message'] = 'Name is required';
}else{
$response['status'] = true;
$response['message'] = 'success';
}
// Exit here, for not processing further because of the error
echo json_encode($response);
exit();
}
exit(json_encode($response));
}
Thanks to the intervention of Martin Mirchev in the comments I was able to solve the problem.Here is the solution for anyone who is in the same conditions.
(The form remained the same)
Js File
jQuery(document).ready(function($) {
$('.mts-edit-account').on('submit', function(e) {
e.preventDefault();
//Ajax function
jQuery.ajax({
type: "post",
data: jQuery(".mts-edit-account").serialize(),
url: "wp-admin/admin-ajax.php",
success : function( response ) {
//jQuery('.woocommerce-notices-wrapper').append(response);
jQuery('.woocommerce-notices-wrapper').prepend(response);
}
});
});
});
functions.php
add_action( 'wp_ajax_save_account_details', 'save_account_details' );
add_action( 'woocommerce_save_account_details_errors','save_account_details', 10, 1 );
function save_account_details() {
if (trim($_POST['account_first_name']) == '') {
$response = wc_print_notices();
} else {
$response = "Settings Saved!";
}
// Don't forget to exit at the end of processing
echo json_encode($response);
exit();
}

PHP/Ajax Form Sumission

I have designed a Sidebar Floating Form with PhP/Ajax which is working and sending submission to my targeted email. Here is the Link: http://logohour.com/form.html but when a visitor fill and submit the form successfully it routes him to another page for the confirmation.
This shouldn't be like this and must be stick to the homepage with popup Message as per my coding:
<div id="sendingMMessage" class="statusMessage"> <p>Sending your message. Please wait...</p> </div>
<div id="successMMessage" class="statusMessage"> <p>Thanks for sending your message! We'll get back to you shortly.</p> </div>
Below you may find my Ajax & PHP for reference:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }
Below the simple ajax form submission. Hope it will help your need.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(function () {
$('form#consultationForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'receivedConfirmation.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#receivedStatus').attr('style','display:block');
$('#receivedStatus').html(result);
}
});
e.preventDefault();
});
});
</script>
<form id="consultationForm" method="post">
Firstname: <input name="fname" />
Lastname: <input name="lname" />
<div style='clear:both;'></div>
<input type="submit" name="submit" value="save"/>
<input type="reset" name="cancel" value="cancel"/>
</form>
<div id='receivedStatus' style='display:none;'></div>
receivedConfirmation.php
<?php
echo "<PRE>";
print_r($_POST);
echo "</PRE><br>";
//do your DB stuffs here and finally echo your response based on success or failure
echo "Thanks for sending your message! We'll get back to you shortly.";
echo "<br>Click your browser's Back button to return to the page."
?>
First you have to avoid the normal form submission for this form and you can do this by using normal button instead of submit button.
<input type="button" id="sendMMessage" name="sendMMessage" value="Submit">
Execute a javascript ajax submit code onclick of sendMMessage id.
and this will solve your problem.
Updated answer :
$( "#target" ).click(function() {
// put your ajax form submit code here
$.ajax({
type: "POST",
url: 'http://logohour.com/sidebar-form.php',
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data); // show response from the php script.
}
});
});
If you are still unclear about this I will explain you more detail.
thanks.

Sending e-mail form using PHP and AJAX

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});
Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better
You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action
Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"
What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.

send form via AJAX in jQuery then save in MySQL but doesn't work

as title, I am a beginner about website design.
Please never mind if I ask a stupid question.
while i send the form, it didnt work.
here is html:
<form id="form1" name="form1" action="toSQL.php" method="POST" accept-charset="utf-8">
<input type="text" name="Cliname" id="textfield" maxlength = "10" />
<textarea name="message" id="message" rows="3" maxlength = "20" ></textarea>
<input type="submit" value="submit" id="submit" />
</form>
<div class="alert"></div>
and here is js:
<script type="text/javascript">
$(document).ready(function() {
var form = $(this) ;
var submited = $('#submit') ;
var alerted = $('.alert') ;
form.on( 'submit', this, (function(event) {
event.preventDefault();
if ( $.trim($form.find('input[name="Cliname"]').val()) == "" || $.trim($form.find('input[name="message"]').val()) == "" ) {
alert( "please enter!!" ) ;
return ;
}
else {
$.ajax({
url: 'toSQL.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: form.serialize(), // serialize form data
beforeSend: function() {
alerted.fadeOut();
},
success: function(data) {
alerted.html(data).fadeIn(); // fade in response data
form.trigger('reset'); // reset form
},
error: function(e) {
console.log(e)
}
});
}
}));
});
</script>
server side php:
<?php
if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) ){
if (isset($_POST['Cliname']) AND isset($_POST['message'])) {
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
if (send($name, $message)) {
echo 'Message sent!';
} else {
echo 'Message couldn\'t sent!';
}
}
else {
echo 'All Fields are required';
}
return;
}
function send( $name, $message ) {
$time = date("Y-m-d H:i:s");
$mysqlConnection=mysql_connect("localhost", 'root', '') or die("connect error!");
mysql_select_db('test') or die ("db error!");
$queryStr="INSERT INTO fortest (time, message, name)
VALUES ( '$time', '$message', '$name')";
mysql_query($queryStr,$mysqlConnection) or die(mysql_error());
return true ;
}
?>
here is the website i reference : http://www.w3bees.com/2013/08/submit-form-without-page-refresh-with.html
Did i miss something?
As a couple people have mentioned already, you are trying to serialize your entire dom object, which isn't going to work. Change it to var form = $("#form1") and it should work.
I recommend you open the webpage in chrome dev tools and click the network tab, click preserve log and then submit the form. When it is submitted you'll see the full headers that were sent to the server and can verify it works correctly to help narrow down the problem

Efficient way to use jquery submit [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 9 years ago.
I am looking for a basic jQuery function to submit a form without refreshing the page. I had this once but I can't find it, all I can find is the long boring and complicated ones you have to update to add an input field into the form.
From what i remember the code includes the URL of the process file, the form id and the #results id.
you can use Ajax form submit as follow;
<form id="formId" action="url" method="post">
</form>
<script type="text/javascript">
var form = $('#formId');
form .submit(function () {
$.ajax({
type: "POST",
url: "url",// url which you want to post
data: formData,
success: function (data) {
alert('success');
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage); // Optional
}
});
});
</script>
<?php
$message = '';
if( isset( $_GET['name'] ) ) {
if( empty( $_GET['name'] ) ) $message = 'Name is required';
else $message = 'Form submitted successfully.';
}
?>
<form id="ajax-form">
<input name="name" type="text">
<input type="submit">
<div id="message"> <?php echo $message; ?> </div>
</form>
<script>
$( '#ajax-form' ).submit( function( e ) {
e.preventDefault();
var query = $(this).serialize();
$(this).find('#message').load( window.location.href + '?' + query + ' #ajax-form #message' );
});
</script>

Categories

Resources