how can i pass js variable to php variable? - javascript

here is my sample code hope you can help me.
how can i pass a JavaScript variable to php variable?
<script>
var jsvar = "name";
</script>
<?php
$phpVar= jsVar;
?>

You can't. As others said million times, JavaScript is Client Side Language meanwhile PHP is Server Side. You can't manipulate Server Side language via Client Side Language. You should pass your JavaScript variable to Server with AJAX and do your operation.
Sources that you can find useful :
Access a JavaScript variable from PHP
How to pass variables and data from PHP to JavaScript?

<script>
var jsvar = "Name";
</script>
<?php
$phpVar = "<script>document.write(jsvar);</script>";
echo $phpVar;
?>

Related

Is it possible to store a JavaScript function that returns a string in a php variable?

something like :
<?php
$phpVar = "<script> function jsFunc(){ return 'Hello world';} </script>";
?>
is that even possible? if no, is there a way to do same thing?
If Ajax is the only solution, how do I retrieve a value of an input and store it as a php variable?
I tried something like this and it doesn't work.
<input type=text value="hello" id="myInput">
<?php
$phpVar = "<script>
function jsFunc(){
var inputVal = $('#myInput').val();
return inputVal;
}
</script>";
?>
PHP runs at server side and JS in the browser (apart node and related technologies).
Only way you can do something similar would be do to render from PHP in your HTML a tag <script> </script> and add you JS function and executing it there.
Al thought I would definitely not suggest it.
you can store this string in variable. for php interpreter it will be just a text string, nothing else. but when browser receives this data, string will be recognized as js function.
UPDATE
in this case easiest way for send data from browser to server is use a form. there is many examples in the web how to do it.

pass PHP Variable to JS

The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....

PHP cannot access variable declared in loaded php page with jquery load()

Usually I can get php variables from a different php file declared like this:
$myVar = 'hello';
require 'header.php'
So then in header.php I can use $myVar. But I cannot access a variable that I loaded with ajax in jquery. For example:
index.php:
<html>
<body>
<div id="myDiv"></div>
</body>
</html>
In a script I have:
$(#myDiv).load('newPage.php')
newPage.php :
$myLoadedVar = 'loaded var';
But then I cannot access $myLoadedVar from index.php, is it possible to do this or you cannot access php variables created with ajax ?
PHP is a server-side language while JavaScript is a client-side language. The only way you can get PHP data into JavaScript is by outputting the data in some manner. If you want the full output, just echo it. If you want to load a bunch of simple PHP variables into JavaScript, you can add all the variables you need JS to know about into an array, and then json_encode them.
$firstName = 'John';
$lastName = 'Doe';
$outputArray = array('firstName' => $firstName, 'lastName' => $lastName);
echo json_encode($outputArray);
Then when an ajax function can retrieve this data as an object and you can use result.firstName in JavaScript.
Passing complex items is impossible though, such as those with database connections as properties.

How to use xml pass the data to javascript by DHTMLX

I use DHTMLX. I want to use the ajax component get the data from php, the php will create the xml. How to get this xml data into javascript.
enter code here
dhtmlxAjax.get("php/getUsername.php", function(r){
r = r.xmlDoc.responseXML; // will give you DOM object
//console.log(r.firstChild.tagName);
alert(r.firstChild.tagName("param1"));
});
thank you
Just use the php echo function to echo the php variable into a java script variable.
eg. If you have a php variable called $XMLData you would do the following
var XMLdata = <?php echo $XMLData; ?>
Then on page load your php variable becomes a javascript variable and can be used. from anywhere in javascript provided that the variable is within its scope.

Run JavaScript from PHP from Ajax

Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data

Categories