Jefferson Jefferson - 4 months ago 16
jQuery Question

How to pass comma separated Php dynamic params in javascript onclick function

How to pass comma separated Php dynamic params in javascript onclick function. Can anybody help me with the correct fix? The following does not workout.

echo "<td><a href='#' onclick='editUser(". $row['pub_name'] .",". $row['name'] .",". $row['email_id'] .")'>Edit</a></td>";


JavaScript:

function editUser(id, pm, email) {
alert(id);
alert(pm);
alert(email);
}

Answer

Assuming the values are strings, you need to put quotes around them:

echo "<td><a href='#' onclick='editUser(\"". $row['pub_name'] ."\",\"". $row['name'] ."\",\"". $row['email_id'] ."\")'>Edit</a></td>";

Also note that it's considered much better practice to use unobtrusive JS code to attach your event handlers, over the outdated on* event attributes. As you've tagged jQuery you could to this:

echo '<td><a href="#" data-pubname="'.$row['pub_name'].'" data-name="'.$row['name'].'" data-emailid="'.$row['email_id'].'">Edit</a></td>';
$('td a').click(function(e) { // change selector as appropriate here
    e.preventDefault();
    var $el = $(this);
    console.log($el.data('pubname'));
    console.log($el.data('name'));
    console.log($el.data('emailid'));
});