Skip to content Skip to sidebar Skip to footer

Jquery Ajax Call In Wordpress Plugin Page Not Working

In wordpress I created a plugin which has the following files Statistics visitor

Solution 1:

WordPress environment

First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.

Please take a look to:

  1. wp_register_script(); function
  2. wp_enqueue_scripts hook
  3. wp_enqueue_script(); function
  4. wp_localize_script(); function

add these functions to plugin file.

add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
functionso_enqueue_scripts(){
  wp_register_script( 'ajaxHandle', get_template_directory_uri() . 'PATH TO YOUR SCRIPT FILE', array(), false, true );
  wp_enqueue_script( 'ajaxHandle' );
  wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

File: jquery.ajax.js

This file makes the ajax call.

jQuery(document).ready( function($){
  //Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
  $.ajax({
    url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script functiontype: 'POST',
    action: 'myaction'// this is the function in your functions.php that will be triggereddata:{ 
      name: 'John',
      age: '38'
    },
    success: function( data ){
      //Do something with the result from serverconsole.log( data );
    }
  });
});

Finally on your plugin file there should be the function triggered by your ajax call. Remember the suffixes:

  1. wp_ajax ( allow the function only for registered users or admin panel operations )
  2. wp_ajax_nopriv ( allow the function for no privilege users )

These suffixes plus the action compose the name of your action:

wp_ajax_myaction or wp_ajax_nopriv_myaction

add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction''so_wp_ajax_function' );
functionso_wp_ajax_function(){
  //DO whatever you want with data posted//To send back a response you have to echo the result!echo$_POST['name'];
  echo$_POST['age'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}

Hope it helps!

Let me know if something is not clear.

Post a Comment for "Jquery Ajax Call In Wordpress Plugin Page Not Working"