How do I set the beforesend option in WordPress AJAX? I want to show loading option.

This is my code:

function showmyvideos() { 
    var datas="data";
    var data = {
        action: 'my_vids',
        link: datas  
    ajaxurl= "http://localhost/wordpress/wp-admin/admin-ajax.php";
    jQuery.post(ajaxurl, data,function(response) {



2 Answers 2


You have two options:

  1. Use jQuery.ajax() instead of jQuery.post()
  2. Use jQuery.ajaxSetup() to change the beforeSend behavior globally.

Reference: https://stackoverflow.com/questions/2257975/using-beforesend-and-complete-with-post


For posterity.

You can still use $.ajax() without having to use $.ajaxSeteup(). All you need to specify is the type and make sure it is set to POST.


    url: localized_script.ajax_url,  /* Admin ajax url from localized script */
    type: 'POST',  /* Important */
    data: data_object,  /* Data object including 'action' and all post variables */
    beforeSend: function() {
        alert('Before Send');
    success : function(response) {
        alert(response);  /* Response from ajax function */
    complete: function() {

As you can see, you can set different functions/events for beforeSend, success and complete.

  • Lets say I am using $.post, I have the field - action: [name of the "add_action('wp_ajax_.." ect]. Where do I write it when using $.ajax ?
    – Kar19
    Feb 26, 2015 at 13:38
  • 1
    You'll set it in the "data_object". So just before the $.ajax call; you'll define data_object. Like, data_object = { 'action': 'my_action', 'whatever': 1234 };.
    – josh
    Feb 26, 2015 at 15:16
  • 1
    Or, in the ajax call; set data: as data: { 'action': 'my_action', 'whatever': 1234 },
    – josh
    Feb 26, 2015 at 15:17
  • OK, works. For some reason I get an error POST http://54.149.xx.xx/wp_admin/admin_ajax.php 404 (Not Found) in my console. Any clue why?
    – Kar19
    Feb 26, 2015 at 15:20
  • You have to pass the admin_ajax.php url to the script; using localization. You can try using url: ajaxurl (instead of url: localized_script.ajax_url) if it's available as a global js variable on the page where you are including your script. What value are you using for url:?
    – josh
    Feb 26, 2015 at 21:12

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.