James Radford
James Radford

Reputation: 1855

using jquery ajax beforeSent not working for me when posting a form

Any ideas why the beforeSend does not work for me using the code below on a click event? I guess it's the window.location but how can I handle this I don't know!? Many thanks,

"use strict";

(function ($, ns, w) {

    $(document).ready(function () {
        $.post(ns.validateField, { name: userName})
            .done(function (data) {
              window.location = ns.newUrl;  // Fires browser reload
            })
            .beforeSend(function() {
              console.log("!!NOT REACHED!!");
    }) 

})(window.jQuery, namespace('wp.checkout'), window);

UPDATE

When moving the .beforeSend(..) above the .done event I get an error in firebug, shown below:

TypeError: $.post(...).beforeSend is not a function
.beforeSend(function() {

Full change detailed below

beforeSend above done

$.post(ns.validateField, { name: userName})
        .beforeSend(function() {
            console.log("HERE");  // never reached
        })
        .done(function (data) {             
            window.location = ns.newUrl;
        })
        .always(function() {
            // this is not reached as well incidentally
        });

Upvotes: 2

Views: 5501

Answers (2)

Hüseyin Cevizci
Hüseyin Cevizci

Reputation: 919

In order to use beforeSend, you should use jQuery.ajax() method, not the jQuery.post() method. If you want to do a post request, you can specify it in settings parameters as type:"POST". You should define beforeSend event in settings parameter too.

 $.ajax({
    type:"POST",
    url:"**YOUR_POST_URL**",
    data: {name:userName}
    beforeSend: function (){
      console.log("**Whatever before send!**");
    }
  });

Upvotes: 2

JocBro1
JocBro1

Reputation: 24

Using ajax:

$.ajax({
  url: "",
  data: { name: userName},
  beforeSend: function() {
    console.log("!!NOT REACHED!!")
  }
})

Upvotes: -1

Related Questions