Wordpress Ajax - returns 0 - ajax

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!

Related

Wordpress, admin menu, Ajax 400 bad request

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

Why Ajax response in Wordpress doesn't work?

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

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

Wordpress ajax cannot get it to work always returns 0

I've tried to get an ajax function to work with wordpress and always get the default result.
I have in functions.php (beside other functions)
add_action('wp_ajax_count_results_cal', 'count_results');
add_action('wp_ajax_nopriv_count_results_cal', 'count_results');
function count_results(){
echo 'test';
die();
}
function my_theme_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'theme-plugins',get_template_directory_uri() . '/js/plugins.js' , array( 'jquery','jquery-ui-draggable','jquery-ui-dialog' ) );
wp_enqueue_script( 'google-map','http://maps.google.com/maps/api/js?sensor=true', array( 'jquery','jquery-ui-draggable','jquery-ui-dialog' ) );
wp_enqueue_script( 'theme-script', get_template_directory_uri() . '/js/script.js', array( 'jquery','jquery-ui-draggable','jquery-ui-dialog' ) );
wp_enqueue_script( 'ajax', get_template_directory_uri() . '/js/ajax.js', array( 'jquery') );
}
add_action('init', 'my_theme_scripts');
And in my ajax.js file
jQuery(document).ready(function ($) {
$('#manufacturer,#make_date,#fuel_type,#transmission,#price_from,#price_to').on({
change: function(){
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'count_results_cal',
manufacturer : $("#manufacturer").val(),
year : $("#make_date").val(),
fuel : $("#fuel_type").val(),
transmission : $("#transmission").val(),
price_from: $("#price_from").val(),
price_to : $("#price_to").val(),
body_type : $("#body_type").val(),
vat : $("#vat").val()
},
success: function(data, textStatus, XMLHttpRequest){
$('#offers_found span').html(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
}});
});
I've tried everything I could think of with no results. Does anyone have some ideas?
Fixed this by changing the url to full address (http://.../)

Resources