Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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) {

    });

}
share|improve this question
1  
This is the wrong way to do ajax within WordPress. The proper way is documented here: 5 Tips for Using Ajax in WP –  cale_b Mar 22 '12 at 23:46

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: http://stackoverflow.com/questions/2257975/using-beforesend-and-complete-with-post

share|improve this answer
    
thank you very much.can u edit my code. –  SANS780730 Mar 23 '12 at 0:07

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.

$.ajax({

    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() {
        alert('Complete');
    }
});

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

share|improve this answer
    
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 ? –  ElectricWizard Feb 26 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 at 15:16
1  
Or, in the ajax call; set data: as data: { 'action': 'my_action', 'whatever': 1234 }, –  josh Feb 26 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? –  ElectricWizard Feb 26 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 at 21:12

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.