0

can i send a php variable to my javascript function using onclick event of a link like this

<a onclick="change(<?php echo $description ?>)">

when I echo the description it is available but when I send it to my javascript function it says undefined

How can I do this ?

Thanks

3
  • Use a JSON encoding routine to encode the description. That'll add quotes and check for embedded quotes. Commented Mar 23, 2012 at 13:24
  • <?php echo json_encode($description); ?> Commented Mar 23, 2012 at 13:24
  • not working :( i get an empty alet inside my javascript function Commented Mar 23, 2012 at 13:29

2 Answers 2

3

$description is probably a string, so you need quotes around it in your Javascript:

<a onclick="change('<?php echo $description ?>')">
Sign up to request clarification or add additional context in comments.

6 Comments

Also take a look at "Unobtrusive Javascript". It is better to separate your Javascript from your HTML
Since we can't see your output, "not working" is not enough information for us to provide useful answers. Please update your question or your comment to provide full details: what do you expect to happen, what you tried (exactly), and what really happened (errors, etc).
I have just a javascript function change function change(desc) alert(desc) nothing else in javascript
Do <?php var_dump($description); ?> and tell us what it says
@George Cummins It is not showing me the alert in which i want to display the description. when I use hardcoded string it shows the alert... I think there is some problem in the data that comes from the database... It contains some html tags when it comes from database can I remove all the tags first and then pass the string only ?
|
0

you can easily do this in jquery.. if you're interested in using another library such as jquery..

Js

var description;
$('#description').click(function(){
  description = $(this).val();
  //alternatively you can use data-description and retrieve it like so:
  description = $(this).data('description');
  //if that doesnt work use attr();
  description = $(this).attr('data-description');
  //this will return "My awesome description"
  console.log(description);
}

php

<?php 
$description = 'My awesome description';
?>

html

<a id="description" href="#"><?= $description; ?></a>
<!-- alternatively you could used data-description attribute on the href and pass that.. -->
<a href="#" data-description="<?= $description; ?>">Link 1</a>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.