How To Create Query String In Jquery?
Solution 1:
Submit form
The simplest way to build and send request with filter parameters is to submit form that contains the filter's controls to your server that is defined by the form's action
attribute value. If you need to apply the filter every time the filter is changed, then just call .submit()
method in the form change
event handler.
Serialize form
If you need to build request URL manualy, then you could use .serialize()
method. Just place your controls to a form, and it will be possible to get query string by the form serialization.
var staticUrl = '/the/path/of/request';
$("#filter").change(function() {
var queryString = $(this).serialize();
var url = !queryString ? staticUrl : staticUrl + '?' + queryString;
console.log(url);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script><formid="filter"><h3>Select your favorite sports:</h3><label><inputclass="getfilter"type="checkbox"value="football"name="sport"> Football</label><label><inputclass="getfilter"type="checkbox"value="baseball"name="sport"> Baseball</label><label><inputclass="getfilter"type="checkbox"value="cricket"name="sport"> Cricket</label><label><inputclass="getfilter"type="checkbox"value="boxing"name="sport"> Boxing</label><label><inputclass="getfilter"type="checkbox"value="racing"name="sport"> Racing</label><label><inputclass="getfilter"type="checkbox"value="swimming"name="sport"> Swimming</label><br><h3>Select your favorite food:</h3><label><inputclass="getfilter"type="checkbox"value="choclate"name="food"> Choclate</label><label><inputclass="getfilter"type="checkbox"value="biscuits"name="food"> Biscuits</label><label><inputclass="getfilter"type="checkbox"value="candy"name="food"> Candy</label><label><inputclass="getfilter"type="checkbox"value="Cake"name="food"> Cake</label></form>
The result query string is standard. It should be parsed correctly by PHP server. But if you need any special format, you could transform the string using regular expressions. For example, use following to separate several values of same field by ~
character:
var staticUrl = '/the/path/of/request';
var delimiter = '~';
$("#filter").change(function() {
var queryString = $(this).serialize().replace(/(?<=([^\?\&\=]+=)([^\&\=]+))(\&\1)/g, delimiter);
var url = !queryString ? staticUrl : staticUrl + '?' + queryString;
console.log(url);
});
You could see the transformation result using the regex101 snippet.
Note, a zero-width positive lookbehind assertion is used in the regular expression. It requires to browser support ES2018.
Build query string form array
If it is not possible to use a zero-width positive lookbehind assertion, then you could use classical way: transform a set of form elements to an array of names and values using serializeArray
method and then build query string from the array.
The serializeArray
creates an item for each control. It is possible to group form values by field name using reduce
method.
var staticUrl = '/the/path/of/request';
var delimiter = '~';
$("#filter").change(function() {
var query = $(this)
// Create array
.serializeArray()
// Group array by key name
.reduce(function(grouped, field) {
grouped[field.name] = grouped[field.name] || [];
grouped[field.name].push(field.value);
return grouped;
}, {});
// Build query stringvar queryString = $
.map(query, function(values, name) {
return name + '=' + values.join(delimiter);
})
.join('&');
// Build URLvar url = queryString ? staticUrl + '?' + queryString : staticUrl;
console.log(url);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid="filter"><h3>Select your favorite sports:</h3><label><inputclass="getfilter"type="checkbox"value="football"name="sport"> Football</label><label><inputclass="getfilter"type="checkbox"value="baseball"name="sport"> Baseball</label><label><inputclass="getfilter"type="checkbox"value="cricket"name="sport"> Cricket</label><label><inputclass="getfilter"type="checkbox"value="boxing"name="sport"> Boxing</label><label><inputclass="getfilter"type="checkbox"value="racing"name="sport"> Racing</label><label><inputclass="getfilter"type="checkbox"value="swimming"name="sport"> Swimming</label><br><h3>Select your favorite food:</h3><label><inputclass="getfilter"type="checkbox"value="choclate"name="food"> Choclate</label><label><inputclass="getfilter"type="checkbox"value="biscuits"name="food"> Biscuits</label><label><inputclass="getfilter"type="checkbox"value="candy"name="food"> Candy</label><label><inputclass="getfilter"type="checkbox"value="Cake"name="food"> Cake</label></form>
Solution 2:
Your html code is perfect and you need some modification in javascript code to get it work.
You also need to push state of updated url with new query string in history. So, you can update url of browser without page load.
$(document).ready(function() {
var queryStringObject = {};
$(".getfilter").click(function(){
var name = $(this).attr('name');
queryStringObject[name] = [];
$.each($("input[name='"+$(this).attr('name')+"']:checked"), function(){
queryStringObject[name].push($(this).val());
});
if(queryStringObject[name].length == 0){
delete queryStringObject[name];
}
var queryString = "";
for (var key in queryStringObject) {
if(queryString==''){
queryString +="?"+key+"=";
} else {
queryString +="&"+key+"=";
}
var queryValue = "";
for (var i in queryStringObject[key]) {
if(queryValue==''){
queryValue += queryStringObject[key][i];
} else {
queryValue += "~"+queryStringObject[key][i];
}
}
queryString += queryValue;
}
console.log(queryStringObject);
console.log(queryString);
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + queryString;
window.history.pushState({path:newurl},'',newurl);
}
});
});
<body><h3>Select your favorite sports:</h3><label><inputclass="getfilter"type="checkbox"value="football"name="sport"> Football</label><label><inputclass="getfilter"type="checkbox"value="baseball"name="sport"> Baseball</label><label><inputclass="getfilter"type="checkbox"value="cricket"name="sport"> Cricket</label><label><inputclass="getfilter"type="checkbox"value="boxing"name="sport"> Boxing</label><label><inputclass="getfilter"type="checkbox"value="racing"name="sport"> Racing</label><label><inputclass="getfilter"type="checkbox"value="swimming"name="sport"> Swimming</label><br><h3>Select your favorite food:</h3><label><inputclass="getfilter"type="checkbox"value="choclate"name="food"> Choclate</label><label><inputclass="getfilter"type="checkbox"value="biscuits"name="food"> Biscuits</label><label><inputclass="getfilter"type="checkbox"value="candy"name="food"> Candy</label><label><inputclass="getfilter"type="checkbox"value="Cake"name="food"> Cake</label><br></body><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Post a Comment for "How To Create Query String In Jquery?"