distinguishing qrcode url parameters from those of the api url - javascript

I want to generate a qr code with multiple pre-filled values. But only the first value seems to be encoded into the generated qr code. I guess because it's assuming parameters after the first belong to the api url..
Can anyone help me here?
.src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data="
+ "https://google.com/?" + "field1=" + var1 + "&" + "field2=" + var2
I've looked online without luck - perhaps because I don't know how to describe the problem. (note that google.com is jut a placeholder url, and not the one i'm using)

Since the URL you are trying to pass to data contains /, ? and & you have to encode it. For instance, the browser wouldn't know whether to pass field2 to the main URL or to the data URL. To encode the URL being passed to data:
const url = "https://google.com/?" + "field1=" + var1 + "&" + "field2=" + var2
const src = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + encodeURIComponent(url)
On an unrelated note, consider using template string to make your code more readable:
const url = `https://google.com/?field1=${var1}&field2=${var2}`
const src = `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(url)}`

Related

How do I extract the domain with a hash?

I want to extract the domain with a hash without the long random id from the location address bar to make it to show like this:
http://test.example.com/#inbox
Here is the full URL:
http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=
Here is what I have tried so far:
var url = location.hash.split('#inbox')[1];
And I have also tried this:
var url = $(location).attr("href").split('/')[2];
Unfortunately, I didn't get what I want to extract the domain and the hash without the long random id.
When I try it, it extracts the domain name and the hash without the random id to get the return output for the URL like http://test.example.com/#inbox.
I would use indexOf() to find the position of the '#' character. Since the URL can't include a '#', it is safe to assume that the first '#' will be the one you're interested in.
Then I would search for the '/', again with indexOf(), so the word between the '#' and the '/' can change and things still work as expected.
That position is the location of the '/' and anything before that can be returned which is what the String.sub() function does and it returns that URL you're looking for:
var pos = location.href.indexOf('#')
pos = location.href.indexOf('/', pos)
var url = location.href.substr(0, pos)
Another way, although I'm not sure whether it's fully portable, is to use the location fields like so:
var url = location.origin + location.pathname + "#inbox"
If the "#inbox" part can change, you may be able to tweak the code or search for a slash in location.hash like so:
var pos = location.hash.indexOf('/')
var url = location.origin + location.pathname + location.hash.sub(0, pos)
Either way should be plenty fast anyway (especially since you won't need to loop over such).
I got the whole URL, found where the "#" is, added 6 to its count for "#" + the word "inbox", and dropped the rest of the URL:
var url = document.URL;
var i = url.indexOf('#') + 6; // 6 is length of "#" + the word "inbox"
var answer = url.substr(0, i);
Try the code below:
// Complete URL
var url = 'http://test.example.com/#inbox/U2FsdGVkX19stSSdMXLZq5v7bOgzRLtaM7Lr1t+lWpI=';
var desiredResult = url.match(/.*\/\#inbox\//)[0];
console.log(desiredResult.substring(0, desiredResult.length - 1)); // this will output 'http://test.example.com/#inbox'

replace certain parameter or entire URL

I need to replace the window URL with a new one based on a checkbox input. I'm trying to do this like so:
// get checkbox value
var selection = $('input[type="checkbox"]:checked').val()
// get current url
var url = window.location.href;
// prefix current URL with checkbox
url += '&site=' + selection + '&page=1';
// debug line
// console.log(url);
// navigate to new URL
location.replace(url);
I have a series of parameters at the end of my URL that looks like:
mywebsite.com&site=main&page=1
I either need to replace the entire URL, or just the parameters below:
&site=main&page=1
The key is in the last line. I've tried a few things this is the output:
Both location.assign(url); and location.replace(url); gives: mywebsite.com&site=main&page=1&site=main&page=1
window.location.href() seems to have the same behavior, it does not replace the entire URL.
What I don't understand is for location.replace() - sanity checking the behavior on reading MDN, it quotes:
The Location.replace() method replaces the current resource with the
one at the provided URL.
Ok, lets do it. Then this happens:
http://mywebsite.com&site=main&page=1&site=main&page=1
Beating to the punch - in the console log - it returns the correct URL parameters. So output in my console looks like:
http://mywebsite.com&site=main&page=1
Why is it not replacing the entire URL with the new one? How do you just replace the entire URL with a new one, or somehow just target the parameters? Regex?
Why not just build the URL you want and set that?
var url = 'http://mywebsite.com?site=' + selection + '&page=1';
location.href = url;
If you don't know what page you are on and that will be dynamic you can do:
var hostAndPath = location.host + location.pathname;
var selection = $('input[type="checkbox"]:checked').val();
var url = hostAndPath + '?site=' + selection + '&page=1';
location.href = url;

using + in the variables passed to a url

I am trying to do a call to url
http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415
If you look at var1 that I am passing value 'CD14+ MDM in GM-CSF 3 days then 3days IFN-γ'.
When in the controller I try to get this var 1 using request.params.get("var1"), i get 'CD14 MDM in GM-CSF 3 days then 3days IFN-γ' with missing + and instead getting extra space after CD14
How can I pass + in my variable in url
This has an answer here. It says that + needs to be encoded as %2B.
If you are intended to use plus as a data component, instead of url component, You should pass %2B instead.
Javascript :
var url = "http://example.com/controller/action?var1=CD14+%20MDM%20in%20GM-CSF%203%20days%20then%203%20days%20IFN-%CE%B3&var2=56&var3=ENSG00000115415";
//NOTE: this following wil lreplace all + to %2B
url = url.replace(/\+/g,"%2B");
console.log("new : ",url);
Try '%2B' (as other have stated).
But if you are in Javascript, you could just use the built-in method for doing URL encoding called "encodeURIComponent". Note you need that and not "encodeURI" which will not encode reserved characters like '+'. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Jquery & JSON: Replace section of JSON array

I've been reading a ton on this and can't seem to find a solution that works for me. I am building a drag and drop menu system and saving the structure to the db as JSON.
I have a hidden field as part of a form that submits to the db. This hidden field has the full JSON string in it.
When I update a particular node/menu item, I want to search the value of the hidden text field, find the 'section' of JSON I want to update and replace it with the new values.
What is the best solution for this? grep? replaceWith?
Example before and after JSON
// This is the full json string
[{"title":"Cool link","link":"link","cssclass":"","cssid":"","id":"1399209929525"},{"title":"New link","link":"new-link.html","cssclass":"","cssid":"","id":"1399209790202"},{"title":"Another link","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
// This is the updated section
[{"title":"Another link changed","link":"cool","cssclass":"","cssid":"","id":"1399209834496"}]
So I have the updated section with a unique ID to search against.
A simple solution would be something like this, but it doesn't work like that.
var currentsection = /'{"title":"' + edittitle + '","link":"' + editurl + '","cssclass":"' + editcssclass + '","cssid":"' + editcssid + '","id":"' + editid + '"}'/;
var newsection = /'{"title":"' + updatedtitle + '","link":"' + updatedlink + '","cssclass":"' + updatedcssclass + '","cssid":"' + updatedcssid + '","id":"' + updatedid + '"}'/;
$("#menu_items").val().find(currentsection).replaceWith(newsection);
What do you think the best approach is? Many thanks for taking the time out to help. I really appreciate it.
I think you should create your JSON object, and work with it. In this way it would be easy to change values and also save it as you want ;)
For example :
var json = YOUR JSON HERE;
var obj = JSON.parse(json);
// now you can update values as you want
// for example with example title
obj[0].title = "updatetitle";
And then, before sending your JSON, you may want to convert it in plain text
var json = JSON.stringify(obj);

Due to & in string , can't pass using JSON

I am using this format to pass data to server in GET request .
var val = {
name:"abcd",
age="21"
}
var val2 = "test2" ;
http://server-name/getdata.htm?data=JSON.stringify(val)&data1=val2
.
This works fine but , when val.name is like "abcd&def"
the format of request gets distorted due to this "&"
What should I do ?
What should I do ?
You should correctly encode the elements of the query string, using encodeURIComponent (that's a link to MDC, but the function is available in all browsers, not just Firefox).
You haven't shown actual code, but along these lines:
var link = "http://server-name/getdata.htm?data=" +
encodeURIComponent(JSON.stringify(val)) +
"&data1=" +
encodeURIComponent(val2);
Technically, the more correct way would be to also encode the keys data and data1, like this:
var link = "http://server-name/getdata.htm?" +
encodeURIComponent("data") + "=" +
encodeURIComponent(JSON.stringify(val)) +
"&" + encodeURIComponent("data1") + "=" +
encodeURIComponent(val2);
...but when you're dealing with literal keys (as opposed to keys coming from strings you don't control), when you know the encoded form is identical to the original (which it is for data and data1), you can get away with not encoding the keys.

Categories

Resources