First character of a string fusionning with a % - javascript

So i'm sending a String with javascript to a php page :
if(cp.value!=''){
s+=cp.name +" LIKE '%"+ cp.value +"%'";
console.log(s);
if(sec.value!=''){
s+=" AND "+sec.name+" LIKE '%"+ sec.value +"%'";
console.log(s);
}
}
else{
if(sec.value!=''){disappear
s+=sec.name+" LIKE '%"+ sec.value +"%'";
}
}
console.log(s);
if(s.length!=0){
var connect = new XMLHttpRequest();
connect.onreadystatechange=function(){
if (connect.readyState==4 && connect.status==200){
var resu=connect.responseText;
console.log(resu);
var tab=document.getElementById("main_tab");
tab.innerHTML=resu;
}
};
connect.open("POST","../../Controller/stage.php",false);
connect.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
connect.send("s="+s);
}
}
The string sent is for exemple :
CP_Stage LIKE '%90%' AND secteur_stage LIKE '%ait%'
But when i print the request in the php page i have something like :
SELECT * FROM Stage WHERE CP_Stage LIKE '�%' AND secteur_stage LIKE '%ait%';
i have no idea why my first number disappear with the first %.
If anyone have an idea it would be awesome, thanks !

The percent-sign is a special charcter. Any special characters like %,&,? etc need to be encoded. Your "%90" is converted to an Ascii-Value. You have to encode these values with encodeURIComponent.
s += cp.name + " LIKE '" + encodeURIComponent("%" + cp.value + "%") + "'";
Note that encodeURIComponent does not escape the ' character. If your cp.value has an ' you have to replace it with its encoding value: %27.
By the way.. its a bad idea to send mySQL-queries from client-side - thats a major security flaw. Send only the values and build your queries on server-side.

Related

encodeURIComponent returning string with % on it

Why whenever I run encodeURIComponent('my_url'), I get a weird looking URL like https%3A%2F%2Fr[...]... Why is that and how do I solve it?
Btw, I'm using Windows.
function createSharedAccessToken(uri, saName, saKey) {
uri = // '...'
saName = // '...'
saKey = // '...'
if (!uri || !saName || !saKey) {
throw "Missing required parameter";
}
var encoded = encodeURIComponent(uri);
var now = new Date();
var week = 60 * 60 * 24 * 7;
var ttl = Math.round(now.getTime() / 1000) + week;
var signature = encoded + '\n' + ttl;
var signatureUTF8 = utf8.encode(signature);
var hash = crypto.createHmac('sha256', saKey).update(signatureUTF8).digest('base64');
return 'SharedAccessSignature sr=' + encoded + '&sig=' +
encodeURIComponent(hash) + '&se=' + ttl + '&skn=' + saName;
}
The type of 'wierd looking url' you shared is eactly what encodeURIComponent is designed to return.
all character except
A-Z a-z 0-9 - _ . ! ~ * ' ( ) get replaced by escape sequences.
For example, any spaces become %20 and / becomes %2F.
A typical URL, processed by encodeURIComponent, might look like this:
https%3A%2F%2Fstackoverflow.com
When you are ready to display the original string, you simply use decodeURIComponent to reverse the process:
decodeYRIComponent('https%3A%2F%2Fstackoverflow.com');
// becomes: https://stackoverflow.com
It is well explained here, why we need to encode the URL
if a user writes Jack & Jill, the text may get encoded as Jack & Jill. Without encodeURIComponent() the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
If we need it in human readable form, we always have https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

GoogleTagManager do not seem to accept base64 encoded picture

Is it me or GoogleTagManager do not seem to accept base64 encoded pictures?
Exemple with the very basic code below with a very basic image.
I get the following error :
- Type : JavaScript Too Long"
- Description :
"The JavaScript in your Arbitrary HTML tag has too many contiguous non-whitespace characters (e.g. an array literal '[1,2,..]' that is too long). Try inserting spaces between statements to allow compilation (e.g. change '[1,2,...]' to '[1, 2, ...]')."
Is there no way to implement this in GTM, beside putting the js somewhere else than directly into GTM?
Best,
J.
<script type="text/javascript">
var myurl = "http://wwww.toto.com";
var myimg = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCACYAMoDAS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bVgi3ITq42XhID+PBl1t6NCBm9rujr25d/Q2Oa4iImbHZELsB8FrSoL8T0lp1aZ8Gp+Pur+QOZezco+UIiyhUkMfFqw52Ja1VVCtKrKjaXm5hsK/IUhnzow4+cCpbVo3xz1OrC66zsGnrKjim8u0hry0oZI6+nLD1d9hLTemrs8xKWNrQ/tfDmzODe7N/K5vwcLWxcjXpv5qVThy99xwDT6W4+l0NnQNYqPZoboJYXZCBNOzsRu/26q7+qu/2ZuPKONHoErOvdqd5FVVf3q0u0kP1X59CTrGr/AO3VVd/v3AAKMtQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARAAEQABEAARP/Z";
$("#beta-ad").empty();
$('<div/>', { id: "1" }).insertBefore($("#beta-ad"));
$("#1").append('<img src="' + myimg + '" style="display:inline; width: auto;" ></img>')
</script>
I think this is by design. But the workaround proposed by #Matus works.
To get around the issue of having to generate JS for a very long base base 64 encoded string I wrote a utility function, splitting the string into chunks of 150 (which GTM accepts), and generating the JS concatenation code.
You can then drop this code into your GTM tag, and reference the base64 variable.
function splitString(string, size, multiline) {
var matchAllToken = (multiline == true) ? '[^]' : '.';
var re = new RegExp(matchAllToken + '{1,' + size + '}', 'g');
var responses = string.match(re);
var value = "var base64='';";
responses.forEach(response => {
value += "base64+='" + response + "';";
});
return value;
}
var base64 = 'eyJ3aWRnZXRfc2.... etc';
var gtmString = splitString(base64, 150, true);
console.log(gtmString);
http://jsfiddle.net/azqpdwxg/2/

Javascript converting ' to URL language

I have a very simple JavaScript function that works totally fine, until one of the variables has a ' in it. This is what I tried:
function search(champ1,champ2,role) {
if((champ1!='')&&(champ2!='')){
if((champ1!=champ2)) {
var champ1_name = encodeURI(champ1);
var champ2_name = encodeURI(champ2);
var role_name = encodeURI(role);
window.location.href="http://myurl.com/"+role_name+"/"+champ1_name+"&"+champ2_name;
return false;
} else if(champ1==champ2) {
window.location.href="http://myurl.com/"+role;
}
}
}
but unfortunately when I run this script the URL still has the ' in it even after they ran through encodeURI()
If you need to escape ', do something like .replace("'", "%27"). Or use a URL escaping function that lets you provide a string of characters that need to be escaped.
decodeURIComponent("%27") converts back to "'".

Unexpected Token Illegal with onclick Java Script in Salesforce.com

I have been working on this most of the morning but to no end. I am trying to execute a button that uses OnClick Java in Salesforce.com and it keeps throwing errors. I think the issue may be with special characters in the data as it works when I simply use just text. But any time numbers or any special characters are present I get the error "unexpected token ILLEGAL". Can anyone help me to see what I am doing wrong and how I can get away from failing when special characters are involved?
{!REQUIRESCRIPT("/soap/ajax/28.0/connection.js")}
var opptyObj = new sforce.SObject("Opportunity");
var caseObj = new sforce.SObject("Case");
var today = new Date();
var sOpptyId = "{!Case.Opportunity__c}";
if( sOpptyId != "")
{
alert("This case is already tied to an opportunity!");
}
else
{
opptyObj.AccountId = "{!Case.AccountId}";
opptyObj.CloseDate = sforce.internal.dateTimeToString(today);
opptyObj.Description="{!Case.Description}";
opptyObj.Case__c = "{!Case.Id}";
opptyObj.Name = "{!Case.Subject}";
opptyObj.StageName = "Estimate in Progress";
opptyObj.Created_from_Case__c = "Y";
opptyObj.Type = "New Business";
opptyObj.Amount = ".01";
var opptyresult = sforce.connection.create([opptyObj]);
if (opptyresult[0].success=='false')
{
alert("Opportunity creation failed: " + opptyresult[0].errors.message);
}
else
{
caseObj.Id = '{!Case.Id}';
caseObj.Opportunity__c = opptyresult[0].id;
caseObj.Status = "Estimate in Progress";
var caseResult = sforce.connection.update([caseObj]);
if(caseResult[0].success == 'false')
{
alert("Case update failed: " + caseResult[0].errors.message);
}
else
{
alert("An opportunity has been created and linked to this case.");
location.reload(true);
}
}
}
Assuming this is some kind of template, whatever is rendering this needs to properly escape some values in the strings it's inserting.
Given this:
opptyObj.Description="{!Case.Description}";
Let's say I enter a description consisting of this:
"That is awesome," said John.
When that is rendered in your template the result is this:
opptyObj.Description=""That is awesome," said John.";
As you might be able to see, the result is a syntax error.
You need to escape quote characters in an text inserted this way. And without knowing what is technology rendering this template I can't give you any specifics, but you want to replace " with \" and ' with \'. The \ escapes characters, forcing them to be treated as literal characters in the string instead of other special meaning.
This must be done as it's being inserted into the script. Something in the spirit of this:
opptyObj.Description="{!Case.Description.replace(/'/, "\\'").replace(/"/, '\\"')}
Exactly how to do that depends on what language or template engine is being used here. But th eresult should look like this:
opptyObj.Description="\"That is awesome,\" said John.";
Ruby on Rails implements an escape_javascript method, which sanitizes data for injection into Javascript. It does the following replacements. It seems like a good baseline.
'\\' => '\\\\'
'</' => '<\/'
"\r\n" => '\n'
"\n" => '\n'
"\r" => '\n'
'"' => '\\"'
"'" => "\\'"
UPDATE:
According to this: http://www.salesforce.com/us/developer/docs/pages/Content/pages_security_tips_scontrols.htm
It looks like you want the JSENCODE function. Something like this, perhaps?
opptyObj.Description="{!JSENCODE(Case.Description)}";

How can I truncate result titles?

Im using soundclouds api to echo out track information but I'd like to limit the amount of characters shown for each track title result to just 24 chars? I'd also like to be able to set both the track title and artist title to be displayed as capitalised text (first letter capital rest lowercase)
Thanks
<li>Track: ' + track.title + '<BR>Artist: '+ track.user.username + '</li>'
Try this:
function formatter(str) {
if(str.length < 24) {
return str;
} else {
return str.charAt(0).toUpperCase() + str.substr(1,23) + '..';
}
}
<li>Track: ' + formatter(track.title) + '<BR>Artist: '+ formatter(track.user.username) + '</li>'
DEMO
For part 1 of your question, look at substr method. It's a standard method on all JavaScript String objects.
For part 2, capitalizing, check out this question.
You can prepare the short title in advance, first taking the substring and making sure it is lower case:
var shortTitle = track.title.substr(0,24).toLowerCase();
Then use the following to upper case the first letter and use the rest of the lowercase string, adds ...:
// ... HTML ouput by JS ...
document.write(shortTitle.charAt(0).toUpperCase() + shortTitle.slice(1));
if (shortTitle.length > 24)
document.write('...');
// ... HTML output by JS ...
Here in an example.
You can repeat these steps for the author.

Categories

Resources