0

When an action made by an user, I want to run a php function from the plugin. I checked this link but I'm still pretty confused about it. https://codex.wordpress.org/AJAX_in_Plugins

Here is the related JS code I wrote.

$(function() {
      var data = {
        'nothing': 'nothing'
        'whatever': ajax_object.we_walue
      }
      document.getElementById("getPhp").onclick = function() {myFunction()};
      function myFunction() {
      jQuery.post(ajax_object.ajax_url, data, function(response) {
      alert('It works');
});
});

Actually, I don't really need to pass anything, I made the variable up for just filling the jquery.post function's "data" parameter. Then in the php file:

function phpback_js(){
wp_enqueue_script( 'getPhp', plugins_url( '/mycode.js', __FILE__ ),array('jquery'));
}
 add_action('the_post', 'phpback_js');

add_action('wp_ajax_my_action', 'back_php');
function back_php()
{
    //I want this function to be called.   
}

But it's not working, the alert box never pops up. Where is the issue? Alternatively, is there a way for calling a php function without sending any data?

0

In your JS code, you need an action so it knows what function to execute.

var data = {
    'action': 'my_action',
    'nothing': 'nothing'
    'whatever': ajax_object.we_walue
  }

You should see how the action corresponds to the hook you used in add_action. But I would also add a second action:

add_action('wp_ajax_my_action', 'back_php');
add_action('wp_ajax_no_priv_my_action', 'back_php');

This will ensure that all users will be able to trigger the AJAX, not just those that are logged in.

If you don't need the PHP function to use any data, you could simply pass an empty string. But to ensure it works, I would have the PHP function return something:

function back_php()
{
    echo "text from PHP";
    wp_die();
}

...and then catch it in the AJAX success function:

jQuery.post(ajaxurl, data, function(response) {
  alert(response);
}

Hope this helps.

  • Thanks, but still There is no alert box coming up. May there be other problems? – codemonkey Apr 10 '17 at 22:51
  • You seem to be missing a } in the last line of JS function. Try }});. – scott Apr 10 '17 at 23:18
  • I solved the issue, the problem was adding no ajax_url to javascript variable. Thank you by the way. – codemonkey Apr 11 '17 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.