user188962
user188962

Reputation:

why cant I pass this variable to the javascript function?

I have a variable inside my php file, which I want to pass to a javascript function whenever the user clicks a link on my php page.

here is the php in brief:

$delete_img=$image_id.'_'.$newfilename;
$display_image.="<td><img src='../temp_images/$newfilename'>";
if ($i==$extra_pic){ 
$display_image.="<br><a href='#' onclick='window.parent.reset_imageform($i, $delete_img);'>delete picture</a></td>";}

the "if($i==$extra_pic) is TRUE so dont mind that...

The problem is, if you click on the link 'delete picture' the function reset_imageform(nr, pic_nr) should get called, but it doesn't whenever I try to pass the variable $delete_img to the function. As soon as I remove this variable from the call like this 'reset_imageform($i);' then it works. but adding that variable, will make it not to work. The function doesnt get called at all!

The variable contains a random id nr, with an underscore, and then a filename, for example like this: 23432423439_picture.jpg

is there something Im missing here, should I do something to $delete_img before sending it in php?

All my documents are in utf-8 format!

Thanks

PS: just let me know if you need more input...

Upvotes: 1

Views: 249

Answers (3)

Greg
Greg

Reputation: 321578

As it's a string you'll need to quote it.

The proper way is like this:

$display_image.='<br><a href="#" onclick="window.parent.reset_imageform(' . $i . ', '
    . htmlspecialchars(json_encode($delete_img))
    . ');">delete picture</a></td>';

I've swapped the quotes around to make it work for any string; otherwise if you used it somewhere else and the string contained an apostrophe it wouldn't work. The alternative do swapping the quotes would be to pass ENT_QUOTES to htmlspecialchars().

You says that $i on it's own works, so I'm assuming $i is an integer - therefore it doesn't need quoting.

Upvotes: 5

BalusC
BalusC

Reputation: 1108632

When having problems with Javascript, do not look at the server side code which generates it, but look at the final output (rightclick page in webbrowser and choose 'view source' or so) and concentrate on the generated JS code only. This way you should have spotted the missing quotes around the JS string variable much sooner.

Upvotes: 3

artlung
artlung

Reputation: 34013

If you're passing a string to a JavaScript function, it must be properly quoted:

So without php, it looks like:

<br><a href='#'
  onclick='window.parent.reset_imageform(5, "23432423439_picture.jpg");'>
    delete picture</a></td>

So to get that resulting HTML, you need to include quotes:

$display_image.="<br><a href='#'
  onclick='window.parent.reset_imageform({$i}, \"{$delete_img}\");'>
    delete picture</a></td>";

We have multiple levels of quotes here, so the double quotes around 23432423439_picture.jpg need to be escaped, like \"

Upvotes: 3

Related Questions