Escape special characters in Javascript SQL Query - javascript

I'm trying to send an SQL query with javascript using a variable sourced from an input. In this input, characters like ' and " along with others may be entered.
Here's what my script function looks like:
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = document.getElementById('Desc' + r).value;
desc = desc.replace(/&/g, "&").replace(/>/g, ">").replace(/</g, "<").replace(/"/g, '"""').replace(/'/g, '"'"');
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
An example of the value for 'desc' that I'd want to send is:
80-0234-1 6'5" GATE
So it's a combination of numbers, letters, and special characters.
I tried to replace each of them but it didn't work out.
Any ideas?

Use encodeURIComponent()
function insertJobDesc (r) {
rowid=r;
var qty = document.getElementById('Qty' + r).value;
var desc = encodeURIComponent(document.getElementById('Desc' + r).value);
sendAsync("editDatabase.php?sql=UPDATE+jobdesc+SET+qty="+qty+",+description='"+desc+"',+rowID="+rowid+"+WHERE+id="+rowid+"+AND+jobID="+jobID);
}
Disclaimer: Don't ever do anything like this...

Related

JS: how to filter table using variable

I have a function that I need to use for filtering table rows:
setFilterString("Filter");
But I have a problem. I can set it to
setFilterString("OrderID = 5");
and it will filter out row where OrderID is equal to 5 but if i try using a variable that has a value taken before like this
setFilterString("OrderID = vOrderID");
I get error "Invalid column name 'vOrderID'." (as vOrderID is variable and not a column, I guess)
I have seen somewhere in filter section inputting something like this ("OrderID = '" & vOrderID & "'") but it doesn't have any result at all for me. Doesn't even throw any error in the console.
JavaScript assumes you are just passing a string to the function. If you want to use the variable, you should try this:
setFilterString("OrderID = '" + vOrderID + "'"); // Results in OrderID = '5'
or
setFilterString("OrderID = " + vOrderID); // Results in OrderID = 5
depending on the body of your function.
Use + instead of &: setFilterString("OrderID = " + vOrderID) should work.
Use "+" for merge strings:
setFilterString("OrderID = " + vOrderID)
You can also try to use ${idvOrderID} inside string:
setFilterString("OrderID = ${vOrderID}")
Or:
setFilterString(sprintf("OrderID = %s", vOrderID))
Remember about difference between ' and "

In javascript, spliting a string with order preserving

hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
In javascript, how do i split the above string("hosts") string like the following :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]"
tried this :
var hosts, newhosts;
var ip6_hosts = [];
var ip6_re = /#\[(.*?)\]/g;
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]";
while ((match=ip6_re.exec(hosts)) != null)
ip6_hosts.push(match[0]);
non_ip6_hosts=hosts.replace(ip6_re, '').replace(/:+/g, ':');
newhosts=ip6_hosts.concat(non_ip6_hosts.split(':'));
actual output :
newhosts=#[2001:db8:1/64],#[::2/24],.uk.com,hostname,#10.10.10.10/10,#11.11.11.11/11
expected output :
newhosts=.uk.com,hostname,#10.10.10.10/10,#[2001:db8:1/64],#11.11.11.11/11,#[::2/24]
but not sure how to preserve the order. is there any way to achieve an expected output ?
You could try:
var openbracket=0;
for (i=0; i<hosts.length; i++)
{
if (hosts.substr(i,1) == '[') openbracket=openbracket+1;
if (hosts.substr(i,1) == ']') openbracket=openbracket-1;
if ((hosts.substr(i,1) == ':') && openbracket==0)
{
hosts = hosts.substr(0,i) + ',' + hosts.substr(i+1,hosts.length-i-1);
}
}
seems to work for me, though I'm not sure if there's a better method for changing the value of hosts. All it needs to do is insert the ',' at the location i. The above code adds everything to the left of the ':', a ',', and everything to the right of the ':'.
note: this assumes you don't want any ':' inside of brackets changed to a comma.
hope this helps.
Can't You just say:
host = host.replace(/:+/, ',');
whenever you want to change it?
I feel like this is too simple of an answer, comment if I'm not getting it.
The following should work:
hosts.replace(/([^:]{1})\:{1}([^:]{1})/g, '$1,$2')
Try this.
var hosts='.uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]';
hosts = hosts.replace(/:#/g, ':##');
hosts = hosts.split(':#');
var hostDetails = hosts[0].split(':');
var newHost = hostDetails.concat(hosts.splice(1, hosts.length));
console.log(newHost);
Can you try this...
String.prototype.replaceAt=function(index, character) {
return this.substr(0, index) + character + this.substr(index+character.length);
}
hosts=".uk.com:hostname:#10.10.10.10/10:#[2001:db8:1/64]:#11.11.11.11/11:#[::2/24]"
hosts = hosts.split(':#').join(',#');
var re = /:\w/g;
var found = hosts.match(re);
hosts.replaceAt(found.index,',');

How to use IN with a query parameter?

I have a query like this.
SELECT * FROM player_details where name in ('messi','neymar','suarez','alves')
I want to execute this query in titanium.
I tried like this
var in = ['messi','neymar','suarez','alves'];
db.execute('SELECT * FROM player_details where name in ?',in);
But above code producing error.
How can i add IN and NOT IN condition in sqlite in titanium ?
A single parameter ? replaces a single expression.
When you have four values, you need four parameters:
db.execute('SELECT * FROM player_details where name in (?,?,?,?)', in);
If the length of the array is dynamic try something like this:
var params = ["messi", "neymar", "suarez", "alves"],
qMarks = new Array(params.length).join("?,") + "?";
db.execute("SELECT * FROM player_details WHERE name in (" + qMarks + ");", params);

jQuery .each with Smarty variable in .tpl

I have a page with the following html that appears numerous times with different phone numbers:
<div class="crm-content crm-contact_phone primary">
<span>5555551212</span>
</div>
The phone number itself is displayed using a smarty variable in the form {$phone.i.phone}, where i is the array key in an array of phone numbers.
I want to be able to change the format of these phone numbers using js.
So for just one phone number, I was using the following in my smarty .tpl file:
{literal}
cj(function($){
var phoneNumber = {/literal}{$phone.1.phone}{literal};
var phoneNumberFormatted = '(' + phoneNumber.substr(0,3) + ') ' + phoneNumber.substr(3,3) + '-' + phoneNumber.substr(6);
$(".crm-contact_phone span").text(phoneNumberFormatted);
});
{/literal}
So I figure, I need to do something along the lines of:
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone.1.phone}{literal};
}
but I have no idea how to replace the 1 inside the smarty variable, with the javascript index i.
Any ideas? Thanks.
Try this
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone[i].phone}{literal};
}
Use the bracket Notation and replace it with i .
I took a different approach in the end, saving the entire smarty array to a js array using the following:
var phoneNumbers = {/literal}{$phone|#json_encode}{literal};
I could then just access the phone number by using pure js:
var phoneNumber = phoneNumbers[i]['phone'];

How do I simplify this repetitive jquery code?

I made a jQuery script that works fine, I'd just like to see if anyone had tips on simplifying it, in particular the beginning part in which variables are defined.
Though I'm really interested in straight code simplification, here's a quick synopsis on what the script actually does:
Looks for links with a class of 'tour' and defines 3 more variations of its href attribute (swapping out a 4-digit number).
Replaces links with a class of 'tour' with different content that substitutes in the additional 4-digit values.
With a.tour replaced, visibility of part of the content is toggled on hover.
And here's the code:
HTML:
Link
JQUERY:
<script>
$(document).ready(function() {
var aud = $('.tour').attr('href');
var usd = $('.tour').attr('href').replace(7838,'8062');
var gbp = $('.tour').attr('href').replace(7838,'8907');
var eur = $('.tour').attr('href').replace(7838,'8914');
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});
</script>
Don't keep using $(".tour") over and over, it is both neater and more efficient to define a variable equal to it. Also, you don't need to keep checking the .attr("href") because once you've stored that value in aud you can use that:
var $tour = $(".tour"),
aud = $tour.attr('href'),
usd = aud.replace(7838,'8062'),
gbp = aud.replace(7838,'8907'),
eur = aud.replace(7838,'8914');
$tour.replaceWith(...);
Note that your code will update (replace) all .tour links using the aud, usd, etc. values from the first .tour link. Is that what you intend, or should it update them individually?
well for starters you could have the following:
var $aud = $('.tour').attr('href'),
$usd = $aud.replace(7838,'8062'),
$gbp = $aud.replace(7838,'8907'),
$eur = $aud.replace(7838,'8914');
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var usd = treplace('8062');
var gbp = treplace('8907');
var eur = treplace('8914');
Even better, you can do something like this if you want lots of currencies
var abbrev=["USD","GBP","EUR"]
var codes=[8062,8907,8924]
var names=["US Dollar","British Pounds","Aussie Dollar"]
var treplace=function(with){ $('.tour').attr('href').replace(7838,with);};
var s='<div class="currency"><p>Price & Bookings</p><ul>';
for(i in abbrev){
//build the rest of the HTML here, using the arrays
}
s+='</ul></div>'
$('.tour').replaceWith(s)
You could also use a 2D array or a custom object instead of three arrays.
2 suggestions:
1: write a function for url transformation
such as
function currencyExchange(srcUrl){
return srcUrl.substring(0,preLength) + rate * Number(src.substring(preLength));
}
2: using javascript template technique to simply the new element construction.
This is not shorter but definitely more optimized and more extensible. Untested:
var href = $('.tour').attr('href'),
items = '',
currency = {
aud : {
name : 'Australian Dollar',
value : 1
},
usd : {
name : 'United States Dollar',
value : 1.05
},
eur : {
name : 'Euros',
value : 0.8
},
gbp : {
name : 'British Pounds',
value : 0.67
}
}
for (var c in currency) {
var num = href.match(/\d+/), // Simple regex, maybe too simple...
conv = Math.ceil(currency[c].value * num),
url = href.replace(num, conv);
items += '<li>' +
'<a href="' + url + '">' +
currency[c].name + ' (' + c.toUpperCase() + ')' +
'</a>' +
'</li>';
}
$('.tour').replaceWith('<div><ul>' + items + '</ul></div>');
$(document).ready(function() {
var ref = $('.tour').attr('href');
function G(t) {return ref.replace(7838, t=='eur'?'8914':t=='usd'?'8062':t=='gbp'?'8907':'7838');}
$('.tour').replaceWith('<div class="currency"><p>Price & Bookings</p><ul class="currencydd" style="display:none"><li>Australian Dollar (AUD)</li><li>United States Dollar (USD)</li><li>British Pounds (GBP)</li><li>Euros (EUR)</li></ul></div>');
$('.currency').hover(function () {
$('.currencydd').slideToggle("fast");
});
});​
FIDDLE

Categories