How to use ajax in Wordpress?

2019-08-23 21:11发布

问题:

I want to use ajax in wordpress. How can I do it? I have attached my code here. But this is not working for me. Here it is my wordpress action and hook.

function ajax_enqueuescripts() {
    wp_enqueue_script('ajaxloadpost', get_template_directory_uri().'/js/my-ajax.js', array('jquery'));
    wp_localize_script( 'ajaxloadpost', 'ajax_postajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action('wp_enqueue_scripts', ajax_enqueuescripts);

add_action('wp_ajax_nopriv_ajax_ajaxhandler', 'my_action_callback' );
add_action('wp_ajax_ajax_ajaxhandler', 'my_action_callback' );

function my_action_callback(){  
    //echo "Df";print_r($_POST);die;
}

and here it is my js code

jQuery(document).ready(function(){
 jQuery('#event-form').submit( function () {

    var email = jQuery('#event_name').val();
jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function() {
            alert(email);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

    return false;
  });
});

回答1:

The value that you alert in your success ajax function must come from your php function so you would have something like this:

PHP

function my_action_callback(){  
    echo $_POST['email']; die();
}

Javascript

jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function(data) {
            alert(data);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

in your case data in javascript will be equal to anything that you echo out in your php function.

You can send json objects to javascript by encoding arrays in which case you would have

PHP

function my_action_callback(){  


    echo json_encode('email' => $_POST['email']));

die();
}

Javascript

jQuery.ajax({
        type: 'POST',
        url: ajax_postajax.ajaxurl,
        data: {
            action: 'ajax_ajaxhandler',
        email : email   
        },
        success: function(data) {
            alert(data.email);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Fd");
        }
    });

I only gave you example of the places in your code that needed to be replaced, the rest seems alright.