In the latest version of wp I created a theme, on the index.php page I have the following HTML:
<p><input type="hidden" name="GreetingAll" id="GreetingAll" value="Hello Everyone!" /> <input type="submit" id="PleasePushMe" /></p>
<div id="test-div1"></div>
My theme functions.php file, I added the following functions:
function add_myjavascript(){
wp_enqueue_script( 'js', get_template_directory_uri().'/lib/js/js.js', array( 'jquery' ));
//wp_localize_script( 'js', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'add_myjavascript' );
function MyAjaxFunction(){
//get the data from ajax() call
$GreetingAll = $_POST['GreetingAll '];
$results = "<h2>".$GreetingAll."</h2>";
// Return the String
die($results);
}
// creating Ajax call for WordPress
add_action( 'wp_ajax_nopriv_MyAjaxFunction', 'MyAjaxFunction' );
add_action( 'wp_ajax_MyAjaxFunction', 'MyAjaxFunction' );
My JavaScript js.js:
jQuery(document).ready(function() {
var GreetingAll = jQuery("#GreetingAll").val();
jQuery("#PleasePushMe").click(function(){
jQuery.ajax({
type: 'POST',
url: 'http://localhost/brenda/wordpress/wp-admin/admin-ajax.php',
data: {
action: 'MyAjaxFunction',
GreetingAll: GreetingAll,
},
success: function(data, textStatus, XMLHttpRequest){
alert(data);
jQuery("#test-div1").html('');
jQuery("#test-div1").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
My Ajax request works fine:
---------------
Request Method:POST
Status Code:200 OK
Form Data
action:MyAjaxFunction
GreetingAll:Hello Everyone!
---------------
Inside my admin-ajax.php the do_action fires. I echoed out a message in plugin.php to test to see if it was firing. However my function MyAjaxFunction() does not get executed. Note the add_actions are carried out, I tested that. My output into the target test-div1 is zero, which is the default status, see below.
if ( is_user_logged_in())
{
do_action( 'wp_ajax_' . $_REQUEST['action'] ); // Authenticated actions
}
else
{
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ); // Non-admin actions
}
//Default status
die('0');
Content-Type - application/json
in file /wp-admin/admin-ajax.php
test send data ($_POST, $_REQUEST...)
if necessary, apply a fix
$headers = getallheaders();
if (strpos($headers['Content-Type'], 'application/json') !== false) {
$input = json_decode(file_get_contents("php://input"), true);
$_REQUEST['action'] = $input['action'];
}
inserted after
/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
here ...
Related
I am trying to delete database row using button, (this is inside my plugin in admin area)
but i am not able to figure out why my ajax call is not working.
Every time i try i recive: 400 bad request all the time.
So i did not manage it yet to call the function properly
this is my button:
<button class="deletebutton" <?php echo 'value="' . $data->id . '"' ?> class="delete"> delete</button>
And i use:
add_action('wp_ajax_delete_data', 'delete_data');
MY function: (i know it work i have use it many times before
'function delete_data($element_id){
global $wpdb;
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}'
And Jquery/AJAX <- here is the problem i think
<script>
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery(document).ready(function() {
jQuery(".deletebutton").click(function(){
var element_id = this.value;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
action: 'delete_data',
data: element_id
dataType: 'data',
});
});
});
</script>
You have given the wrong actions name. see more information here
Change this line
`add_action('wp_ajax_worktmp_delete_absence', 'delete_data');`
With this
`add_action('wp_ajax_delete_data', 'delete_data');`
So the proper of doing this is
Create a separate js file or you can use it upon the existing js file like following while you are enqueuing your script:
wp_register_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . '{your_js_file_location}', array( 'jquery' ), $this->version, false );
wp_localize_script( $this->plugin_name, 'test_ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script($this->plugin_name);
Then
add_action('wp_ajax_delete_data', 'delete_data');
if it is for normal user hten add the folowwing as well
add_action('wp_ajax_nopriv_delete_data', 'delete_data');
Then in your js file
jQuery(document).ready(function($) {
$(".deletebutton").click(function(){
var element_id = this.value;
$.ajax({
url: test_ajax_object.ajaxurl,
type : 'post',
data : {
"action" : 'delete_data', "data_id":element_id},
success: function( response ) {
console.log(response);
}
});
});
});
And in your php file
function delete_data(){
global $wpdb;
$element_id = $_POST['data_id'];
$tablename = $wpdb->prefix . 'my_table';
$wpdb->delete($tablename, array('id' => $element_id));
}
This might work, try once
I have odd (for me) problem with ajax in Wordpress. I do not receive proper response from server. I read Wordpress Codex to find out what I doing wrong, but still I have no clue.
I don't know if it is important or not, but when I tried add a type to ajax syntax, I received an error message.
class databaseClass
{
function __construct()
{
if ( isset($_SERVER['HTTPS']) )
$protocol = 'https://';
else
$protocol = 'http://';
wp_enqueue_script( 'ajaxScript', '/wp-content/themes/bulk/js/ajaxScript.js');
wp_localize_script( 'ajaxScript', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php', $protocol ),
'nonce' => wp_create_nonce( '111')
) );
add_action('wp_ajax_save_sort', 'ajaxFunctionInPHP');
add_action( 'wp_ajax_nopriv_save_sort', 'ajaxFunctionInPHP');
}
function ajaxFunctionInPHP(){
/*check_admin_referrer();
$response['custom'] = "ssss";
$response = json_encode($response);
wp_send_json($response) ;*/
ob_clean();
$response['custom'] = "TEST";
echo $response;
die();
}
}
class ajaxClass extends databaseClass
{
function __construct()
{
parent::__construct();
}
public function ajaxPage()
{
echo '<form name="ajaxTest" type="POST">
<input id="ajaxButton" type="button" value="KLIK"/>
</form>
';
}
}
jQuery( document ).ready( function () {
jQuery('#ajaxButton').click(function() {
var dataFromFunction="";
jQuery.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
success: function (response){
console.log("success message");
console.log(response.custom)
},
error: function (response){
console.log("error message");
}
});
});
} );
success message
ajaxScript.js?ver=5.0.4:15 undefined
Your code seems to be correct but I am sharing my personal approach to doing this in hopes that this might be helpful. Make changes to JS as mentioned below:
jQuery( document ).ready( function ($) {
$('#ajaxButton').click(function() {
var dataFromFunction="Test Data";
$.ajax({
url: my_ajax_object.ajaxurl,
type: 'POST',
data: {
action: 'save_sort',
order: dataFromFunction
},
}).done( function (response){
console.log("success message");
console.log(response.custom)
}).fail(function (response){
console.log("error message");
}).always(function(){
console.log('Ajax Completed');
});
});
});
Also for your script localization, it is good to define the scheme parameter in admin_url function but not necessary so 'ajax_url' => admin_url( 'admin-ajax.php') should be just fine.
You seem to have created nonce but haven't used it and a good practice would be to use create nonce function in your form section and not in localization.
I do have a suggestion for your ajax response function but this is just an advice. Change your function to return as follows:
function ajaxFunctionInPHP(){
$response['dataFromFunction'] = sanitize_text_field($_POST['dataFromFunction']);
wp_send_json( $response);
}
Good Luck!!
I have this button:
bla bla
This button is located on my homebage and is generated by a page builder. What I want to accomplish is when somebody click on the button, it will take them on the checkout, and add a product to the cart. I know that this can be accomplished via a URL, but I need to have this button do other things as well(client idea).
So right now I'm stucked here:
JQuery
jQuery(document).ready(function($){
$(".remove-all").click(function(){
$.ajax({
url: "wp-admin/admin-ajax.php",
data: 'myajax'
});
});
});
PHP
add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
function myajax() {
global $woocommerce;
$product_id = 264;
$woocommerce->cart->add_to_cart($product_id);
die();
}
I'm a javascript noob, so can you please point me to the right direction, or maybe give me a hint on what I'm doing wrong.
Thanks in advance!
As I mentioned in the comments, you can pretty much borrow from core WooCommerce functions.
First, here's the button we'll be trying to ajaxify:
bla bla
Secondly, we'll load our custom script and pass it important variables such as the admin ajax and checkout urls.
add_action( 'wp_enqueue_scripts', 'so_load_script', 20 );
function so_load_script(){
wp_enqueue_script( 'so_test', plugins_url( 'js/test.js', __FILE__ ) );
$i18n = array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'checkout_url' => get_permalink( wc_get_page_id( 'checkout' ) ) );
wp_localize_script( 'so_test', 'SO_TEST_AJAX', $i18n );
}
Now we will write our ajax callbacks, which is copied almost verbatim from WooCommerce core with only a few small modifications:
add_action('wp_ajax_myajax', 'myajax_callback');
add_action('wp_ajax_nopriv_myajax', 'myajax_callback');
/**
* AJAX add to cart.
*/
function myajax_callback() {
ob_start();
//$product_id = 264;
$product_id = 34;
$quantity = 1;
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity );
$product_status = get_post_status( $product_id );
if ( $passed_validation && WC()->cart->add_to_cart( $product_id, $quantity ) && 'publish' === $product_status ) {
do_action( 'woocommerce_ajax_added_to_cart', $product_id );
wc_add_to_cart_message( $product_id );
} else {
// If there was an error adding to the cart, redirect to the product page to show any errors
$data = array(
'error' => true,
'product_url' => apply_filters( 'woocommerce_cart_redirect_after_error', get_permalink( $product_id ), $product_id )
);
wp_send_json( $data );
}
die();
}
And finally the contents of test.js:
jQuery(document).ready(function($){
$(".test-button").click(function(e){
e.preventDefault(); // Prevent the click from going to the link
$.ajax({
url: wc_add_to_cart_params.ajax_url,
method: 'post',
data: {
'action': 'myajax'
}
}).done( function (response) {
if( response.error != 'undefined' && response.error ){
//some kind of error processing or just redirect to link
// might be a good idea to link to the single product page in case JS is disabled
return true;
} else {
window.location.href = SO_TEST_AJAX.checkout_url;
}
});
});
});
You likely need to cancel/prevent the default action of clicking the link, and then redirect once the AJAX call finishes (this is just one way to do it):
jQuery(document).ready(function($){
$(".remove-all").click(function(e){
e.preventDefault(); // Prevent the click from going to the link
var $redirect = $(this).attr('href');
$.ajax({
url: "wp-admin/admin-ajax.php",
data: 'myajax',
success: function () {
window.location.href = $redirect;
}
});
});
});
PHP
add_action('wp_ajax_myajax', 'myajax');
add_action('wp_ajax_nopriv_myajax', 'myajax');
function myajax() {
$product_id = 264;
// Avoid using the global $woocommerce object
WC()->cart->add_to_cart($product_id);
die();
}
I'm setting up a plugin. Now I'm trying to get an AJAX-PHP code working but I don't get the succeed data and all end with an error.
tracker.php is the main plugin file.
This is the function on my tracker.php that prints the title and some HTML code:
require_once dirname(__FILE__) . '/user-listing.php';
function trez_tracker_user_listing(){
?>
<h1>Tracker - User List</h1>
<div class="clicker">Click here</div>
<div id="printer"></div>
<?php
}//trez_tracker_user_listing
So in user-listing.php I added the following code:
function user_listing_enqueuer() {
wp_register_script( "ajax_user_request", WP_PLUGIN_URL.'/tracker/script/ajax_user_request.js', array('jquery') );
wp_localize_script( 'ajax_user_request', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'ajax_user_request' );
}
add_action( 'init', 'user_listing_enqueuer' );
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
add_action("wp_ajax_user_fetcher", "user_fetcher");
And finally the javascript code in /script/ajax_user_request.js:
/* ajax_user_request.js */
jQuery(document).ready( function() {
jQuery(".clicker").click( function() {
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "user_fetcher"},
success: function(response) {
if(response.type == "success") {
jQuery("#printer").html(response)
}
else {
alert("AJAX error")
}
}//success
})//jQuery.ajax
})//Clicker function
})//document ready
When clicking on the <div>, I just get the alert message "AJAX error".
How can I fix it?
Thank you!
You are getting the error because you are not returning the JSON data, you are return string through your user_fetcher function.
function user_fetcher(){
$result = 'Message to display';
return $result;
}//user_listing
Change the user_fetcher function so that it will return the JSON data to the AJAX call.
function user_fetcher(){
$result = 'Message to display';
echo json_encode(array('type'=>'success', 'message'=>$result));
die(0);
}//user_listing
And in jquery check the response like this:
success: function(response) {
if(response.type == "success") {
// Add message
jQuery("#printer").html(response.message)
}
else {
alert("AJAX error")
}
}//success
For the hook wp_ajax_user_fetcher, make sure you are using this after logged in, if you are not logged in in the admin section then you have to use wp_ajax_nopriv_user_fetcher. Or you can use both:
// Work if user is login
add_action("wp_ajax_user_fetcher", "user_fetcher");
// Work if user is not login
add_action("wp_ajax_nopriv_user_fetcher", "user_fetcher");
I am using WooCommerce and added an additional field "location_gps" to collect the location (lat,long) added the ajax call to collect the data. Now I'm stuck getting the data into the current users (user_meta).
Added this in funtions.php
// AJAX - implementation
function add_myscript(){
wp_enqueue_script( 'my-ajax.js', get_bloginfo('template_directory') . "/scripts/my-ajax.js", array( 'jquery' ) );
}
add_action( 'init', 'add_myscript' );
function myAjax(){
global $wpdb;
//get data from our ajax() call
$long = $_POST['long'];
$lat = $_POST['lat'];
$results = "<p>".$lat.", ".$long."</p>"; // this is how it supposed to land in the DB
if($wpdb->insert('location_gps',array(
'long'=>$long,
'lat'=>$lat,
))===FALSE){
echo "Error";
}
else {
echo "Successfully added, row ID is ".$wpdb->insert_id;
}
die();
}
// create custom Ajax call for WordPress
add_action( 'wp_ajax_nopriv_myAjax', 'myAjax' );
add_action( 'wp_ajax_myAjax', 'myAjax' );
Here the JS part..
jQuery(document).ready(function() {
jQuery("#save_loc_button").click(function(){
var long = jQuery("input#long").val();
var lat = jQuery("input#lat").val();
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: { "action": "myAjax", "lat": lat, "long": long },
beforeSend: function(){
jQuery("#test-div").html('processing...');
},
success: function(event, request, settings){
jQuery("#test-div").html('');
jQuery("#test-div").append(event);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});