0

as the title already says I am calling a onclick method in php, but every string with a space in it seems to fail.

php (mysql loop)

echo '<img onclick=test("'.$row['name'].'","name'.$row['id'].'") src="blabla.png"/>';

javascript

function test(vali, id){

   alert(vali); //Maria, Josef (but not "Michael Jackson")
   alert(id); //name23, name28
}

As I said if its a string without a space, alert method is getting called and shows the text, however with at least one space nothing happens.

2
  • echo '<img onclick="test('.$row['name'].', name'.$row['id'].')" src="blabla.png"/>'; ? Commented Feb 2, 2017 at 13:11
  • @DevNiels prob mainly because name'.$row['id'].' is one value so I have to put it in "" else javascript wont know the id is for example "name12" Commented Feb 2, 2017 at 13:14

2 Answers 2

1

Your whole onclick handler needs to be quoted. You then need to also HTML-escape the quotes inside it.

echo '<img onclick="test(&quot;'.$row['name'].'&quot;,&quot;name'.$row['id'].'&quot;)" src="blabla.png"/>';

In the HTML this will then appear as

<img onclick="test(&quot;A Name With Spaces&quot;,&quot;name1&quot;)" src="blabla.png"/>

And the javascript part is ultimately decoded to

test("A Name With Spaces","name1")
Sign up to request clarification or add additional context in comments.

3 Comments

ur genius ty :)
and how would u do this in javascript :)? .innerHTML="<img onclick=test2('"+vali+"','"+id+"') />"; cause if I replace the single quotes with &quote; it doesnt seem to work for me :/
In Javascript you quote using backslash, ie: \" but you're still not wrapping the onclick handler and really should avoid innerHTML in favour of more modern methods like var img = new Image(); img.addEventListener('click', someFunction); someElement.appendChild(img)
0

You can use it like below

<img onclick='test("<?php echo $row['name']; ?>",name="<?php echo $row['id']; ?>")' src="blabla.png"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.