jQuery Validate submitHandler not working with WP AJAX / wp_localize_script - php

I am implementing front end login form in wp. And validate form with jquery validate. Using submit handler to submit the form. Validations working good and also ajax, But the main issue is wp_localize_script variables not working in submit handler.
Here's my js code:
var $form = $(this);
jQuery('form#login').validate({
rules:{
username: { required: true },
password: { required: true }
},
submitHandler: function(form) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
// contains all required values for login
},
success: function(data){
document.location.href = ajax_login_object.redirecturl;
}
});
$form.submit();
}
});
Here's my wp code:
function ajax_login_init(){
wp_enqueue_script('script' );
wp_enqueue_script('js-validate' );
wp_localize_script( 'ajax-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => get_site_url().'/page'
));
}
Here I am not getting the ajax_login_object values. Suggest me where I am wrong to implement this.

If you have set $ == jQuery then stick to it. Plus did you mean to put $form as your function parameter or?
Also you're localizing your script on what? Where is the ajax-script handle.
Try with
function ajax_login_init(){
wp_enqueue_script('script' );
wp_enqueue_script('js-validate' );
wp_localize_script( 'js-validate', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => get_site_url().'/page'
));
}
And see if your localized script is in the DOM (inspect it with Chrome and search for ajaxurl and redirecturl). JS part:
var $form = $(this);
$('form#login').validate({
rules:{
username: { required: true },
password: { required: true }
},
submitHandler: function(form) {
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
// contains all required values for login
},
success: function(data){
form.submit();
document.location.href = ajax_login_object.redirecturl;
}
});
}
});

Related

Wordpress ajax request not working properly

I am new to wordpress, i make a ajax request on click button and it print the data, but ajax is not giving me any response. Please help me to find out the error.
Here is my code
add_action("wp_ajax_delivery_options", "delivery_options");
add_action("wp_ajax_nopriv_delivery_options", "delivery_options");
function delivery_options()
{
echo json_encode(array('type' => 'success'));
wp_die();
}
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/js/custom.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
Ajax
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});
})(jQuery);
Any solution appreciated!
you have to pass "callback function name" in data: { action: 'delivery_options', delivery_option: data },
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { action: 'delivery_options', delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});})(jQuery);

Need help converting the ajax and php for wordpress

From guides I have gotten this far:
add_action('wp_enqueue_scripts', 'do_enqueue_scripts');
function do_enqueue_scripts()
{
wp_enqueue_script('Java', plugins_url( '/js/form.js', __FILE__ ), array('jquery'), '1.0', true);
wp_localize_script( 'Java', 'start', array(
'code' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_ajax_nopriv_func', 'func');
add_action('wp_ajax_func', 'func');
function func()
{
$From = $_POST['dateTo'];
$To = $_POST['dateFrom'];
$Name = $_POST['Name'];
echo $From . " - " . $To . " - " . $Name;
die();
}
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data) {
alert(data);
}
});
}));
My problem comes in with the AJAX call. I am still getting used to this action system WordPress is using and I am not sure what I need to change my data to. I have a generic form with 2 dates and a name; nothing crazy. However the returned data to my AJAX call is zero.
I believe my issue now is how I m either returning data to my ajax or with the data type I am send to my PHP function func().
No errors in chrome or mozilla consoles.
Add a hidden input field to your form with the name of the action so wp can execute the right function
<input type="hidden" name="action" value="func">
change your ajax to:
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: start.code,
type: "POST",
data: $(this).serialize(),
cache: false,
success: function(data) {
alert(data);
}
});
}));

jQuery ajax call works only if its debugged step by step

$('.single_add_to_cart_button').click(function() {
$.ajax({
type: "POST",
url: script_e.ajaxurl, //url loaded from the plugin
data: {id:test},
cache: false,
success: function(data){
alert(data);
}
});
});
//php
public function enqueue_scripts(){
wp_enqueue_script( 'e_jquery', plugin_dir_url( __FILE__ ).'../assets/js/script_e.js' );
wp_localize_script( 'e_jquery', 'script_e',
array(
'ajaxurl' => plugin_dir_url( __FILE__ ).'event-capture.php' ,
)
);
}
add_action( 'wp_enqueue_scripts', array($this,'enqueue_scripts') );
I am trying to pass some variables in the the PHP script when the button is clicked, the php script is located in the plugin.
Only way this works is if I debug step by step in the firebug, then the value is passed, else it fails.
Basically add event.preventDefault();after ajax call
Something like this,
$('.single_add_to_cart_button').click(function(event) {
$.ajax({
type: "POST",
url: script_e.ajaxurl, //url loaded from the plugin
data: {id:test},
cache: false,
success: function(data){
alert(data);
}
});
event.preventDefault();
});

$.ajax POST is not posting

This is exactly what the title describes, when I hit submit, and use php file to echo the result its empty.
$( "form#fileupload" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( 'form#fileupload' ).serialize();
$.ajax({
url: 'create_adgroup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
$("#footer").html(returndata);
}
});
return false;
});
and the php is as such:
ECHO "PRINT POST: ".print_r($_POST);
echo "le titre: ".$_POST['title'];
any suggestions please the alert returns the serialized string and it has all the data and title is one of them.
Try with this, usually i did the ajax POST with this kind of code:
$( "form#fileupload" ).on( "submit", function( event ) {
$.post('create_adgroup.php', $('form#fileupload').serialize(), function(data) {
$('#footer').html(data);
});
event.preventDefault();
return false;
});
For uploading file using ajax I prefer using jquery.form.js plugin.
Reference

Submitting a form with ajax in Wordpress

I am trying to get the results of an ajax request in wordpress, but I am getting result of '0' in an alert box of javascript, so the form looks like this:
<form class="form" id="ajax-contact-form" action="#">
<input type="text" name="name" id="name" placeholder="Name" required="">
<button type="submit" class="btn">Submit</button>
</form>
The javascript looks like this:
$('#ajax-contact-form').submit(function(e){
$.ajax({
data: {action: 'contact_form'},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data); // This prints '0', I want this to print whatever name the user inputs in the form.
}
});
})
And the PHP:
add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');
function contact_form()
{
echo $_POST['name'];
}
Does anyone know if the code above is correct, I have also tried $_REQUEST['name'] and it doesnt work.
Thanks soo much,
Try something like this, you did not add the name parameter you are expecting in your PHP contact_form function, so you must add it to the data attribute in the jQuery ajax function call.
$('#ajax-contact-form').submit(function(e){
var name = $("#name").val();
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
console.log(data); //should print out the name since you sent it along
}
});
});
Revisiting the answer, year is 2022. The Accepted answer is accepting BLINDLY any AJAX request without verifying WordPress Nonces. AJAX request should be validated as a legitimate request instead of a potentially nefarious request from some unknown bad actor.
#see https://developer.wordpress.org/plugins/javascript/enqueuing/#nonce
The first thing your AJAX handler should do is verify the nonce sent by jQuery with check_ajax_referer(), which should be the same value that was localized when the script was enqueued.
First we pass the AJAX url and create and pass our nonce through wp_localize_script(). wp_localize_script() must be called after the script has been registered using wp_register_script() or wp_enqueue_script().
<?php
wp_localize_script( 'script', 'localize',
array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
)
);
From our script.js file we declare our AJAX function.
$(function(){
$('button').click(() => {
$.ajax({
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
test: 'test',
/**
* The action parameter is the The dynamic portion of the wp_ajax_{$action} action hook (Ajax action callback being fired).
*
* #see https://developer.wordpress.org/reference/hooks/wp_ajax_action/
* #see https://developer.wordpress.org/reference/hooks/wp_ajax_nopriv__requestaction/
*/
action: '_POST_action',
},
success: (res) => {
console.log(res);
}
});
});
});
And we process the result and send a JSON response back to an Ajax request.
<?php
add_action( 'wp_ajax__POST_action', function () {
if ( check_ajax_referer( '_ajax_nonce' ) ) {
$test = $_POST['test'];
//...
wp_send_json_success();
} else {
wp_send_json_error();
};
} );
You should add an attribute for name too in your javascript.
It may look like this........
$('#ajax-contact-form').submit(function(e){
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
})
You should include this script in functions.php
wp_register_script('my_script_handle','');
wp_add_inline_script('my_script_handle', "var techy_ajaxurl = '".admin_url( 'admin-ajax.php' )."';" );
wp_enqueue_script( 'my_script_handle' );
and in js change to this
$.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: techy_ajaxurl,
success: function(data) {
alert(data);
}
});
It will work 100% tested

Categories