I have declared a javascript variable ,
var myJavascriptVar = 12345;
And unable to assign that value to php variable;
$myPhpVar = 'myJavascriptVar';
I know Ajax may be the solution of my problem. But i don't know how to use Ajax and solve the problem.
var myJavascriptVar = 12345;
Punit Gajjar
4,6217 gold badges32 silver badges64 bronze badges
asked Feb 7, 2014 at 5:37
2
Using Cookie is the better solution i think -
document.cookie = "myJavascriptVar = " + myJavascriptVar
answered Oct 12, 2016 at 19:58
1
Try using ajax with jQuery.post[] if you want a more dynamic assignment of variables.
The reason you can't assign a variable directly is because they are processed in different places.
It's like trying to add eggs to an already baked cake, instead you should send the egg to the bakery to get a new cake with the new eggs. That's what jQuery's post is made for.
Alert the results from requesting test.php with an additional payload of data [HTML or XML, depending on what was returned].
$.post[ "test.php", { name: "John", time: "2pm" }]
.done[function[ data ] {
alert[ "Data Loaded: " + data ];
}];
answered Feb 7, 2014 at 6:31
I have a better solution: Here, in the .php file, I have a variable called javascriptVar. Now, I want to assign the value of javascriptVar to my php variable called phpVar. I do this by simply call javascript variable by document.writeln in the script tag.
answered Mar 26, 2017 at 19:39
1
$msg = "var n=document.getElementById['fil'].val; document.write[n];";
echo $msg;
answered Sep 15, 2017 at 6:46
1
I guess you can use cookies for it.
1] First add a cookie jquery plugin.
2] Then store that window width in a cookie variable.
3] Access your cookie in PHP like $_COOKIE['variable name'].
//www.w3schools.com/php/php_cookies.asp
answered Feb 7, 2014 at 5:53
hizbul25hizbul25
3,7394 gold badges25 silver badges37 bronze badges
Javascript will be interpreted in Client's browser and you can not assign it to PHP variable which is interpreted on SERVER .
Feasible Solution : You can submit the Javascript value via ajax or through form submit.
answered Feb 7, 2014 at 5:58
Dimag KharabDimag Kharab
4,4211 gold badge21 silver badges45 bronze badges
You should see these links:
Assign Javascript value to PHP variable
Passing Javascript vars to PHP
Or you can use AJAX request or POST and GET methods to achieve this.
Snippet below may helpful for you:
document.cookie = "myJavascriptVar = " + myJavascriptVar
answered Aug 25 at 10:42
myvar=12345;
answered Jun 27, 2021 at 13:52
1
Please use this code and it will works fine in all cases.
var width=screen.width;
answered Jul 13, 2021 at 5:01
1