0

This is the first time i am trying to fire ajax in WordPress. I know i am making mistake which is not letting my ajax run so please help me to figure it out.

Here is my js code -

enter image description here

Here is my ajax code -

enter image description here

1 Answer 1

3

You need to follow these steps to properly call ajax function in WordPress,

  1. Register and localize your script, eg.

    wp_register_script(
          '*handle_name*'
        , *js_file_path*
        , array(
            *dependency_name*
        )
        , true
        , true
    );
    

    It will load your script at page footer. Refer to the following link: https://developer.wordpress.org/reference/functions/wp_register_script/

    wp_localize_script(
          '*handle_name*'
        , '*a_unique_name_to_call_this_object*'
        , array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'if_require_any_more_field' => 'necessary_value',
        )
    );
    

    It will create a js object with two properties, ajaxurl and if_require_any_more_field. Refer the following link: https://codex.wordpress.org/Function_Reference/wp_localize_script

  2. Then Enqueue the script wp_enqueue_script('*handle_name*');

  3. In your javascript/jQuery code

        var formDate = jQuery('#tpform1').serialize();                      
        var data = {
            action : 'trade_partners',
            form : formData
        }
    
        $.post(unique_object_name.ajaxurl, data, function(response) {
            alert(response);           
        });
    
  4. Now time to write your php ajax calling function in functions.php file (for best practice)

    add_action('wp_ajax_trade_partners', 'custom_action');
    add_action('wp_ajax_nopriv_trade_partners', 'custom_action');     
    
    function custom_action() {
        global $wpdb;
        echo "<pre>";
        print_r($wpdb);
    }
    

If you use you write your js code within that php file, then you directly jumped into 3rd step, and within the script tag you need to create a variable which have the ajaxurl, ex: var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>"; and modify the line where actual ajax function is calling,

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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