jQuery ajax call works only if its debugged step by step - php

$('.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();
});

Related

Learning AJAX with Wordpress and can't figure out how to debug my mistake

I'm new to wordpress and I'm having trouble getting an AJAX call to work in a plugin. Nothing I try to print to console on the frontend shows up while I have an ajax request running and I don't know how to make anything print to anywhere from the wordpress backend.
If possible, I'd appreciate if someone could tell me how to debug my mistake.
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#question-form').submit(function(e) {
e.preventDefault();
console.log(this);
//var formData = new FormData(this);
var formData = {
action: 'create_question',
post_content: jQuery('#question-form #question-content').val()
};
$.ajax({
type: 'post',
dataType: 'json',
url: '<?php echo wp_localize_script(admin_url( "admin-ajax.php" )); ?>',
data: formData,
processData: false,
contentType: false,
success: function(response) {
if(response.type == "success") {
console.log("test");
// Update question display
}
else {
alert("Error");
}
},
error: function(xhr, textStatus, error) {
console.log(xhr.responseText);
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
</script>
<?php
add_action( 'wp_ajax_create_question', 'create_question_handler' );
add_action( 'wp_ajax_nopriv_create_question', 'create_question_handler' );
function create_question_handler() {
wp_send_json(123);
}
?>
When I delete the ajax, it logs the formdata to console. Otherwise, nothing logs to console except for a navigation to a new blank page. I was under the impression that AJAX is used to avoid loading a new page, so this also confuses me.
I don't know how to confirm whether my hooks are being created or where to look to see if my handler is outputting anything.
I appreciate any help.
your url parameter is using an unnecessary function. it should be:
url: '<?php echo esc_url( admin_url( 'admin-ajax.php') ); ?>',

WordPress fuel plugin how to call ajax actions

I have installed the wordpress fuel plugin. By this I have created a plugin to list the property.
Here I have integrated one ajax call like this
In my view file i use this below code:
$('#collapse3').click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: { },
success: function(data){
$('#collapse3_res').html(data);
}
});
});
By using this code, it is not working. I don't know how to write this. Please help me. Thanks
Try Ajax code like this:
jQuery( document ).on( 'click', '#collapse3', function() {
var data = { };
$.ajax({
type: "POST",
url:"<?php echo $plugin->dispatchRequest("saleshome/index",array('lat' => $latitude,'lng'=>$longitude)); ?>",
data: data,
cache: false,
success: function(response){
$("#collapse3_res").html(response);
}
});
});
javascript add in wp_footer hook on function.php
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
bellow wp_ajax hook add on function.php
add_action( 'wp_ajax_add_foobar', 'prefix_ajax_add_foobar' );
function prefix_ajax_add_foobar() {
// Handle request then generate response using WP_Ajax_Response
// Don't forget to stop execution afterward.
wp_die();
}

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 Validate submitHandler not working with WP AJAX / wp_localize_script

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;
}
});
}
});

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