You need to follow these steps to properly call ajax function in WordPress,
-
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
-
Then Enqueue the script
wp_enqueue_script('*handle_name*');
-
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); });
-
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);
});