Wordpress AJAX doesn't work - response 0 - javascript

I want add AJAX support to my plugin and I have huge problem with this simple thing. WordPress isn't permitting me to use normal AJAX and I need to use WordPress version.
At all times, the WordPress function (that should generate output) returns 0. And I think that the reason is that WP doesn't trigger 'function'. I try to force the function to run many times, but I don't have any idea what I can improve.
<?php
public function widget( $args, $instance ) {
$options = get_option('Free_Quotation_options');
?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
jQuery.ajax({
url: ajaxurl,
type: 'POST',
action: 'fqtag',
data: {
'whatever': 'text'
},
success: function (output) {
$('#secondary').append(output);
}
});
});
</script>
<?php
add_action( 'wp_ajax_fqtag', 'fqtag' );
add_action( 'wp_ajax_nopriv_fqtag', 'fqtag' );
function fqtag() {
global $wpdb;
echo 'echo';
die();
}
}
I try to add alert('echo'); to the test function, but it doesn't have any effect. I think that AJAX doesn't run the proper function: fq_tag_support_callback() .
On the beginning I had a problem with ajaxurl variable. It was not defined. It's not a normal situation. I attempt to resolve this problem by using:
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
Do you have any idea, how can I try to solve this problem?
---EDIT--- After discussion with David I have file like this (all time doesn't work)
<?php
/*
Plugin Name: TEST PLUGIN
Description: TEST
Author: Krzysztof Kubiak
Version: 1.0
*/
function Test_01_settings_init(){
register_setting( 'Test_01_settings_filed', 'Test_01_options', 'Test_01_validate' );
}
add_action('admin_init', 'Test_01_settings_init' );
function T01_init_method() {
wp_enqueue_script('jquery');
}
add_action('init', 'T01_init_method');
function Test_01_menu_page(){
add_menu_page( 'Test_01', 'Test_01', 'manage_options', 'T01_menu_page', 'T01_add_page' );
echo my_test();
}
add_action('admin_menu', 'Test_01_menu_page');
function my_test(){
echo 'Function test';
}
function T01_add_page() {
echo 'TEST_01_plugin';
}
function Test_01_validate($input) {
}
//AJAX FROM HIRE
function test_callback() {
$whatever = 8;
echo $whatever;
die();
}
add_action( 'wp_ajax_nopriv_fqtag', 'test_callback', 1 );
add_action( 'wp_ajax_fqtag', 'test_callback', 1 );
function print_js() { ?>
<script type="text/javascript">
jQuery.ajax({
url: 'wp-admin/admin-ajax.php',
type: 'POST',
action: 'fqtag',
data: {
'whatever': 'text'
},
success: function (output) {
alert(output);
}
});
</script>
<?php
}
add_action('wp_print_footer_scripts', 'print_js', 1000);
?>

remove
<script>alert('echo');</script>
your response should be echo if you check your console. I suspect all the above code is in your plugin functions file. Basically the php function should be placed in the functions file.
The jquery should be placed in the template from which you want to receive the response.
Place this in your functions file...remove the jquery from the class...
add_action('wp_print_footer_scripts', 'print_js', 1000);
function print_js() { ?>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery.ajax({
url: 'wp-admin/admin-ajax.php',
type: 'POST',
data: {
'action': 'test_callback',
'whatever': 'text'
},
success: function (output) {
alert(output);
}
});
});
</script>
<?php
}
Move this outside your class...
function test_callback() {
$whatever = 8;
echo $whatever;
die();
}
add_action( 'wp_ajax_nopriv_testaction', 'test_callback' );
add_action( 'wp_ajax_testaction', 'test_callback' );

Just make sure that you have put the function 'fq_tag_support_callback()' in your plugin's main file.

I see few problems here. Action should inside the data object, not as a jQuery Ajax parameter. Also in the callback function data is stored in $_POST variable.
function test_callback() {
$whatever = $_POST['whatever'];
echo $whatever;
die();
}
add_action('wp_ajax_nopriv_fqtag', 'test_callback');
add_action('wp_ajax_fqtag', 'test_callback');
function print_js() {
?>
<script type="text/javascript">
jQuery.ajax({
url: <?php echo admin_url('admin-ajax.php'); ?>,
type: 'POST',
data: {
action: 'fqtag',
whatever: 'text'
},
success: function (output) {
alert(output);
}
});
</script>
<?php
}
add_action('wp_print_footer_scripts', 'print_js', 1000);
?>

Related

Add a custom ajax button to WooCommerce admin orders list

I am creating a plugin to track courier order via button in shop order page. This is my code
// add Tracking button in shop order admin column
add_action( 'manage_shop_order_posts_custom_column', 'dvs_add_tracking_admin_list_column_content' );
function dvs_add_tracking_admin_list_column_content( $column ) {
<button type="button" class="woocommerce-Button button mark-as-read" >Track Order</button>
<?php
}
?>
<script type="text/javascript">
jQuery(function($){ // use jQuery code inside this to avoid "$ is not defined" error
$('.mark-as-read').click(function(){
console.log('The function is hooked up');
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'mark_message_as_read'
},
success: function (output) {
console.log(output);
}
});
});
});
</script>
<?php
add_action('wp_ajax_mark_message_as_read', 'mark_message_as_read');
add_action('wp_ajax_nopriv_mark_message_as_read', 'mark_message_as_read');
function mark_message_as_read() {?>
<script>
alert("Hello! I am an alert box!!");
</script>
<?php
wp_send_json_success([/* some data here */]);
wp_send_json_error([/* some data here */]);
}
This is screenshot
But when I click the Track Order button nothing happens, it should display the alert-box as defined in a function, please help me what I did wrong?
There are multiple mistakes in your codeā€¦ Here is the correct way to make it work:
add_action( 'manage_shop_order_posts_custom_column', 'add_tracking_admin_list_column_content' );
function add_tracking_admin_list_column_content( $column ) {
if ( $column === 'wc_actions') {
?><button type="button" class="woocommerce-Button button mark-as-read" ><?php _e('Track'); ?></button><?php
}
}
add_action( 'admin_footer', 'admin_footer_tracking_js' );
function admin_footer_tracking_js() {
global $pagenow;
if ( $pagenow === 'edit.php' && isset($_GET['post_type']) && 'shop_order' === $_GET['post_type'] ) :
?>
<script type="text/javascript">
jQuery( function($){
$('.mark-as-read').on('click', function(){
$.ajax({
type: 'POST',
url: '<?php echo admin_url('/admin-ajax.php'); ?>',
data: {
'action': 'mark_message_as_read',
'track_order': 'yes'
},
success: function (response) {
console.log(response);
if ( response == 'yes' ) {
alert("Hello! I am an alert box!!"); // => alert box
}
}
});
});
});
</script>
<?php
endif;
}
add_action('wp_ajax_mark_message_as_read', 'get_mark_message_as_read');
function get_mark_message_as_read() {
if ( isset($_POST['track_order']) ) {
//wp_send_json_success([/* some data here */]);
//wp_send_json_error([/* some data here */]);
echo $_POST['track_order']; // Send data back to JS
die();
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.

POST undefined index $v3

I work with ajax in wordpress, I want to show what the user enters,
the success of ajax is sent to the server, but the POST array issues
an indefinite index in my index.php, why doesn't it work?
inc/send.php
<?php
add_action( 'wp_ajax_applican', 'applican');
add_action( 'wp_ajax_nopriv_applican', 'applican');
function applican(){
$v3 = $_POST['v3'];
};
?>
/js/custom.js
let arr = [];
btnNext.on('click', () => {
if(roomsRadio.is(':checked')) {
calc.slick('slickNext');
arr['version1'] = $('.rooms input[type="radio"]:checked').val();
console.log(arr['version1'])
}
if(versionRadio.is(':checked')) {
calc.slick('slickNext');
arr['version2'] = strip_html_tags($('.version input[type="radio"]:checked').val());
console.log(arr['version2'])
}
if(typeRadio.is(':checked')) {
calc.slick('slickNext');
arr['version3'] = strip_html_tags($('.type input[type="radio"]:checked').val());
console.log(arr['version3'])
$.ajax({
type: "POST",
dataType:'json',
url: "/wp-admin/admin-ajax.php",
data: {"action": "applican", "v3": arr['version3'], "v2": arr['version2'], "v1": arr['version1']},
success: function(msg) {
alert( "Data Saved: " + msg );
},
error: function () {
console.log({"v3": arr['version3']});
}
})
}
index.php
<?php applican(); echo $v3; ?>
Like Magnus said, variables in PHP have different scopes Variable scope, You can't reach it out of the scope. In your code, $v3 can only be reached inside the function applican(), but not index.php. You can extend the variable's scope with keyword global:
<?php # inc/send.php
function applican(){
global $v3;
$v3 = $_POST['v3'];
};
Or other solution like:
<?php # inc/send.php
function applican(){
return $_POST['v3'];
};
<?php # index.php
$v3 = applican(); echo $v3;

I cant get $_POST from js to php in wordpress with ajax

My js file is here.
function sayHelloWorld() {
window.alert('hey');
$.ajax({
url: 'admin-ajax.php',//I wrote absolute path here.
type:'POST',
data: {
'action': "mon_action",
'newFormRecherche': 'newFormRecherche'
},
timeout:10000,
}).done(function(data) {
window.alert(data);
}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
window.alert("error");
});
and functions.php is here.
add_action( 'wp_ajax_mon_action', 'mon_action' );
add_action( 'wp_ajax_nopriv_mon_action', 'mon_action' );
function mon_action() {
if (isset($_POST["newFormRecherche"])) {
$field1='hey';
exit();
}else{
$field1='heye';
exit();
}
echo 'echo';
die();
}
this process succeeds and I get window.alert(data), but data is empty. could you tell me why this does not include 'echo'?
(this script is something that I am just trying.)
You need to echo some data on php function like this
if (isset($_POST["newFormRecherche"])) {
$field1='hey';
echo 'if';
exit();
}else{
$field1='heye';
echo 'else';
exit();
}
echo 'echo';
die();
Nothing is echoing and the page comes out empty becuase you're exiting before echo 'echo';, your code should be
add_action( 'wp_ajax_mon_action', 'mon_action' );
add_action( 'wp_ajax_nopriv_mon_action', 'mon_action' );
function mon_action() {
if (isset($_POST["newFormRecherche"])) {
$field1='hey';
}else{
$field1='heye';
}
echo 'echo';
die();
}

javascript variable pass into php

I get category id by js and want to use it to get category description.
when i am passing this id using ajax into php variable its print correct output but when i try to put this id in get_description code ajax give 500 error and not return output why this happen please help me.
Below is my code.
<script type="text/javascript">
$(".-filter").click(function() {
var js_var = this.id;
$.ajax ({
type: "POST",
url: "<?php echo plugin_dir_url( __FILE__ ); ?>category.php",
data: { val : js_var },
success: function( result ) {
$("#update").html(result);
}
});
});
</script>
<div id="update">
<?php
$cat_id = $_POST['val'];
echo $cat_id;
//echo term_description($cat_id,'category');
?>`enter code here
</div>
Thanks,

Using AJAX to check variables in database, if true, header to a certain page, PHP, JAVASCRIPT

I'm trying to use AJAX to check variables in the database, and if it's true, then it should make it header to a certain page, except in this testing phrase, I'm not checking any variables. I'm just testing if it'll header off to that certain page if I call the function. I started at test1.php, but it should've called the ajax function, and immediately header off to test3.php, but it didn't. I'm not sure what I did wrong. Please take a look:
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function nopassAjax(url,timeout) {
$.ajax({
type: "POST",
url: url,
error: function(xhr,status,error){alert(error);},
success:function(data) {
setTimeout(function() { timeoutAjax(url,timeout); }, timeout);
}
});
}
</script>
test1.php
<?php
include('ajax.php');
echo "<script>";
echo "nopassAjax('test2.php',1000);";
echo "</script>";
?>
test2.php
<?php
//checks some stuff in the database
//if true, header off to test3.php
header("Location: test3.php");
?>
test3.php
<?php
echo "Hello";
?>
From your question I'm assuming you want to redirect to the page that's returned from your AJAX call. You can't do this from PHP alone.
Javascript:
$.ajax({
method: "POST",
url: someUrl
}).fail( function( error ) {
alert( error );
}).done( function( response ) {
window.location = response;
});
PHP:
<?php
echo "test3.php";
?>

Categories