jQuery append params to url - javascript

I like the way jQuery's $.ajax() method allows to specify request url:
{
url: 'http://domain.com/?param=1',
data{
param2: '2'
}
}
$.ajax() method will (probably) call $.param() on provided data and optionally append it to provided URL.
My question is: is this type of url manipulation available outside of $.ajax() call?
For example, I want to open a popup window, and I would like to construct URL in the same way that I do with $.ajax().
I have written a function which does this, but I have a feeling I am reinventing the wheel and duplicating already existing function of jQuery:
var prepareUrl = function( url, data )
{
var params = $.param( data );
if ( params.length > 0 )
{
// url contains a query string
if ( url.indexOf( '?' ) > -1 )
{
// get last char of url
var lastChar = url.substr( url.length - 1 );
// Append & to the end of url if required
if ( lastChar != '&' && lastChar != '?' )
{
url += '&';
}
}
else // url doesn't contain a query string
{
url += '?';
}
url += params;
}
return url;
}
thanks!

Since other replies didn't answer my question, i have made a few tests with the $.ajax() call to see how it merges urls with param data.
My findings so far:
if url contains a ?, then $.ajax() will append '&' + $.param(data)
if not, then $.ajax() will append '?' + $.param(data)
So if I want to keep my url processing function consistent with the way $.ajax() does it, then it should be something like the following:
var addParams = function( url, data )
{
if ( ! $.isEmptyObject(data) )
{
url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);
}
return url;
}
I am still wondering if there is a built-in jQuery method to do this.

You can build query string like this:
getQueryStr = function(obj) {
var str = [];
for (var p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
console.log(serialize({
param1: "val1",
param2: "val2"
}));
For recursive :
getQueryStr = function(obj, prefix) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p,
v = obj[p];
str.push(typeof v == "object" ?
getQueryStr(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize({
favfruit: "apple",
data: {
name: 'js',
points: [1, 2, 3]
}
}));

yes you can use jqueries .param() function to do this.
jsfiddle demo
var params = { param1:"foo", param2:"bar"};
var str = jQuery.param( params );
alert(str);

The param method will generate a query string for you, but you will need to to remove the existing query string.
var base = "http://example.com/foo/?example=old";
var data = {
foo: "hello",
bar: "world?"
};
var url = base.replace(/\?.*$/, "") + "?" + jQuery.param(data);
alert(url);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

As mentioned in this SO answer, just use URLSearchParams
let urlParams = new URLSearchParams(location.search.substr(1));
urlParams.set(key, value);
where key=value is new url parameter that you want to add
You could check the browser compatibility here

Related

Best practice for sending JSON to php with keeping field types

Obviously, if I send JSON data to php using an AJAX post or get request I will end up only receiving string data type in the php $_POST variable.
What is best practice for sending JSON fields but keeping their data types? My idea would be to send the whole JSON in one $_POST field, and then decoding it one more time.
So in JavaScript instead of:
$.post('test.php', {"stringparm":"a string","numparm": 66,"boolparm":true)}, function (result) ...
I would use:
params = '{"stringparm":"a string","numparm": 66,"boolparm":true)}';
$.post('test.php', {'params': params}, function (result) {
....
}
And in php I would:
$params = json.decode($_POST['params']);
or is there a better way?
My recommendation would be to send them as a query string using Fetch or Axios, you can use Ajax as well and it should send the various datatypes properly, and then parse the query string in PHP like this.
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
I'm sure you know what your standard query string looks like
https://example.com/?user_id=value&someotherdata=value etc...
Once you have the $data object you can access the values with the arrow -> operator.
$user_id = $data->user_id
Here is a script I use to create a query string from a provided object.
prepareQuerystring(url, paramsObject, isParamsObjectUsed, phpMethod = '') {
if (url !== '') {
let postUrl = `${url}${phpMethod}`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${url}${phpMethod}/`;
return postUrl;
}
} else {
let postUrl = `${window.location.href}${phpMethod}/`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${window.location.href}${phpMethod}/`;
return postUrl;
}
}
}
The url argument is your base url (https://example.com)
The paramObject is your JSON object which is just an object in Javascript.
{
user_id: 1,
someotherdata: 'shoe'
}
The PHP method argument is there to call a specific method in php, it simply gets appended after the base url, my API lets me make calls this way, yours might not so you can just leave that as an empty string ''.
And the isParamsObjectUsed is a boolean, if you pass an object in the second argument then this will be true, I honestly can't recall ever setting it to false so may need to refactor and remove that eventually.
Heres an example of how to use it.
let url = prepareQuerystring(
https://example.com/,
{
user_id: 1,
someotherdata: 'shoe',
someBool: true
},
true
)
You will have reference to all the parameters as their data type in PHP using this method. I use Axios to send http requests but this also works with Ajax and Fetch, I'd recommend using Fetch or Axios. Mostly because I can't remember how I got it working with Ajax, I typically use Fetch or Axios.
Using Fetch
fetch(url, { method: "POST" })
Hope this helps point you in the right direction. Let me know if you have any questions.

If statement in Javascript return values

I am learning Javascript. I wrote a JS to return a Json-type value.
var generateUrl = function(Name, Letter, rootUrl, V1) {
rootUrl = rootUrl || Letter;
return {
classname: 'mycss-' + Letter,
text: Name,
url: rootHref.replace(Rex, "$1" + rootUrl + "."),
onclick: {
fn: clickFn,
obj: V1
}
};
};
I want to add a if statement inside url:.
For example, if Name = google, url won't use this logic rootHref.replace(Rex, "$1" + rootUrl + "."), instead it will directly return an url.
I have searched for an answer quite a while but still have no luck. May someone tell me how to add a if statement logic in my code.
Try as follows
url: (num == 1) ? Link1 : Link2,

How to redirect to same page with parameters given as json

On my site i am using jQuery's ajax this way:
$.ajax({
type: 'GET',
url: productSearch.searchUrl,
data: parameter,
dataType: 'json'
}
"data" contains all parameters.
On some state i want to redirect the user to the same page but with all paramters from "data" appended.
Example
data = {
"par1" = "value1",
"par2" = "value 2"
}
current url: www.google.com
should be redirected to www.google.com?par1=value1&par2=value2.
How to do this (with jQuery?)?
with simple javascript
window.location.href = "www.google.com?" + Object.keys(data).map(function(key){
return key + "=" + data[key];
}).join("&");
And yes, data key can be encoded as well
window.location.href = "www.google.com?" + Object.keys(data).map(function(key){
return encodeURIComponent(key) + "=" + encodeURIComponent(data[key]);
}).join("&");
Since you're using jQuery, $.param() will serialize an object like that. Then you just append the resulting string to the URL.
try:
var data = {
"par1": "value1",
"par2": "value 2"
}
var params = $.param(data);
if (location.href.match(/\?/)) {
location.href += params;
} else {
location.href += '?' + params;
}
You can try this:
params = $.params(data);
window.location.href = window.location.href +'?'+params;

How to parse the first line of the http header?

Is there any javascript function, to parse the first line of the http header?
GET /page/?id=173&sessid=mk9sa774 HTTP/1.1
The url is encoded.
I would like to get an object, like this:
{
"method" : "GET",
"url" : "/page/",
"parameters": {
"id" : 173,
"sessid" : "mk9sa774"
}
}
I searched a lot, but I haven't found anything useful.
thanks in advance,
First you can split on spaces:
var lineParts = line.split(' ');
Now you can get the method, unparsed path, and version:
var method = lineParts[0];
var path = lineParts[1];
var version = lineParts[2];
Then you can split up the path into the query string and non-query string parts:
var queryStringIndex = path.indexOf('?');
var url, queryString;
if(queryStringIndex == -1) {
url = path, queryString = '';
}else{
url = path.substring(0, queryStringIndex);
// I believe that technically the query string includes the '?',
// but that's not important for us.
queryString = path.substring(queryStringIndex + 1);
}
If there is a query string, we can then split it up into key=value strings:
var queryStringParts = [];
if(queryStringIndex != -1) {
queryStringParts = queryString.split('&');
}
Then we can unescape them and stuff them into an object:
var parameters = {};
queryStringParts.forEach(function(part) {
var equalsIndex = part.indexOf('=');
var key, value;
if(equalsIndex == -1) {
key = part, value = "";
}else{
key = part.substring(0, equalsIndex);
value = part.substring(equalsIndex + 1);
}
key = decodeURIComponent(key);
value = decodeURIComponent(value);
parameters[key] = value;
});
If you really wanted to, you could then put all that data into an object:
return {
method: method,
url: url,
version: version,
parameters: parameters
};
If you're in a browser environment, that's the only way to do it. If you're using Node.JS, it can deal with the URL parsing for you.

Support for encoding query string or POST data in YUI?

How do you encode a javascript object/hash (pairs of properties and values) into a URL-encoded query string with YUI (2.7.0 or 3.0.0 Beta) ?
I want to do the equivalent of Object.toQueryString() from Prototype:
I need this to encode parameters for GET and POST requests with YAHOO.util.Connect.
It turns out YAHOO.util.Connect has a setForm() method to serialize a form but that still leaves me out cold to encode parameters for GET requests, or the 4th parameter of YAHOO.util.Connect.asyncRequest() to pass post data.
I've made this little helper for my own project.
var toQueryString = function(o) {
if(typeof o !== 'object') {
return false;
}
var _p, _qs = [];
for(_p in o) {
_qs.push(encodeURIComponent(_p) + '=' + encodeURIComponent(o[_p]));
}
return _qs.join('&');
};
// And to use it
var qs = toQueryString({'foo' : 'bar'});
YUI3 has the io-form module, which you can instantiate in your call the use. It allows you to write code like this:
YUI().use('node', 'io-form', function(Y) {
Y.get('#formId').on('sumbit', function(e) {
e.preventDefault();
Y.io(postURL,
{
method: "POST",
on: {
complete: on_complete_handler
},
form: {
id: "formId"
}
});
}
});
This code will make a POST request to postURL, with all the input values from the form with id "formId" is submitted. This module also works for GET requests.
I ended up using something like this based on some code found on github. The function must handle posting arrays..
"Y" is a reference to "YAHOO"
/**
* Turns an object into its URL-encoded query string representation.
*
* #param {Object} obj Parameters as properties and values
*/
toQueryString: function(obj, name) {
var i, l, s = [];
if (Y.lang.isNull(obj) || Y.lang.isUndefined(obj)) {
return name ? encodeURIComponent(name) + '=' : '';
}
if (Y.lang.isBoolean(obj)) {
obj = obj ? 1 : 0;
}
if (Y.lang.isNumber(obj) || Y.lang.isString(obj)) {
return encodeURIComponent(name) + '=' + encodeURIComponent(obj);
}
if (Y.lang.isArray(obj)) {
name = name; // + '[]'; don't do this for Java (php thing)
for (i = 0, l = obj.length; i < l; i ++) {
s.push(arguments.callee(obj[i], name));
}
return s.join('&');
}
// now we know it's an object.
var begin = name ? name + '[' : '',
end = name ? ']' : '';
for (i in obj) {
if (obj.hasOwnProperty(i)) {
s.push(arguments.callee(obj[i], begin + i + end));
}
}
return s.join("&");
}
I see YUILibrary Ticket 2528174 refers to an accepted contribution on for this.
The Querystring Utility
Provides static methods to serialize objects to querystrings and deserialize objects from querystrings.
Three modules are available:
querystring - Both parse and stringify functionality
querystring-parse - Parse valid querystring into JavaScript objects
querystring-stringify - Serialize JavaScript objects into valid query strings

Categories

Resources