Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't include empty strings or nulls with jQuery's $.param()

I am using jQuery's $.param() to serialize an object in the following format:

var queryParams = {
    firstNm: null,
    lastNm: 'M',
    id: null,
    email: null
}

When I use $.param(queryParams), I get the following:

firstNm=&lastNm=M&id=&email=

What I would like to have instead is simply:

lastNm=M

I would like any parameters that are null or empty to not show up in the output. Is this possible using jQuery's $.param(), or will it require custom serialization?

EDIT:

This is NOT a duplicate of this question. That question pertains more to the MediaWiki API and has to do with not including the = when a parameter is null or empty, and only including the key of the key value pair. My question is whether it is possible to leave off the key value pair entirely from the output if the value is null or empty.

like image 694
Andrew Mairose Avatar asked Sep 16 '15 13:09

Andrew Mairose


2 Answers

You can write your own function to exclude null and empty values:

var queryParams = {
  firstNm: null,
  lastNm: 'M',
  id: null,
  email: null
}

function isEmpty(value){
  return value == null || value == "";
}

for(key in queryParams)
  if(isEmpty(queryParams[key])) 
     delete queryParams[key]; 

// queryParams now =  { lastNm: "M"}

and if you get this values from form you can do the following:

$("#form :input[value!='']").serialize()
like image 185
mohamed-ibrahim Avatar answered Oct 03 '22 13:10

mohamed-ibrahim


Another alternative to achieve removal of empty parameters in the serialized string.

var serializeURLParameters = function(oParameters) {
    return "?" + Object.keys(oParameters).map(function(key) {
        if(oParameters[key]) {
            return key + "=" + encodeURIComponent(oParameters[key]);
        }
    }).filter(function(elem) {
        return !! elem;
    }).join("&");
}
like image 40
Mirko Vogt Avatar answered Oct 03 '22 11:10

Mirko Vogt