wordpress ajaxurl code example

Example 1: wordpress ajax url

<?php
add_action( 'wp_footer', 'my_ajax_without_file' );

function my_ajax_without_file() { ?>

    <script type="text/javascript" >
    jQuery(document).ready(function($) {

        ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl

        var data = {
            'action': 'frontend_action_without_file', // your action name 
            'variable_name': "Some value" // some additional data to send
        };

        jQuery.ajax({
            url: ajaxurl, // this will point to admin-ajax.php
            type: 'POST',
            data: data,
            success: function (response) {
                console.log(response);                
            }
        });
    });
    </script> 
    <?php
}

add_action("wp_ajax_frontend_action_without_file" , "frontend_action_without_file");
add_action("wp_ajax_nopriv_frontend_action_without_file" , "frontend_action_without_file");

function frontend_action_without_file(){
    echo json_encode($_POST);
    wp_die();
}

?>

Example 2: ajax in wordpress

jQuery(document).ready( function() {

   jQuery(".user_vote").click( function(e) {
      e.preventDefault(); 
      post_id = jQuery(this).attr("data-post_id")
      nonce = jQuery(this).attr("data-nonce")

      jQuery.ajax({
         type : "post",
         dataType : "json",
         url : myAjax.ajaxurl,
         data : {action: "my_user_vote", post_id : post_id, nonce: nonce},
         success: function(response) {
            if(response.type == "success") {
               jQuery("#vote_counter").html(response.vote_count)
            }
            else {
               alert("Your vote could not be added")
            }
         }
      })   

   })

})

Tags:

Php Example