Skip to content Skip to sidebar Skip to footer

How To Pass An Integer Value To Js That Is In A Php Integer Variable?

I'm trying to pass some variables from PHP to JS. I saw here that for strings the following code would work: var str = ''; I've been using this: va

Solution 1:

First of all, lets go over how to declare a variable in javascript.

There are many types of variables, but lets go over int and string. Strings have to have quotation marks around the. Int's don't.

varint = 5;
varstring = "hello";

Now when we are passing a variable from php to javascript, all we are doing is replacing the value after the equal sign with a variable declared in php. You mentioned the two ways for echoing a variable.

var str = "<?phpecho$phpVariable; ?>";
var str = "<?=$phpVariable?>";

If these variables were int (which by the way includes any number, whether integer or not), there would be no quotation marks around the php open and close tags. Now, you said you prefer using the second method. I would really advise you not to. Even though it is a lot easier to type <?= $phpVariable ?> than <?php echo $phpVariable; ?>, the former one isn't supported on all servers, whereas the latter one is. You can use it if you want, but if you ever want to move to a server, you need to check if that syntex is allowed first.

Solution 2:

Well, Lets say in PHP,

$php_int_variable = 5;
$php_string_variable = "Hello";

For getting it in javascript as like following,

varint = 5;
varstring = "Hello";

You have to write,

var int = <?phpecho$php_int_variable; ?>;
var string = "<?phpecho$php_string_variable; ?> ";

Solution 3:

For a general solution, use this:

var data = JSON.parse("<?phpecho addslashes(json_encode($data)); ?>");

Solution 4:

EVEN Anyone with problems , make the Next Way !

var str = "<?phpecho$x; ?>"; 

this to string !

and

var int = parseInt('<?phpecho$x; ?>');

this to Int!

Solution 5:

var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var c = parseInt("10.33") + "<br>";
var d = parseInt("34 45 66") + "<br>";
var e = parseInt(" 60 ") + "<br>";
var f = parseInt("40 years") + "<br>";
var g = parseInt("He was 40") + "<br>";

var h = parseInt("10", 10)+ "<br>";
var i = parseInt("010")+ "<br>";
var j = parseInt("10", 8)+ "<br>";
var k = parseInt("0x10")+ "<br>";
var l = parseInt("10", 16)+ "<br>";

var n = a + b + c + d + e + f + g + "<br>" + h + i + j + k +l;

Post a Comment for "How To Pass An Integer Value To Js That Is In A Php Integer Variable?"