Elian Elian - 1 year ago 59
jQuery Question

jQuery post in WordPress

I have the following code in a JS file inside a JS folder in my WP theme:

jQuery('#tarieven-submit').on('click', function(event) {
event.preventDefault();

var dest = jQuery('#destination').val();
var type = jQuery('input[name=taxiType]:checked', '#distance_form').val()

if (jQuery.trim(dest) != '' && type != '') {
jQuery.post('../HTA/wp-content/themes/HTA/ajax/tarieven.php', { destination: dest, type: type}, function(data) {
jQuery('#result').text(data);
});
}
});


I cannot get this to work even though the file that is being posted to is located in the correct folder. I'm guessing it has something to with a wrong AJAX call. But I cannot seem to find how to do this properly. For example, I've seen I need to do an AJAX call in admin-ajax.php, however, how do I add my custom code there?

Answer Source

You should try to do the AJAX call with the WordPress standard, to create an AJAX call, you just add the PHP function that is going to handle your call in your functions.php file, e.g.,

function ajax_handler() {
    // Do your stuff here;

    wp_die(); // Always put this at the end, it is required by WordPress to end your call.
}

And then you register your AJAX action with this.

add_action( 'wp_ajax_ajax_handler', 'ajax_handler' );
add_action( 'wp_ajax_nopriv_ajax_handler', 'ajax_handler' ); // This is for unlogged users.

So, your jQuery function should be like this:

var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; // This is the WordPress AJAX handler file.

jQuery('#tarieven-submit').on('click', function(event) {
event.preventDefault();
var dest = jQuery('#destination').val();
var type = jQuery('input[name=taxiType]:checked', '#distance_form').val()
if (jQuery.trim(dest) != '' && type != '') {
    jQuery.post(ajaxurl, { destination: dest, type: type, action: "ajax_handler"}, function(data) {
        jQuery('#result').text(data);
    });
}

Notice the action parameter we are sending to our WordPress AJAX handler file (admin-ajax.php). It is required to tell WordPress which function/action should execute on our call.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download