0

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.

2 Answers 2

5

You should pass the value as string:

<input type="button" name="delete" value="Remove" onclick="del('<?echo $arr1[0]?>');"/>
Sign up to request clarification or add additional context in comments.

7 Comments

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?
Naturally, that depends on the data format. What's been given in the question is a simple digits-and-dashes string id.
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.
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.
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]))?>);'...
|
2

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

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

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.