Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.ajax() and sending boolean request arguments

$.ajax({
  url : uri,
  type : 'post',
  data : {someBooleanVar1: false, subVar: {someBooleanVar2: true}}
});

The problem is that on server someBooleanVar1 and someBooleanVar2 will be received as strings "false" and "true", but not as "0" and "1". Is there any way to automatically convert boolean arguments to "1" and "0"?

like image 794
barbushin Avatar asked Feb 08 '11 13:02

barbushin


People also ask

How does AJAX work in jQuery?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

How does AJAX return an API call?

ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


1 Answers

There is a fixed version of @jcubic Answer:

function convertBoolToNum(obj) {
    $.each(obj, function(i) {
        if (typeof obj[i] == 'object') {
            convertBoolToNum(this);
        }
        else if (typeof obj[i] == 'boolean') {
            obj[i] = Number(obj[i]);
        }
    });
}

$.ajax = (function($ajax) {
  return function(options) {
    convertBoolToNum(options.data);
    return $ajax(options);
  };
})($.ajax);
like image 129
barbushin Avatar answered Oct 20 '22 01:10

barbushin