0

I work on MySQL PHP

while($row = mysqli_fetch_array($result))
 {
  echo "<a href=javascript:click('$row[Name]')>".$row['Name']."</a>";
  echo "<br><br><br>";
 }

But in result:

<a href="javascript:click('Slow" cooker="" pepper="" steak')="">Slow Cooker Pepper Steak</a>

javascript

clikc(name)
{
alert("test");
}

what is error.

3 Answers 3

1

You need to quote your href value and you should encode the data for the medium you are outputting to in case your data contains characters that might break your html or javascript.

So you could use something like:

echo "<a href=\"javascript:click(" . htmlspecialchars(json_encode($row['Name']))) . ");\">"
     . htmlspecialchars($row['Name']) . "</a>";
Sign up to request clarification or add additional context in comments.

4 Comments

Remove the quotes inside the click parentheses if you're using json_encode
That said, json_encode will use double-quotes, which will just give the same problem again. You also need to htmlspecialchars the json_encode.
@Kolink Thanks for reminding me why I never write javascript like this.
Hehe, no problem. Personally I'd prefer putting the value in a data-* attribute and accessing it with this.getAttribute... but that won't work for a javascript: href due to this referring to the window. Joy!
0

Something wrong with your concatenation. Try this:

 echo "<a href=javascript:click('".$row['Name']."')>".$row['Name']."</a>";

And clikc(name) must be click(name).

1 Comment

@NiceMan what is the result now ?
0

If you plan to use vars like this, you should escape them

version 1:

echo "<a href=\"javascript:click('".addslashes($row['Name'])."');\">".$row['Name']."</a>";

version 2,cleaner:

$value = addslashes($row['Name']);
echo <<<EOD
<a href="#" onclick="click('{$value}');return false;">{$row['Name']}</a>
EOD;

version 3,clean js also:

a) php:

$value = addslashes($row['Name']);
echo <<<EOD
<a href="#" class='js-clicky' data-value="{$value}">{$row['Name']}</a>
EOD;

b) html, using jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$('.js-clicky').click(function(){
    alert($(this).data('value');
})
</script>

Read here about :

heredoc: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

addslashes: http://php.net/manual/en/function.addslashes.php

jquery : http://jquery.com/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.