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' ) ));
}
Related
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.
}
}
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;
}
So i want to send the form data to a custom post type that i created in WP, with the name, email and the message(text). But i cant send it, the AJAX request its not working. Without the ajax request everything its working. What i missed here?
<div class="group">
<form id="form" class="form" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-control1">
<input type="text" placeholder="Name" id="username" name="nume" />
<small>Error message</small>
</div>
<div class="form-control1">
<input type="email" placeholder="Email" id="email" name="email"/>
<small>Error message</small>
</div>
<div class="form-control1">
<textarea class="input" name="mesaj" id="text" name="mesaj" cols="40" rows="5" placeholder="Write a nice message for us:)"></textarea>
<small>Error message</small>
</div>
<button type="submit" id="submit" name="submit">Submit</button>
</form>
</div>
the Jquery:
jQuery('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.post(window.ajaxObject.ajaxUrl,{
method: 'POST',
action: 'messaging_post',
'data':data,
success: function (response) {
console.log(data);
}
})
});
and PHP:
function ajax_scripts1() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() .'/form.js', array ( 'jquery' ), 1.12, true);
wp_localize_script( 'ajax-script', 'ajaxObject',
array( 'ajaxUrl' => admin_url( 'admin-ajax.php') ));
}
add_action( 'wp_enqueue_scripts', 'ajax_scripts1' );
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
add_action('wp_ajax_nopriv_messaging_post', 'messaging_post');
function messaging_post(){
if(isset($_POST['submit']) == '1') {
$new_post = array(
'ID' => '',
'post_type' => 'dn_message',
'post_status' => 'publish',
'post_title' => $_POST['nume'],
'post_content' => $_POST['mesaj'],
);
//here i introduce the data in the custom type post
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
$field_key1 = "movie_form";
$value1 = $title;
$update1 = update_field( $field_key1, $value1, $post_id );
$field_key = "email";
$value = $_POST['email'];
$update = update_field( $field_key, $value, $post_id );
};
}
Try this ajax call:
jQuery('#form').submit(function(event) {
event.preventDefault();
var data = "action=messaging_post&" + $('#form').serialize();
console.log(data);
jQuery.ajax(
{
type: "POST",
url: window.ajaxObject.ajaxUrl,
data: data,
success: function(msg) {
console.log(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
Looks like you are treating wordpress action as ajax property. Ajax action should be sent like this with formdata.
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.
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