Wordpress, admin menu, Ajax 400 bad request - ajax

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

Related

wordpress ajax won't send response as array, why?

i have worked for wordpress project which need to call back some result from database via ajax .
the problem is the response will be in string form which is not as i aspect .
here is whats my try :
//The PHP
function edit_something() {
if ( isset($_REQUEST) ) {
global $wpdb;
$ID = intval( $_REQUEST['ID'] );
$query= "SELECT * FROM `TABLE` WHERE `ID` = '$ID';";
$result= $wpdb->get_results( $queryHavadesEnsani, 'ARRAY_A' );
print_r( $resultsHavadesEnsani );
}
}
die();
}
add_action( 'wp_ajax_edit_something', 'edit_something' );
and the endpoint
function myplugin_ajaxurl() {
echo '<script type="text/javascript">
var ajaxurl = "' . admin_url('admin-ajax.php') . '";
</script>';
}
add_action('wp_head', 'myplugin_ajaxurl');
at the end the jquery
function sendAjax( ID ) {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
'action' : 'edit_something',
'ID' : ID
},
success:function(data) {
console.log(data)
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
i realy need your guidance
more info :
i also tried json_encode for php and JSON.parse for js but error the response will be Object object .
I guess instead of "echo" you should use wp_send_json_success
https://developer.wordpress.org/reference/functions/wp_send_json_success/
How to call ajax in Wordpress

Wordpress Ajax - returns 0

always returns 0, I have looked through other answers but nothing help.
Can anybody else help me find a solution?
plugin code:
function testOne(){
require_once plugin_dir_path( __FILE__ ) . "do.php";
}
add_shortcode( 'testOne' , 'testOne' );
od.php:
<?php
add_action( 'wp_ajax_myfun', 'myfun' );
add_action( 'wp_ajax_nopriv_myfun', 'myfun' );
function myfun() {
echo 'Test';
wp_die();
}
?>
<script>
$( document ).ready(function() {
$.ajax({
type:"POST",
url: ajaxurl,
data: {
action: "myfun",
},
success:function(data){
alert(data);
}
});
});
</script>
header.php in theme:
<script type='text/javascript'>
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
It seems that there is some issue with ajaxurl variable.
I suggest you to please create a separate javascript file for all code between script tag and than enqueue that script and localize it with ajaxurl.
Below is sample code for localizing :-
wp_register_script( 'my-cstm-script', 'script_url_path', array( 'jquery' ) );
wp_enqueue_script( 'my-cstm-script' );
wp_localize_script( 'my-cstm-script', 'MyCstmVar', array( 'ajaxurl' => admin_url( 'admin-ajax.php', ( is_ssl() ? 'https' : 'http' ) ), ) );
After this please in php file, which includes on that page, just add your function code and check whether this is working or not.
Let me know if you need further assistance.
#user3231235 your code is right only write your whole code out of your function which you would declare in plugin.
Try Below Code:
<script>
jQuery(document).ready(function() {
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
'action':'myfun',
},
success: function (data) {
alert(data);
}
});//end ajax
});
</script>
Put below ajax function in your theme's functions.php
add_action( 'wp_ajax_nopriv_myfun', 'myfun' );
add_action( 'wp_ajax_myfun', 'myfun' );
if( !function_exists('myfun') ):
function myfun(){
echo 'Test';
exit();
}
endif;
Hope this will Help!

Woocommerce Ajax add to cart programmatically

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

Wordpress: AJAX not working

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

Using Ajax in WordPress

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 ...

Resources