CakePHP: Escape single quotes within an implode function delimited with commas - php

I have a routine in my controller that retrieves the values from a single database column and builds a quoted array out of them:
$suppliers=$this->Model->find('list',array('fields'=>array('Model.supplier', 'Model.supplier')));
$strSuppliers="'".implode("','", $suppliers)."'";
$this->set('suppliers', $strSuppliers);
$strSuppliers is then fed to a jQuery script that creates an auto-complete dropdown list in the "suppliers" field in my Edit view:
<script>
$(function() {
var availableTags = [<?php echo $suppliers ?>];
$( "#MsrSupplier" ).autocomplete({
source: availableTags
});
});
</script>
The output of the variable is something like 'Tom', 'Dick', 'Harry', etc.
This works fine, unless any of the retrieved values contain single quotes. 'Tom's', 'Dick', 'Harry' breaks the array, and I'm having difficulty understanding how to escape the single quotes so that my dropdown will continue to function when they're present. I've tried changing the delimiter and swapping single quotes for double quotes, like so:
$strSuppliers='"'.implode("','", $suppliers).'"';
But that didn't work. What else might I try here?

Check out json_encode() for PHP to output a JSON string, and then look at JSON.parse() for use in your jQuery.
Instead of using implode() to generate your string, use json_encode() and then have JSON.parse() decode that for use in whatever application you need.
Edit: Added some code for clarity:
$strSuppliers = json_encode($suppliers);
and then in your jQuery:
var jsonStr = '<?php echo $suppliers; ?>';
var availableTags = JSON.parse(jsonStr);
EDIT 2: As ndm pointed out in the comments, you can do this more cleanly by directly assigning the Javascript variable to the output of json_encode():
var availableTags = <?php echo $suppliers; ?>;

Related

Double quote in php json encode

The JSON out of my file is:
[{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":["3","723","19","48","3","6","14","17","15","6"]}]
I require:
[{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":[3,723,19,48,3,6,14,17,15,6}]
JSON required for plotting bar chart in highchart.js.
When I run php query from mysql for json encode it gives the output with double quote.
I guess you want to do this if name = total
Here is the code try it:
var a = [{"name":"ltrs","data":["25","80","110","113","139","1025","1026","1027","1028","1029"]},{"name":"total","data":["3","723","19","48","3","6","14","17","15","6"]}];
$.each(a, function(k,v){
if(v.name == 'total'){
$.each(v.data, function(k1,v1){
v.data[k1] = v1*1;;
});
}
});
console.log(a);

Trying JSON Encoding of Ajax function sending values

I am using a hidden field and appending values with the following function.
$( "#invite_suggestion" ).autocomplete({
source: BASEURL + 'index.php/search_contacts_suggestion/',
select: function( event, ui )
{
$('#invite_id').val($('#invite_id').val()+ui.item.friend_id);
}
});
In the PHP side
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(array($_POST['invite_id'])):json_encode(NULL);
But Actually the final output of this is string ["4565"] and what i actually need is to JSON encode of individual values in field ["45","65"]
seperate the values by a comma in your js:
$('#invite_id').val($('#invite_id').val()+','+ui.item.friend_id);
then explode on the comma in php to create the array:
(isset($_POST['invite_id']))?json_encode(explode(',',$_POST['invite_id'])):json_encode(NULL);
on the PHP side I expect you'll want to do an 'explode' on the $_POST['invide_id'] to get an array of elements. $_POST['BLAH'] will only return a string.
e.g. something like...
$_POST['invite_id']=(isset($_POST['invite_id']))?json_encode(explode($_POST[',', 'invite_id']))):json_encode(NULL);

Getting unexpected newline when inserting JavaScript with PHP

I am trying to insert items into a javascript array for the autocomplete function. I take the values that I need for the array from a database, so I grab them with PHP. Then I just push each item into the javascript array. However, it keeps telling me that I have an "unexpected token ILLEGAL" and it looks like it's pointing at the single "quote" character that gets inserted, then has a newline, then continues to the actual value.
My javascript/PHP
<script type="text/javascript">
$(function() {
var availableTags = [];
<?php
foreach ($modelList as &$model)
echo "availableTags.push('$model');" . "\n";
?>
$("#devicemod").autocomplete({
source: availableTags
});
});
</script>
Then the error message...
$(function() {
var availableTags = [];
availableTags.push('
***Uncaught SyntaxError: Unexpected token ILLEGAL***
ODEL: T]422P');availableTags.push('');availableTags.push('!');availableTags.push('!6.1/120{ MODEL: TM402P');availableTags.push('!A`$');availableTags.push('!DP1110 CREATED ON: JAN 29 2002');availableTags.push('!MODEL: TM402P');
It should turn out to be...
availableTags.push('ODEL:T]422P');
availableTags.push('');
etc...
Using json_encode() you can do this in a single (and safe) step:
<script type="text/javascript">
$(function() {
$("#devicemod").autocomplete({
source: <?php echo json_encode($modelList); ?>
});
});
</script>
The json_encode() function makes sure that the values are properly escaped according to the rules of JavaScript notation. This prevents nasty surprises when the values contain single quotes in this case.
If $modelList is not a true list (i.e. the keys are not numbered sequentially), you should apply array_values() first:
...
source: <?php echo json_encode(array_values($modelList)); ?>
...
This is a bad idea:
echo "availableTags.push('$model');" . "\n";
if $model contains ANY javascript metacharacters, particularly ', you'll introduce syntax errors and kill the entire <script> block. Never directly output arbitrary text into Javascript context - you're basically vulnerable to the JS equivalent of an SQL injection attack.
At bare minimum, you should be using json_encode() to guarantee that your text is syntactically valid for the context you're using it in:
echo 'availableTags.push(' . json_encode($model) . ");\n";
or better yet... why do all this pushing when youd could just generate an array automatically?
<?php
$data = array();
foreach ($modelList as $model) {
$data[] = $model;
}
?>
var availableTags = <?php echo json_encode($data); ?>;

passing PHP string to JavaScript: unterminated string literal

i am assigning PHP var to my javascript var and sending to PHP file through
ajax-jQuery, but my php variable contains newline chars which
i have replaced with <br>
e.g. $values1 = 'abc<br>pqr<br>xyz'; $values2 = 'xyz<br>lmn';
javascript - var data = 'val1=<?php echo $values; ?>&val2=<?php echo $values2; ?>';
and then ajax script to post data to PHP file
but when i print this data on console it is giving me error- SyntaxError: unterminated string literal.
Can anyone help ?
Your JS code:
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Will give Javascript syntax error if one or more of your PHP variables $values1 OR $values2 contain single quote ' in them.
Make sure your PHP variable don't contain single quotes in them by replacing all single quotes to something else otherwise use double quotes " to create JS var like this:
var data = "val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>";
Provided PHP variables don't contain double quotes.
First of all, you have a typo, that might cause an error:
// --------------------------------v
var data = 'val1=<?php echo $values1; ?>&val2=<?php echo $values2; ?>';
Then, I suggest you to use object as data parameter for Ajax request:
var data = {
val1: '<?php echo $values1; ?>',
val2: '<?php echo $values2; ?>'
};
Also it is better to escape single quotes ' in both $values1 and $values2 variables.
Try using <br /> instead of <br>. Just guessing here, no testing.

how to pass array string in JavaScript function from PHP end as a argument?

I am getting the error missing ) after argument list in my Firebug console.
emissing ) after argument http://a8.sphotos.ak.fbcdn.net/hphotos-ak-snc7/s720x720/393131_320846714645076_100001592501599_911297_470580896_n.jpg
My question is how to pass $char_data variable in JavaScript function as a argument
Define php variable:
<?php
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
$div = "graph";
?
Call JavaScript function with define argument
<script>
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
</script>
A function of JavaScript
<script>
function dynamicChartArray(div,chartdata){
var myData = new Array(chartdata);
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
<script>
Rather than creating an array out of a string in javascript, why not just just get the PHP to output it as an array to start with?
Just add an extra set of [] which javascript reads as an array.
$chart_data = "[['NBA',1],['NFL',2],['MLB',3],['NHL',4]]";
then ditch the quotes on the output (which are responsible for causing the error messages)
dynamicChartArray('<?php echo $div;?>', <?php echo $chartdata;?>);
and then myData can just equal chart data (since its already an array)
var myData = chartdata;
'<?php echo $chartdata;?>'
This is going to echo '['NBA',1],['NFL',2],['MLB',3],['NHL',4]'. Note how there are single quotes inside the single quotes.
new Array(chartdata)
This will just make an array, with one element, the string "['NBA',1],['NFL',2],['MLB',3],['NHL',4]".
Try doing dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
This will make chartdata an array of arrays.
Instead of
$chart_data = "['NBA',1],['NFL',2],['MLB',3],['NHL',4]";
Use
$chart_data = "[\"NBA\",1],[\"NFL\",2],[\"MLB\",3],[\"NHL\",4]";
Change your call to this:
dynamicChartArray('<?php echo $div;?>',[<?php echo $chartdata;?>])
And function to this:
function dynamicChartArray(div,chartdata){
var myData = chartdata;
var myChart = new JSChart(div, 'pie');
alert(chartdata+div);
}
change this:
dynamicChartArray('<?php echo $div;?>','<?php echo $chartdata;?>')
to this:
dynamicChartArray('<?php echo $div;?>', [<?php echo $chart_data;?>]);
and see if it works
You dont need var myData = new Array(chartdata);.
chartdata is already an array.
Take a look at json_encode.
$chart_data = json_encode(array(array('NBA',1),array('NFL',2)));
which will produce a json string ready to echo into your script
string(21) "[["NBA",1],["NFL",2]]"
You should have a look at the output. I bet it is:
dynamicChartArray('graph','['NBA',1],['NFL',2],['MLB',3],['NHL',4]')
and you can already see that you have problems with the quotes.
Instead of creating a string, I suggest to create an array and use json_encode:
$chart_data = array(
array('NBA',1),
array('NFL',2),
array('MLB',3),
array('NHL',4)
);
and
dynamicChartArray('<?php echo $div;?>', <?php echo json_encode($chartdata); ?>)
JSON happens to be valid JavaScript as well and it gives you more possibilities to process the data on the server side.

Categories