WordPress: Passing data to a page using Ajax

I am trying to pass data from an ajax call to a specific page of WordPress.
Below is the code I am using:

jQuery.ajax({type: "POST",
            url: 'single-member-page.php',
            data:{ size: 'item' }, 
            success: function(){
              //alert(data);
              jQuery('#display-member-size').text(data);
            }
        });

The script does not work for WP. I also inspected the page using the console and I get an error:

Read More

single-member-page.php” NOT FOUND

I am new to WP and I do not know how to pass data from an ajax call to a specific page.

Related posts

Leave a Reply

3 comments

  1. @Daniel

    You asked a very good question, before proceeding to solution we need to understand thumb rules of wordpress ajax.

    Thumb Rules:

    1. According to wordpress standards all the ajax request should come to “ajaxurl” in javascript. It actually contains the “wp-admin/admin-ajax.php” file path.

      Example:

      $.ajax({
          url: ajaxurl,
          data: {'action':'generateCptApiKey'},
          success:function(data) {
              console.log(data);
          },
          error: function(errorThrown){
              console.log(errorThrown);
          }
      });
      

    If you are doing some sutff in wp-admin dashboard section or related to wp-admin section like creating an option page in wp-admin dashboard area, than “ajaxurl” global variable will be always available there in javascript.

    If case of this ajax request is initialized from front end page/post than you have to specify admin-ajax.php files path using following method and better if you localize this for front-end javascript,So it will be available in javascript variable like it is available in wp-admin dashboard section.

    In order to achieve this we need to add few more lines of code.

    Method:

    Updated Example code front-end ajax call :

    // Register the script
    wp_register_script( 'ajaxsettings', 'path/to/ajaxsettings.js' );
    
    // Localize the script with new data
    $ajaxsettings = array(
        'ajaxurl' => admin_url('admin-ajax.php')
    );
    wp_localize_script( 'ajaxsettings', 'ajaxsettings', $ajaxsettings );
    
    // Enqueued script with localized data.
    wp_enqueue_script( 'ajaxsettings' );
    
    $.ajax({
            url: ajaxsettings.ajaxurl,
            data: {'action':'generateCptApiKey'},
            success:function(data) {
                console.log(data);
            },
            error: function(errorThrown){
                console.log(errorThrown);
            }
        });
    

    After this we need to write method to handle this ajax request and send output back to the ajax call.

    For detecting ajax request call in wordpress they have two standard hooks, hooks are just events like when i send a ajax request, wordpress ajax related hook will trigger and i can call any function on that trigger.

    So basically for handling ajax request below are two hooks:

    1. wp_ajax_(action) : It handles request from authenticated / logged in users. (Used for back-end wp-admin dashboard related tasks )
    2. wp_ajax_nopriv_(action) : It handles front-end unauthenticated requests.
      (Used for front-end page/post ajax call related tasks )

    Here (action) is the name of the method that you have to code in your current theme function.php file, and this method will handle this ajax request.

    Examples:

    Object oriented style:

    add_action( 'wp_ajax_cleanResponseFiles', array($this, 'cleanResponseFiles'));
    add_action( 'wp_ajax_nopriv_cleanResponseFiles', array($this, 'cleanResponseFiles'));
    

    Note: Here “cleanResponseFiles” is Method of class that will handle ajax request. and $this is pointing current class object.

    Procedural style:

    add_action( 'wp_ajax_cleanResponseFiles',  'cleanResponseFiles');
    add_action( 'wp_ajax_nopriv_cleanResponseFiles','cleanResponseFiles');
    

    Note: Here “cleanResponseFiles” is function added in current theme function.php file and it will handle ajax request.

    In this we are considering that ajax request can be made either from wp-admin dashboard or from front-end page/post.

    Example ajax request handler method:

    function cleanResponseFiles(){
        echo "<pre>";
        print_r($_POST);
        echo "</pre>";
    
        //Always use exit() in ajax request handler function end
        exit();
    }
    

    Thumb Rule :

    1. Always use exit() method in ajax request handler method, it’s essential.
    2. The best practice of sending ajax request is use WordPress_nonce.

    It’s just for avoding CRSF (Cross site request forgery ) by adding Honeypot , A hidden input field with generated random key and at in request handler method it should be validated.

    These are the methods that we can use for creating Wordepress nonce and verifying WordPress nonce and ajax request handler or simple http request handler.

    WordPress Nonce Methods:

    1. wp_create_nonce : Used for creating random key for sending in forms as a hidden field.
    2. wp_verify_nonce : Used for verifying random key in request handler method.

    I will attach a working example of wordpress ajax call ASAP in this comment.

  2. Just a brief: All ajax post should be sent to admin-ajax.php Each request needs to supply at least one piece of data called action. Based on this action, the code in admin-ajax.php creates two hooks.
    if the value of action is cusom_action, wp_ajax_custom_action and wp_ajax_nopriv_custom_ction are auto created. Check WordPress coddex. https://codex.wordpress.org/AJAX_in_Plugins

  3. Refer this https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    Basically you create an action like wp_ajax_myaction, this you can define in your functions.php or somewhere where you seem fit. And then call it as shown in the example(Usage section) on the page.

    EDIT:
    Adding some code to help you understand

    In your functions.php

    add_action( 'wp_ajax_my_ajax', 'my_ajax' );
    add_action('wp_ajax_nopriv_my_ajax', 'my_ajax');
    
    function my_ajax() {
        die( "Hello World" );
    }
    

    In your JS:

    $.ajax({
            url: "http://yoursite.com/wp-admin/admin-ajax.php",
            data : {action : 'my_ajax'},
            success: function( data ) {
                alert( 'The code says ' + data);
            }
        })
    

    Few things about the code:

    1. This is just a quick and dirty code, mostly ripped off from the example just to show you how it will work.

    2. The no_priv action is used for allowing unauthorized access(i.e to non-admin users as well)

    3. The url is usually not hardcoded in the way shown in the example, people usually pass it to the script using admin_url( 'admin-ajax.php' )

    4. The action, sent in the data determines which function should be called. (my_ajax in our case)

    Let know if you still have issues.