Pass PHP array to Javascript via onClick using JSON - php

I am using PHP and MySQL to loop through products and generating HTML code that consists of an img tag with an onClick event that calls a Javascript function. I want to pass PHP variables via the onClick event to a Javascript function. I'm using jQuery and thought it would be a good idea to use PHP's json_encode() function and jQuery's jquery-json plugin.
My PHP code looks like this:
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a href=\"javascript:;\" onClick=\"changepic('" . htmlentities($onclick) . "')\">";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
As you can see my Javascript function is called changepic(). I've left out a bit of code that is irrelevant to this question (i.e. the database access code and deciding where the thumbnail image is).
My Javascript code is:
function changepic(productarray) {
var productid = $.evalJSON(productarray).productid;
var productdesc = $.evalJSON(productarray).description;
alert(productid);
}
I'm not really doing anything yet with the PHP variables that I'm passing to the Javascript array, I'm just trying to get it to work first! My ultimate aim is to use jQuery to insert the product description into a <div>
A sample product detail might look like this:
ProductID: 30c7508008ac7597619ad9b90a97b40f
Description: <p>Wide and Narrow Bands<br>
Set with Top-Quality Diamonds</p><p>
As you can see the description contains HTML code, as well as a newline after the <br> tag.
The HTML that is generated looks like this:
<img src="products/tn-30c7508008ac7597619ad9b90a97b40f.jpg" width="100" height="100">
When I run this I get a Javascript error:
Event thread: click
Uncaught exception: SyntaxError: JSON.parse: Unescaped control char in string: "<p>Wid
Error thrown at line 18, column 2 in changepic(productarray) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
var productid = $.evalJSON(productarray).productid;
called from line 1, column 0 in <anonymous function>(event) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
changepic('{"productid":"30c7508008ac7597619ad9b90a97b40f","description":"<p>Wide and Narrow Bands<br>\r\nSet with Top-Quality Diamonds<\/p>"}')
From what I can see I've done something wrong with encoding the JSON string. I've done some Googling and found some people that say no encoding is necessary (I tried that and the product description was taken as HTML and showed up in the page), others say to use addslashes() and some say htmlentities().
Do I need to do something in the Javascript function to decode it before I try to use it with evalJSON()?

I usually just do this,
var foo = <?php echo json_encode($foo); ?>;
and I don't really see how this can result in any sort of an "injection" attack as long as json_encode is doing its job.

I don't understand why you are getting into so much mess.. here is the solution and it works
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a id='test' href='' var='$onclick'>";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
Here is your jquery:
$(function(){
$("#test").click(function(){
var img = jQuery.parseJSON(($(this).attr("var")));
alert(img.description);
});
});
Now since you have the json object you can create div tag and put the variables inside or put the content on already existing div tag. I am sure you know what to do here.
Dins

I think I was over-complicating things, I didn't really need to use JSON at all.
I got this working by changing my PHP code to this:
$productid = $productsRow['ProductID']
$description = rawurlencode($productsRow['Description']);
echo "<a href=\"javascript:;\" onClick=\"changepic('$productid','$description')\">";
Then my Javascript looks like this:
function changepic(productid, description) {
description = decodeURIComponent(description);
alert(description);
}
This works fine so now I can continue and actually do something useful in the Javascript function.

Related

how to give quotes in php for html attributes

echo "<tr onclick='window.location=("www.google.com")'>
<td>something</td>
<td>something</td>
</tr>"
i have written code like this but it is not working.i dont know where to put single quotes and double qoutes.
I dont know how to write onclick for in php
please suggest me
Avoid using echo for HTML. Leave PHP mode and go into output mode.
Avoid using nested literal values. Write each language as a separate variable, use suitable escaping functions to add whatever quotes you need and then put them together.
By keeping everything as separate layers and dealing with them one at a time, and by using functions instead of trying to write your escapes manually, you make things much easier to maintain.
$url = "http://www.google.com";
$js_string_literal_url = json_encode($url);
$js = "window.location = $js_string_literal_url";
$html_safe_js = htmlspecialchars($js);
?>
<tr onclick="<?php echo $html_safe_js; ?>">
<td>something</td>
<td>something</td>
</tr>
That said, you should also avoid:
Features which depend entirely on JS
onclick attributes
Write HTML that works, and then enhance with JS.
If you want to link somewhere: use a link:
<tr>
<td>something</td>
<td>something</td>
</tr>
If you want to make that link work (using JS) for the whole table row, bind an event listener that looks for clicks, and then find the first link in the row that was clicked on.
document.querySelector("table").addEventListener(follow_link_in_row);
function follow_link_in_row(event) {
var table_row = event.target;
while (table_row && table_row.tagName.toLowerCase() !== "tr") {
table_row = table_row.parentNode;
}
if (!table_row) { return; }
var link = table_row.querySelector("a[href]");
var url = link.href;
window.location = url;
}

Passing variable through function Javascript / PHP

i want to pass a variable through to a php on an onClick event, it doesn't seem to be passing it through to the page properly though.
Here's my html
<a href="data.php" onClick="video(We Have a Pope)" hidefocus="">
and the relevant javascript function
function video(result) {
$('#information').load('data.php?result=' + result);
document
}
My php page looks like this
<?php
$result = $_GET['result'];
echo $result;
?>
Nothing is being outputted though :S
onClick="video(We Have a Pope)" should be onClick="video('We Have a Pope')"
You need quotation marks when you pass string as parameter, like this:
<a href="data.php" onClick="video('We Have a Pope')" hidefocus="">
<a href="data.php" onClick="javascript:video('We Have a Pope');" hidefocus="">
onClick="video('We Have a Pope');"
or
onClick="video(\"We Have a Pope\");"

How should I escape?

its a simple logger function. I want to load an array to a DIV content:
document.getElementById('layout').innerHTML = '<?php foreach ($logs as $item) { echo str_replace(array('"',"'"), array ('"','''), $item).'<hr />'; } ?>';
because $logs can contain HTML elements, but not quotes, since they would ruin the echoing. It should be OK, but Firefox say "malformed Unicode character sequence" and it doesnt displayed. Now what?
use html entities to translate your html code into safe sequencies
I might be wrong, but it looks like you're trying to enter php code into your page using javascript. Javascript is client side, so if anything, you will get the full code, not the parsed code.
If you want the php to be run beforehand, so the actual code in your page will be a javascript that has the allready-parsed contents in it, you neet to make a string that contains the finished content AND add "'" for javascript to understand it.
This might look like this (haven't checked the foreach for you)
<?//this part is parsed before sending it to the client
$conts = "'";
foreach ($logs as $item) {
$conts .= str_replace(array('"',"'"), array ('"','''), $item);
$conts .= "<hr/>";
}
$conts .= "'";
?>
document.getElementById('layout').innerHTML = <? echo $conts ?>;

Go Link thru iFrame

I have problem and I tried click link then it doesn't work to open link using target: name of iFrame. i dont want use href because im going make show/hide div.
Javascript:
<script type="text/javascript">
<!--//
function godirect(url, targetname)
{
document.getElementById(targetname).src = url;
//frame[targetname].location.href = url;
}
//-->
</script>
in HTML and PHP:
$a=0;
echo 'Click Me!';
echo '<iframe class="iframe_url" id="iframe_url'.$a.'"></iframe>';
How about
<script type="text/javascript">
function godirect(url, targetname) {
window.frames[targetname].location = url;
//OR
//window.open(url,targetname);
return false;
}
</script>
<?PHP
$a=0;
?>
Click Me!
<iframe class="iframe_url" name="iframe_url<? echo $a; ?>" id="iframe_url<? echo $a; ?>"></iframe>
You have to quote strings in JavaScript. You are trying to get the id of the element by passing in a variable which you haven't defined.
You are also using the same quote characters to delimit your HTML attribute value as you are using to delimit your JS strings.
To use the approach you are using, while making the minimum number of fixes to make it work:
echo 'Click Me!';
Using JS for this is a very silly idea in the first place though, and your implementation fails to have any kind of fallback for when JS is not available (which is odd, since you are taking steps to stop browsers which don't recognise the script element from rendering the JS as content text).
You can do this with plain HTML:
<a href="http://www.google.com"
target="iframe_url<?php echo htmlspecialchars($a); ?>">
Click Me!
</a>
i dont want use href because im going make show/hide div.
You can do that as well as having a normal, functioning link. Build on things that work.
Try this:
echo 'Click Me!';
echo '<iframe class=\"iframe_url\" id=\"iframe_url'.$a.'\"></iframe>';

Changing Text in PHP

I haven't found anytihng in Google or the PHP manual, believe it or not. I would've thought there would be a string operation for something like this, maybe there is and I'm just uber blind today...
I have a php page, and when the button gets clicked, I would like to change a string of text on that page with something else.
So I was wondering if I could set the id="" attrib of the <p> to id="something" and then in my php code do something like this:
<?php
$something = "this will replace existing text in the something paragraph...";
?>
Can somebody please point me in the right direction? As the above did not work.
Thank you :)
UPDATE
I was able to get it working using the following sample:
Place this code above the <html> tag:
<?php
$existing = "default message here";
$something = "message displayed if form filled out.";
$ne = $_REQUEST["name"];
if ($ne == null) {
$output = $existing;
} else {
$output = $something;
}
?>
And place the following where ever your message is to be displayed:
<?php echo $output ?>
As far as I can get from your very fuzzy question, usually you don't need string manipulation if you have source data - you just substitute one data with another, this way:
<?php
$existing = "existing text";
$something = "this will replace existing text in the something paragraph...";
if (empty($_GET['button'])) {
$output = $existing;
} else {
$output = $something;
}
?>
<html>
<and stuff>
<p><?php echo $output ?></p>
</html>
but why not to ask a question bringing a real example of what you need? instead of foggy explanations in terms you aren't good with?
If you want to change the content of the paragraph without reloading the page you will need to use JavaScript. Give the paragraph an id.<p id='something'>Some text here</p> and then use innerHTML to replace it's contents. document.getElementById('something').innerHTML='Some new text'.
If you are reloading the page then you can use PHP. One way would be to put a marker in the HTML and then use str_replace() to insert the new text. eg <p><!-- marker --></p> in the HTML and $html_string = str_replace('<!-- marker -->', 'New Text', $html_string) assuming $html_string contains the HTML to output.
If you are looking for string manipulation and conversion you can simply use the str_replace function in php.
Please check this: str_replace()
If you're using a form (which I'm assuming you do) just check if the variable is set (check the $_POST array) and use a conditional statement. If the condition is false then display the default text, otherwise display something else.

Categories