Custom ajax requests in wordpress

My question pertains to where I should create an ajax function that I’d like to call from my page view.

I am using a jQuery validator on a custom form that should check the inputted zipcode against my database of valid zipcodes.

Read More

I just need to know where this function should exist.

Normally when using a non wordpress site I’d create a PHP file with my ajax functions and call them by referencing the URL to this page and passing some parameters.

How can I achieve this with wordpress? Where can i explicitly call a php file and pass it arguments?

Note: I’d like to call the ajax function like so:

$.post('http://mysite.com/ajax-functions.php?fxn=zipcodes',
    {zipCode:00000},
    function(response){
      // do stuff
    });

Thanks

Related posts

Leave a Reply

4 comments

  1. There are WordPress ajax hooks that helps to create function using ajax. WordPress allows admin ajax to run any function. Following code is help to use custom ajax in wordpress.

    <?php
    // javascript ajax call with click event
    add_action('wp_head', 'ajx_action_javascript_wp');
    function ajx_action_javascript_wp() {
    ?>
    
    <script type="text/javascript" >
    jQuery(document).ready(function($) {
        $('.myajax').click(function(){
          //alert(1);
          var mydata = $(this).data();
          //var termID= $('#locinfo').val();
          $('#wpajaxdisplay').html('<div style="text-align:center;"><img src="<?php echo get_template_directory_uri(); ?>/images/bx_loader.gif" /></div>');
          //console.log(mydata);
            var data = {
                action: 'custom_action',
                //whatever: 1234,
                id: mydata.id
            };
    
            $.post('<?php echo esc_url( home_url() ); ?>/wp-admin/admin-ajax.php', data, function(response) {
               // alert('Got this from the server: ' + response);
               $('#wpajaxdisplay').html(response);      
            });
        });
    });
    
    </script>
    <?php
    }
    
    add_action('wp_ajax_custom_action', 'custom_action_callback_wp');
    add_action( 'wp_ajax_nopriv_custom_action', 'custom_action_callback_wp' );
    
    function custom_action_callback_wp() {
         global $wpdb; // this is how you get access to the database
         $getid = 'ID=> '. $_POST['id'];
         echo $getid;
         // do something
         exit(); // this is required to return a proper result
    } ?>
    

    HTML Part

    <a href="#ajaxthing" class="myajax" data-id="600">Click On this</a>
    <div id="wpajaxdisplay">Ajax Result will display here</div>
    
  2. I think one easy method is to create a new template and assign this template to a new page.
    then you can write your code in this template file and use the url of the page for ajax request

  3. Try this, It easiest way, I have worked on this many times:

    step 1: Add these code snippets in functions.php

    add_action( 'wp_ajax_nopriv_add_to_folder', 'add_to_folder' );
    add_action( 'wp_ajax_add_to_folder', 'add_to_folder' );
    function add_to_folder() {      
        global $wpdb;
        $lbm_add_request_table = $wpdb->prefix . 'lbm_add_request';
        $user_id = get_current_user_id();
        $lbmuid = $_COOKIE['lbmuid'];
        $lib_data_id = $_POST['lib_data_id'];
        $return = array();
        $return['lib_data_id'] = $lib_data_id;
        $getAddedData = $wpdb->get_row("SELECT * FROM $lbm_add_request_table WHERE lbmuid = '$lbmuid' AND  lib_data_id = $lib_data_id ", ARRAY_N);
    
        if ($getAddedData != null) {
            $wpdb->delete( $lbm_add_request_table, array( 'lbmuid'  => $lbmuid,'lib_data_id' => $lib_data_id) );
            $return['status'] = 'deleted';
        }else{
            $wpdb->insert( 
            $lbm_add_request_table, 
            array( 
                'user_id' => $user_id, 
                'lbmuid'  => $lbmuid,
                'lib_data_id' => $lib_data_id,
                'add_date'  => current_time('mysql')
            ));
            $return['status'] = 'added';
        }
        echo json_encode($return);
        exit();
    
    }
    

    Step 2:
    Now call the ajax in your template page

    <script>
    // Add to request folder ajax function call Start
    jQuery( document ).on( 'click', '.add_to_folder', function() {
        var lib_data_id = $(this).prev(':input').val(); 
        jQuery.ajax({
        url : '<?php echo admin_url( 'admin-ajax.php' );?>',
        type : 'post',
        data : {lib_data_id: lib_data_id,action:'add_to_folder'},
        success : function( response ) {        
            response = $.parseJSON(response);       
            if(response.status=='added'){       
                $("#addBtn"+response.lib_data_id).val('Remove from request folder');    
                $("#addBtn"+response.lib_data_id).addClass('remove');
            }else{
                $("#addBtn"+response.lib_data_id).val('Add to request folder'); 
                $("#addBtn"+response.lib_data_id).removeClass('remove');
            }
        }
        });
    });
    // Add to request folder ajax function call End
    </script>