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

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.

Related

distinguishing qrcode url parameters from those of the api url

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)}`

Store data having a double quote in a javascript var

I have a var in script which has data like . But when i add this to another variable its not working.
var x = '32"';
onclick="javascript:selectSize(' + "'" + x + "'" + ');"
I want
onclick="javascript:selectSize('32"');"
But it becomes
onclick="javascript:selectSize('32"');""=""
i don't know whats happening
onclick="javascript:selectSize('32"');"
^ ^
The HTML parser will parse the attribute value before passing the value of it to the JS engine for execution.
You are using a " to delimit the attribute value.
The second " ends the attribute value.
If you want to use " as data in an attribute value delimited with " then you must express it as an entity (e.g. ").
var html_x = x.replace(/"/g, """);
Escaping becomes very painful when you start generating nested languages.
You have JavaScript embedded in HTML embedded in JavaScript.
Avoid mashing strings together to construct your DOM. Use DOM methods directly instead.
var x = '32"';
var button = document.createElement("button");
button.addEventListener("click", function (event) {
selectSize(x);
});
from comment, Make use of encode/decode URI Component as follows
var a=encodeURIComponent('abc"');
console.log(a);
console.log(decodeURIComponent(a));

how to embed value with an apostrophe in querystring

I have the following javascript:
tr.append("<a href='add_widget.html?id=" + data[i].id + "&pg=" + data[i].page_number + "&dest=" + data[i].dest + "&name=" + data[i].name.replace("'","\\'") + "'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>");
The code in question has to do with the name field.
If I have a name like "John Doe" when I click on the hyperlink created by the above javascript, the new page's querystring has the full name.
However, if I try to pass a name like "John's stuff", the above logic creates a query string variable that looks like this:
&name=John\
How can I change the above code so that the entire string "John's stuff" is passed to the add_widget.html page?
Thanks.
replace("'","%27")
try http://meyerweb.com/eric/tools/dencoder/ it's an online URL encoder/decoder.
When you're trying to "protect" characters, you have to keep in mind what you're protecting them from. In this case, there are two interpreters you have to worry about:
You're building HTML, so you have to worry about the HTML parser;
You're building a URL, so you have to worry about how the browser and the server will parse the URL.
To deal with the first problem, you can replace the quotes with the HTML entity equivalent ('). To deal with the second, you can use encodeURIComponent().
I think you'd want to do the encodeURIComponent() call first, to avoid having the HTML entity notation get messed up. The entity notation will be gone after the HTML parser is finished with the string anyway:
function qEncode(str) {
return encodeURIComponent(str).replace(/'/g, "'");
}
To use that:
tr.append("<a href='add_widget.html?id=" +
qEncode(data[i].id) + "&pg=" +
qEncode(data[i].page_number) + "&dest=" +
qEncode(data[i].dest) + "&name=" +
qEncode(data[i].name) +
"'</a><button class='btn btn-xs btn-primary'>Edit</button> </td>"
);
Note that you could also encode double-quote characters too.
A totally different way of working around this problem would be to build the DOM content with DOM APIs. By doing that, you'd completely avoid the HTML parser, and you'd just need encodeURIComponent().
You need to think, what will be interpreting my code, so what do I need to escape for?
Your code will be interpreted by the HTML Interpreter in the browser
Your code will be interpreted as a URI
This means you need to escape/encode them in reverse order. Luckily JavaScript provides a URI encoder as encodeURIComponent, but it doesn't provide a HTML one (probably as we have DOM Methods) but it isn't too hard to implement for important characters, e.g.
function html_encode(str) {
var re_chars = /[<>'"]/g;
function replacer($0) {
return '&#' + $0.charCodeAt(0) + ';'
}
return str.replace(re_chars, replacer);
}
// example follows
html_encode('<foo bar="baz">'); // "<foo bar="baz">"
So for you,
attrib_value = html_encode(/* ... + */ encodeURIComponent(data[i].name) /* + ... */ );
For completeness,
function html_decode(str) {
var re = /&(?:#\d{1,3}|amp|quot|lt|gt|nbsp);/g, // notice extra entities
d = document.createElement('div');
function replacer($0) {
d.innerHTML = $0;
return d.textContent;
}
return str.replace(re, replacer);
}
// and an example
html_decode('<foo bar="baz">'); // "<foo bar="baz">"
Using escape(data[i].name) instead of data[i].name.replace("'","\\'"), will solve your problem.

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);

How to JSON decode array elements in JavaScript?

I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.
But if I try to do a redirect or simply do an 'alert' on the link array element I get:
function(){return JSON.encode(this);}
As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.
After following some suggestions I've run eval('(' + jsonObject + ')') but it still returns the same output.
So how's this done ?
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
See the jQuery API.
Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -
echo json_encode($iniData);
In Javascript, use the following :
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajaxCalls.php",
data: "dataType=ini",
success: function(msg)
{
var x = eval('(' + msg + ')');
$('#allowed').html(x.allowed); // these are the fields which you can now easily access..
$('#completed').html(x.completed);
$('#running').html(x.running);
$('#expired').html(x.expired);
$('#balance').html(x.balance);
}
});
});
</script>
If you get this text in an alert:
function(){return JSON.encode(this);}
when you try alert(myArray[i]), then there are a few possibilities:
myArray[i] is a function (most likely)
myArray[i] is the literal string "function(){return JSON.encode(this);}"
myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.
The simplest way to tell would be to check typeof(myArray[i]).
eval('(' + jsonObject + ')')
JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.
You will then have a JavaScript datastructure that you can traverse for the data you need.
If the object element you get is a function, you can try this:
var url = myArray[i]();
I decode JSON this way:
eval( 'var from_json_object = ' + my_json_str + ';' );

Categories

Resources