Check for existing email in WooCommerce checkout using Ajax - php

I'm trying to check inserted value for billing_email field in WooCommerce checkout to know if it is existed or not.
Here is code in functions.php
add_action('wp_enqueue_scripts', 'live_validation' );
add_action('wp_ajax_validate_email', 'validate_email_input');
add_action('wp_ajax_nopriv_validate_email', 'validate_email_input');
function live_validation() {
wp_enqueue_script( "validate_email", get_stylesheet_directory_uri() . '/check-email.js', array( 'jquery' ) );
wp_localize_script( "validate_email", "validateEmail", array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
function validate_email_input() {
global $wpdb;
$email = $_POST['billing_email'];
if ( email_exists($email) ) {
echo 'existed';
} else {
echo 'not exist';
}
exit;
}
And this is js file
jQuery(document).ready(function($) {
$('input[name=billing_email]').change(function() {
var input_value = $(this).val();
$.post( validateEmail.ajaxurl, { action:'validate_email', billing_email:input_value }, function(data) {
$('.message').html(data);
});
});
});
HTML form
<p class="form-row form-row form-row form-row-first validate-required woocommerce-validated" id="billing_email_field">
<label for="billing_email" class="">Email <abbr class="required" title="required">*</abbr></label>
<input type="text" class="input-text " name="billing_email" id="billing_email" placeholder="Email" value="abc#gmail.com"></p>
<span class="message"></span>
I can see admin-ajax file fired when input value of billing_email changed, but the notification didn't show.
Please help. Thanks.

Related

Apply coupon code on Woocommerce checkout page with AJAX

I moved the Woocommerce coupon form by editing the review-order.php based on this method
I would like to know if it's possible to make the coupon code apply with AJAX (without reloading the page) like in the cart page. I don't know where to start, please help.
as per your shared link, if you follow the same means you are using the coupon form inside the checkout form, so you should remove the coupon form tag and then use it.
Copy woocommerce review-order.php and past inside your active then woocommerce folder.
Open review-order.php and past coupon HTML inside table structure like this:
<tr class="coupon_checkout">
<td colspan="2">
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! wc_coupons_enabled() ) {
return;
}
?>
<i class="fa fa-plus"></i> REDEEM A PROMO CODE/GIFT VOUCHER
<div class="checkout_coupon" method="post" style="display:none">
<p class="form-row form-row-first">
<input type="text" name="coupon_code" class="input-text" placeholder="<?php esc_attr_e( 'Coupon code', 'woocommerce' ); ?>" id="checkout_coupon_code" value="" />
</p>
<p class="form-row form-row-last">
<input id="checkout_apply_coupon" type="button" class="button" name="apply_coupon" value="<?php esc_attr_e( 'Apply Coupon', 'woocommerce' ); ?>" />
</p>
</div>
</td>
</tr>
Add jQuery code either your custom.js file or directly on the footer page like this:
<script>
jQuery(document).on('click','#checkout_apply_coupon', function() {
// Get the coupon code
var code = jQuery( '#checkout_coupon_code').val();
var button = jQuery( this );
data = {
action: 'ajaxapplucoupon',
coupon_code: code
};
button.html( 'wait.');
// Send it over to WordPress.
jQuery.post( wc_checkout_params.ajax_url, data, function( returned_data ) {
if( returned_data.result == 'error' ) {
jQuery( 'p.result' ).html( returned_data.message );
} else {
setTimeout(function(){
//reload with ajax
jQuery(document.body).trigger('update_checkout');
button.html( 'Apply');
}, 2000);
console.log( returned_data+code );
}
})
});
</script>
As I have tested on my checkout page it's working perfectly like this:
https://www.loom.com/share/7dfc833895d248f191ba327cf5290403
Optional (if not setup wp_localize_script yet then add into functions.php)
function custom_enqueue() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/custom.js', array('jquery') ); // optional - if you want to add custom.js then goto theme directory- > js -> and create/add custom.js file
wp_localize_script( 'ajax-script', 'wc_checkout_params', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); // setup ajax call url
}
add_action( 'wp_enqueue_scripts', 'custom_enqueue' );
You can modify the snippet below to match your styles.
Place the coupon form below in review-order.php or include it from a separate file
<form class="checkout_coupon m-0 p-0 border-0 woocommerce-form-coupon grid grid-cols-3" action="<?php echo esc_url(wc_get_cart_url()); ?>" method="post">
<input type="text" name="coupon_code" class="input-text col-span-2" placeholder="<?php esc_attr_e('Coupon code', 'woocommerce'); ?>" id="coupon_code" value=""/>
<button type="submit" class="theme-button-secondary" name="apply_coupon"><i class="fas fa-arrow-right"></i></button>
</form>
<script>
jQuery(document).on('submit', 'form.checkout_coupon', function (e) {
e.preventDefault()
var form = jQuery(this)
form.block({message: null, overlayCSS: {background: '#FFF', opacity: 0.6}})
jQuery.post(wc_checkout_params.ajax_url, {
action: 'ajax_apply_coupon',
coupon_code: form.find('[name="coupon_code"]').val()
}).done(function () {
jQuery(document.body).trigger('update_checkout')
form.unblock()
}).fail(function (data) {
jQuery(document.body).trigger('update_checkout')
form.unblock()
})
})
</script>
If you want to include it from different file use this
add_action('woocommerce_review_order_after_cart_contents', function () {
if (is_checkout()) {
wc_get_template('checkout/coupon.php');
}
});
Add your ajax handler with the coupon logic in your function.php
function ajax_apply_coupon()
{
$coupon_code = null;
if (!empty($_POST['coupon_code'])) {
$coupon_code = sanitize_key($_POST['coupon_code']);
}
$coupon_id = wc_get_coupon_id_by_code($coupon_code);
if (empty($coupon_id)) {
wc_add_notice(__('Sorry, there has been an error.', 'woocommerce'), 'error');
wp_send_json_error(['message' => __('Sorry, there has been an error.', 'woocommerce')], 400);
}
if (!WC()->cart->has_discount($coupon_code)) {
WC()->cart->add_discount($coupon_code);
}
wp_send_json_success(['message' => __('Coupon code applied successfully.', 'woocommerce')], 200);
}
add_action('wp_ajax_ajax_apply_coupon', 'ajax_apply_coupon');
add_action('wp_ajax_nopriv_ajax_apply_coupon', 'ajax_apply_coupon');

WP admin ajax return 404

I want create custom login page. I have some problems with ajax-admin php. When i send data for loggined i get response 0, and 404 error. Also when i try get success response data similarly give null. Where my mistake ?
My main task after successful authorization was redirected to the main page and if unsuccess authorization give error text
login.php
<form id="login" action="login" method="post" >
<p class="status"></p>
<div class="form-group">
<label>Email</label>
<input class="form-control required" id="logusername" type="email" name="logusername">
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control required" id="logpassword" type="password" name="logpassword" >
</div>
<a class="forgot-pass" href="<?php echo wp_lostpassword_url(); ?>">Forgot Password</a>
<div class="d-flex justify-content-center mt-3">
<input type="submit" class="btn btn-success submit_button" value="Login">
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</div>
</form>
ajax-login-script.js
jQuery(document).ready(function($) {
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajax_login',
'username': $('form#login #logusername').val(),
'password': $('form#login #logpassword').val(),
'security': $('form#login #security').val() },
success: function(data){
console.log(data); // null
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
} else {
console.log(false);
}
}
});
e.preventDefault();
});
});
function.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery'), time() );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...!')
));
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
check_ajax_referer( 'ajax-login-nonce', 'security' );
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( !is_wp_error($user_signon) ){
wp_set_current_user($user_signon->ID);
wp_set_auth_cookie($user_signon->ID);
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
You must have to pass correct hook name after,
The Hook must be end with the name of action you are passing through jQuery request ex.
wp_ajax_nopriv_{action_name} so please correct it first.
add_action( 'wp_ajax_nopriv_ajax_login', 'ajax_login' );
Put this action outside the function and do your login condition inside the hook callback function.
function ajax_login(){
if (!is_user_logged_in()) { // It's not necessary it should be based on your requirement
// Your code goes here.
}
}

Wordpress based ajax form submission not working

Basically I am beginner to WordPress and ajax and I am trying to make a custom newsletter with Wordpress using ajax method. It seems something is wrong with my code which I have been trying to sort for quite while. any help would be appreciated.
front page code:
<form id="myform" method="POST">
<div class="newsletter" data-aos="fade-up" data-aos-delay="300">
<h2>Newsletter</h2>
<div class="form-element">
<input type="text" class="input-element" name="email" id="email" placeholder="Email"><br>
<span class="email-message" id="email_msg"></span>
<button class="btn form-btn" name="submit" value='Submit' id="submit" type="button">Subscribe</button>
</div>
</div>
<div class="messageDiv"></div>
</form>
ajax:
<script>
jQuery(function() {
jQuery('#myform').submit(function(event){
event.preventDefault();
jQuery.ajax({
dataType : "json",
type : "post",
data : jQuery('#myform').serialize(),
url : my_ajax_object.ajax_url,
success:function(data)
{
jQuery('.messageDiv').html(data.message);
}
});
});
});
</script>
function.php:
function my_enqueue() {
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
if(isset($_POST['email'])){
global $wpdb;
$email = $_POST['email'];
$con = new mysqli("localhost", "root", "", "blogger", 3306);
$table_name ='newletter';
$sql=$wpdb->insert("newletter", array("email" =>$email));
if($rowResult == 1){
echo json_encode(array('message' => '<h1>form submit sucesss</h1>', 'status'=> 1 ));
}else{
echo json_encode(array('message' => '<h1>error submission</h1>', 'status'=> 0 ));
}
die;
}

Ajax in Wordpress form submission

I'm following the page here - http://solislab.com/blog/5-tips-for-using-ajax-in-wordpress/#admin-ajax
So I have a simple form
<form role="form">
<div class="form-group">
<label class="">Name</label>
<input type="text" id="name" class="form-control" name="name" />
</div>
<div class="form-group">
<label class="">Email</label>
<input type="text" id="email" class="form-control" name="email" />
</div>
</form>
In functions.php I have
// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . '/js/compiled/main.min.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );
function myajax_submit() {
// get the submitted parameters
$name = $_POST['name'];
$email = $_POST['email'];
// generate the response
$response = json_encode( array( 'success' => true ) );
// response output
header( "Content-Type: application/json" );
echo $response;
// IMPORTANT: don't forget to "exit"
exit;
}
I'm using grunt to concatenate my js files which are then minified to /js/compiled/main.min.js
This minified file includes the js to validate the form and the post function.
The js
$atj(function(){
$atj('.js-training').click(function(e) {
//
e.preventDefault();
if(verfiyTrainingFields()) {
$atj.post(
MyAjax.ajaxurl,
{
action : 'myajax-submit',
firstName : $atj("#name").val(),
email : $atj("#email").val(),
},
function(response){
alert(response);
}
)
}
});
})
//Verfiy
function verfiyTrainingFields() {
var flag = true;
var name = $atj('#name');
var email = $atj('#email');
if(name.val().indexOf(' ') === -1 ){
name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
fadeOut();
flag = false;
}
if(!IsEmail(email.val())){
email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
fadeOut();
flag = false;
}
return flag;
}
I'm getting an error in the console
Uncaught ReferenceError: MyAjax is not defined
UPDATE
add_action( 'wp_enqueue_scripts', 'add_my_script' );
function add_my_script() {
wp_register_script('scripts',get_template_directory_uri() . '/js/compiled/main.min.js', array('jquery'),1 ,true);
wp_enqueue_script('scripts');
//
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . '/js/compiled/main.min.js', array( 'jquery' ),'', true );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ));
}

Wordpress contact form - ajax, wp_mail

I'm tring to create a simple contact form using jquery to validate the form and ajax to pass it to php and WP wp_mail to send it.
I have a simple form like this.
<form role="form">
<div class="form-group">
<label class="">Name</label>
<input type="text" id="name" class="form-control" name" />
</div>
<div class="form-group">
<label class="">Email</label>
<input type="text" id="email" class="form-control" name="email" />
</div>
<?php wp_nonce_field( 'atex_php', 'atex_nonce' ); ?>
<button class="submit">Submit</button>
</form>
jQuery to validate the inputs and send to php
//IsEmail and fadeOut functions aren't shown
$atj(function(){
$atj('submit').click(function(e) {
e.preventDefault();
if(verfiyFields()) {
$atj.post({
data : {
action : "request",
firstName : $atj("#name").val(),
email : $atj("#email").val(),
}
})
}
});
})
//Verfiy
function verfiyFields() {
var flag = true;
var name = $atj('#name');
var email = $atj('#email');
if(name.val().indexOf(' ') === -1 ){
name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
fadeOut();
flag = false;
}
if(!IsEmail(email.val())){
email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
fadeOut();
flag = false;
}
return flag;
}
And the php in the function.php
add_action( 'wp_ajax_nopriv_request', 'my_action_callback' );
function my_action_callback() {
if ( isset( $_POST['atex_nonce'] ) && wp_verify_nonce( $_POST['atex_nonce'], 'atex_php' ) ) {
$name = $_POST['firstName'];
$email = $_POST['email'];
$send_to = me#test.co.uk;
$subject = 'Request from'. $name;
$success = wp_mail($send_to, $subject, $message);
if($success){
return true;
}else{
return false;
}
}
}
I'm getting a 404 Not Found for [object%20Object] in the Network tab of chrome dev tools when the submit is clicked.
How can I get this to work
you need to enqueue some scripts:
Let's say you validation script is in a file called validationForm.js
function ajaxScript(){
$params = array(
'ajaxurl' => admin_url('admin-ajax.php')
);
wp_enqueue_script( 'validation', get_template_directory_uri() . '/js/validationForm.js', array(), '', true );
wp_localize_script( 'validation', 'ajax_object', $params );
}
add_action( 'wp_enqueue_scripts', 'ajaxScript' );
Also you need to add this action hook:
add_action('wp_ajax_amc_form_fr', 'my_action_callback');
Then, use ajax jquery function to send info:
var dataString = $(form).serialize();
jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl,
dataType : 'JSON',
data : 'action=jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl,
dataType : 'JSON',
data : 'action=amc_form_fr&'+dataString,&'+dataString,
success: function(response) {
console.log(response);
// your code
}
If im not wrong, i think that is. And check this link

Categories