I'm passing PHP variable value like this:

<input type="button" name="delete" value="Remove" onclick="del(<?echo $arr1[0]?>);"/>

del() is a Javascript function and Eg:$arr1[0]=234-675-90 the value of $arr1[0] is obtained from MYSQL database and its data-type in mysql is varchar.

I'm fetching value using mysql_query.

The problem I'm facing is that when value is passed to JavaScript function it takes it wrongly(eg:instead of 234-675-99 as -876).Is there any casting is to be done to pass value from PHP to JavaScript?

Any help is greatly appreciated.

share|improve this question

62% accept rate
feedback

2 Answers

up vote 4 down vote accepted

You should pass the value as string:

<input type="button" name="delete" value="Remove" onclick="del('<?echo $arr1[0]?>');"/>
share|improve this answer
1  
Why do that manually and possibly break if the string contains quotes when you can let json_encode() do it for you in a way that never breaks? – ThiefMaster May 11 at 7:04
Naturally, that depends on the data format. What's been given in the question is a simple digits-and-dashes string id. – Alexander Pavlov May 11 at 7:06
On a side-note, json_encode() will break the code in this particular case, since the string will be escaped using double-quotes ("), while apostrophes (') should be used here instead. The HTML will be broken otherwise. – Alexander Pavlov May 11 at 9:45
Do I need to install any package to use json_encode()?Because I tried earlier with json_encode but the call to javascript function did not happen. – user725719 May 11 at 9:50
That is exactly what I said in the previous comment: json_encode() will break your HTML, since you cannot have double-quotes inside a double-quoted attribute value. To avoid the breakage while still using json_encode(), you need to use apostrophes around the onclick value. Using ThiefMaster's solution, ... onclick='del(<?=htmlspecialchars(json_encode($arr1[0]))?>);'... – Alexander Pavlov May 11 at 9:54
show 4 more comments
feedback

Use json_encode() to convert the value into value JavaScript:

<input type="button" name="delete" value="Remove" onclick="del(<?=htmlspecialchars(json_encode($arr1[0]))?>);"/>
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.