Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.post not always sending form data

I'm using the jQuery Post function, for example:

var fooVar = true;
var barVar = 1;
var bazVar = "baz";

$.post("url",
   {
        foo: fooVar,
        bar: barVar,
        baz: bazVar
   },
   function(){
     alert("success");
   }
);

In my logs, I'm seeing an intermittent issue where requests to "url" are being made without any form parameters, and I only have this one function which calls it.

Is there ever a situation in which the POST request can be fired, without sending the form parameters specified in jQuery Post?


I would expect to see:

foo=true&bar=1&baz=baz

However there are no form parameters at all:


UPDATE: This issue seems to be mainly on Internet Explorer browsers (IE7-IE11) from looking at the stats, however its not exclusive to IE (Chrome, Firefox have also had issues).

like image 353
Curtis Avatar asked Feb 20 '14 14:02

Curtis


3 Answers

jQuery Post can send a request without form parameters when the parameter values are undefined.

For example if we have the following:

var fooVar = undefined;
var barVar = 1;
var bazVar = "baz";

$.post("url",
   {
        foo: fooVar,
        bar: barVar,
        baz: bazVar
   },
   function(){
     alert("success");
   }
);

Then the form parameters posted will be:

bar=1&baz=baz

Now this doesn't solve my actual issue (from what I can tell correct conditions have been put in place to only make the call if all variables have a value), but it does answer my question.

like image 59
Curtis Avatar answered Nov 18 '22 09:11

Curtis


Sounds like a browser version specific issue, try to reproduce it locally with different versions of IE. It might be a typo in the code that is handled gracefully by some versions of IE but not the others (like the trailing comma in arrays) - run a JSLint/JSHint on your JavaScript code. Another scenario I can think of is CORS preflight OPTIONS request - that has no body. Are you sure that you are not executing a CORS request? Does your Ajax URL match the origin?

like image 2
peterfoldi Avatar answered Nov 18 '22 09:11

peterfoldi


Instead of using the $.post shorthand, try using $.ajax instead; not sure whether that will solve it, but it certainly won't hurt to try it out.

Plus, you'll have one less function call to worry about. Micro-optimisations ftw!

$.ajax({
  type: "POST",
  url: "url",
  data: { foo: bar }
});
like image 1
Lino Silva Avatar answered Nov 18 '22 11:11

Lino Silva