Passing long string in javascript argument - php

I have a php page which i have array of values with long values.
I gave to pass this array in a javascript function like this
$canswer is an array
I am imploding that and passing as arguments as follows,
$cans=implode(',',$canswer);
echo "<input type='checkbox' name='q1' id='1' onclick=\"save_answer('1','$cans')\">";
This code is working for short values in array.When I have long values in array,onclick is not working.When I tried to see view source,I saw the array values cut off in the page.
I have tried the following code to give quotes for each values.But this also not works.
$correctanswer1="'" . implode("','", $correctanswer) . "'";echo $correctanswer1;
Regards,
Rekha

You could save the array of values as a javascript string on the page, then call the string in the onclick attribute.
<script type="text/javascript">
cans_string = '<?php echo implode(',',$canswer); ?>';
</script>
<input type="checkbox" name="q1" id="1" onclick="save_answer('1',cans_string)">

explore the array before to add it as parameter (print_r?)
extract javascript function into an javascript file
use jason to pass array as a parameter
Hope this will solve the problem

You're probably not escaping some of the special characters in your output. Run your output through htmlentities or htmlspecialchars to eliminate characters that will break your HTML or javascript.
$cans=htmlentities(implode(',',$canswer), ENT_QUOTES);
echo "<input type='checkbox' name='q1' id='1' onclick=\"save_answer('1','$cans')\">";
Pay attention to where your output is breaking, and what characters could be breaking it.

Related

ajax jquery passing string as a parameter in onclick event jquery

echo "<button onClick='follow(".$name.");'></button>";
I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.
I tried kind of everything, but in php it looks a bit of a big deal for me. Is there any other way around to get the expected result as a string from a php variable.
You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.
Just add escaped quotes like this:
echo "<button onClick='follow(\"".$name."\");'></button>";
Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.
There is various ways to do it, for standard " in html properties:
echo '<button onClick="follow(\''.$name.'\')"></button>';
echo "<button onClick=\"follow('".$name."')\"></button>";
echo "<button onClick=\"follow('$name')\"></button>";
for single quotes
echo '<button onClick=\'follow("'.$name.'")\'></button>';
echo "<button onClick='follow(\"".$name."\")'></button>";
echo "<button onClick='follow(\"$name\")'></button>";
But that's presuming your users are nice, a crafty user may create a username with \n in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:
<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>';
Rendering the following which would cause the page to break:
<button onClick="follow('Foo
Bar')"></button>
Or worse a username like:
$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";
Which would render a stored XSS:
<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>
So a better solution then to directly pass it in, would be to escape it, using htmlentities and json_encode so \n is not rendered by the html.
echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';
Which would render to:
<button onClick='follow("Foo')"><\/button>\n<button onClick="window.location.href = ('http:\/\/example.com")'></button>
Though you should be validating usernames on create before allowing such an attack.

php echo outputs only part of a variable in a form

I'm loading a variable from a database like:
$adres = $row['adres']; //(= "Hoge Filterweg")
Then using it in a echo like:
echo input type='text' name='adres' value='{$adres}'
It displays on the form only the first part of the adress ( "Hoge"), but not the whole adress.
What could I do now?
Single quotes surrounding the inline variable like value='{$adres}' dit the trick.
thanks
You need double quotes to pass params with space.
This code should help you:
echo "<input type=\"text\" name=\"adres\" value=\"{$adres}\" />"

How can I echo an array in an html input text value attribute

I have the following scenario:
I have a PHP array which has tags on it, they can be between 4 and 7.
And I need to put that PHP Array in an input type text separated by commas on the value attribute. Any idea how can I do this?
The input text is a plugin for tags, which is http://timschlechter.github.io/bootstrap-tagsinput/examples/bootstrap3/
Any help would be appreciated!
This is my PHP code:
while($dataTagsToPut = $resultTags->fetch_assoc()){
array_push($stringTags, $dataTagsToPut['SOLUTION_TAGS_NAME']);
}
This is my HTML:
<input type="text" id="solutionTags" value="<?php echo htmlspecialchars(??whatgoeshere); ?>" name="solutionTags">
One simple way:
echo implode(',', array_map('htmlspecialchars', $stringTags));
array_map applies a function to each element and gives you the results from each call. Then you can implode the array to turn it into a string.
Should also work the other way around in this case (implode the array, then call htmlspecialchars on the resulting string), since , isn't special in HTML.
Try this:
<?php echo htmlspecialchars(implode($stringTags)); ?>
Implode the array. implode(',', $stringTags)

Passing PHP array using json_encode method into external Javascript function gives result as 'undefined'

I have searched for that, i got some ideas from following site also.
Passing PHP array into external Javascript function as array
My sample code is below:
<?php $array_sample = array("c1","c2"); $newArray = json_encode($array_sample); ?>
<INPUT type="button" value="Php Array" onclick="Test(<?php echo $newArray ?>)" />
<script language="javascript"> function Test(test_arr){ alert(test_arr); }</script>
For above code, I am getting undefined as alert message.
Any Help would be appreciated.
When you use json_encode(), double-quotes are preserved in the result. So, json_encode($array_sample) produces:
["c1","c2"]
When this is put into your HTML, you have:
<INPUT type="button" value="Php Array" onclick="Test(["c1","c2"])" />
If you can tell, the double-quotes from your json-output break the HTML which break what's passed to the Test() method.
To fix this, you could use htmlentities() to convert the double-quotes to HTML-values ":
<INPUT type="button" value="Php Array" onclick="Test(<?php echo htmlentities($newArray) ?>)" />
EDIT (htmlentities() vs. addslashes())
It appears that using addslashes() actually won't work because an escaped double-quote in an attribute, such as onclick="Test(\"value\")" is invalid. However, an html-entity version such as onclick="Test("value")" works.
Because of this, I have changed my original answer from "use addslashes()" to "use htmlentities()").

Parameters in Javascript using jquery

I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />

Categories