John Davidson

Passing variables from jQuery/AJAX to Wordpress php function does not work

0 comments
Message:


Edit: Resolved (see my own answer)


I have a button with the class "magic" on my wordpress page.
If I click it, I want it to call a PHP function in my plugin_xy.php to store a certain value (blub: "test123") into a text file.
Creating the text file upon button click and writing anything into it works so the chain seem to be fine but I can't pass the value of "blub" to PHP and use it there.


Here is my jquery.main.js:


jQuery(document).on('click', '.magic', function(e){        
jQuery.ajax({
method: 'post',
url: ipAjaxVar.ajaxurl,
data: {
action: 'my_function',
blub: "test123"
},
success:function(data){
console.log(data);
}
}).done(function(msg) {
// Do something when done
console.log("jQuery: Done!");
});

e.preventDefault();
});

And here is my plugin_xy.php:


wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);

wp_localize_script('main', 'ipAjaxVar', array(
'ajaxurl' => admin_url('admin-ajax.php')
));

add_action('wp_ajax_my_function', 'my_function');

function my_function()
{
$log = "The value of blub is: ";

if (isset($_REQUEST['blub'])) {
$log .= $_REQUEST['blub'];
}

$filename = plugin_dir_path(__FILE__) . '/ZZZ_result.txt';
$fh = fopen($filename, "a");
fwrite($fh, $log);
fclose($fh);
}

As you can see I'm trying to add the content of "blub" to $log so it appears in the textfile but it does not.
Any ideas?



My Answer:
"submit-button" that, when clicked, should pass a variable to a Wordpress php function using jQuery/AJAX. However, the variable is not being passed correctly to the php function.

Here is my jQuery/AJAX code:

javascript
jQuery(document).ready(function($) {
$('.submit-button').click(function() {
var myVariable = 'Hello';

$.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'my_php_function',
myVariable: myVariable
},
success: function(response) {
console.log(response);
}
});
});
});


And here is my Wordpress php function:

php
add_action('wp_ajax_my_php_function', 'my_php_function');

function my_php_function() {
$myVariable = $_POST['myVariable'];

echo $myVariable;

wp_die();
}


When I click the button, the php function is called, but the variable `$myVariable` is empty. I have tried various ways of passing the variable in the data object of the AJAX call, but none of them seem to work.

Can anyone help me figure out what I am doing wrong?

Rate this post

4 of 5 based on 1110 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us