How to access variable declared in PHP by jquery - javascript

For example i declare some variable like test in server side of my PHP
echo('var test = ' . json_encode($abc));
Now i want to use this test variable in Jquery ..how can i use it?
What function do i need to use it?
For Example i have:
I have back end PHP code something like this
$abc = no
echo "var test= ".json_encode($abc);
I want jquery to do the following action(client side)
$(document).ready(function(){
function(json) {
if($abc == no )//this i what i want to be achieved
}
}

I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify.
for example:
<?php
$result = array('abc' => 'no');
echo json_encode($result);
?>
This is serverside script called data.php. In Javascript you can make so:
$(document).ready(function(){
$.getJSON('data.php', function (data) {
if(data.abc === 'no') {
your code...
}
});
}

You're comparing the wrong variable:
<?php
echo <<<JS
<script type="text/javascript">
var test = {json_encode($abc)};
$(document).ready(function(){
if(test == 'no' )
// here you go
}
});
</script>
JS;

If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:
<script type="text/javascript">
var phpValue = <?php echo $abc; ?>;
alert(phpValue);
</script>
I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:
<script type="text/javascript">
var phpValue = no;
alert(phpValue);
</script>
This is very basic, but you get an idea of what you could do by using that kind of code.

Related

I am facing errors linking a variable between PHP & JS in this HTML code

I have this PHP & JS Code with me, whose task is to post a variable message to a function :
<!DOCTYPE html>
<html>
<body>
<script language="php">
$somevar = $_GET['id'];
</script>
<script>
var msg = <?php echo $somevar; ?>;
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');
}
}
}
ThunkableWebviewerExtension.postMessage(msg);
</script>
</body>
</html>
What I want to do is, define a variable in PHP, fetch it's value in JS, and post it to the function. The reason I am using PHP is because I can get those values with PHP only. So, all I need to do is, get that PHP value into a JS variable and use it further.
When I run this code, nothing happens - but if I remove the whole PHP thing, and set the JS's var msg to a absolute string (like var msg = 'hi';) then it works. So, I think there's some problem with the linking of PHP and JS - can you please help me with this?
Any help is appreciated! Thanks!
You should not wrap PHP in <script> tags. You should wrap PHP in <?php ?>, so you need to swap this:
<script language="php">
$somevar = $_GET['id'];
</script>
with this:
<?php
$somevar = $_GET['id'];
?>
And the rest of the code seems to be OK.

how to hold javascript variable in php variable

I want to use javascript variable as php variable. I am echo php variable then its print. but when i am use for fetching data from database its show an error
Notice: Undefined index: document.write(i)
here my code
javascript
var i=0;
function inc()
{
i+=1;
}
<?php $foo="<script>document.write(i)</script>"; ?>
php
code work for
echo $foo
code not work for
$i=$foo;
$query="select * from TABLE where id = $i";
$result=mysqli_query($conn,$query);
while($row=mysqli_fetch_row($result))
{
echo $row[0];
}
Then It show This Error Notice: Undefined index: document.write(i)
PHP is server-side code that is run to generate a page. Javascript is client-side code that is run after the page is sent to the visitor's browser. Javascript can't affect the server-side code because the server code is done running by the time the Javascript runs. If you want to have a user's selection change the behavior of the PHP code the next time the form is loaded, pass a variable through a $_POST variable when the form is submitted.
If you want your PHP and Javascript code to be using the same value, have the PHP code write a Javascript variable initialization into the page's <head> section before any Javascript would run that would need to use it.
<script>
var i=0;
function inc()
{
i+=1;
return i;
}
</script>
<?php
$foo = '<script type="text/javascript">document.write(inc());</script>'; //Script function call which return the var i value to php variable
echo $foo;
?>

Call a javascript function from php [duplicate]

How to call a JavaScript function from PHP?
<?php
jsfunction();
// or
echo(jsfunction());
// or
// Anything else?
The following code is from xyz.html (on a button click) it calls a wait() in an external xyz.js. This wait() calls wait.php.
function wait()
{
xmlhttp=GetXmlHttpObject();
var url="wait.php"; \
xmlhttp.onreadystatechange=statechanged;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
}
function statechanged()
{
if(xmlhttp.readyState==4) {
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
and wait.php
<?php echo "<script> loadxml(); </script>";
where loadxml() calls code from another PHP file the same way.
The loadxml() is working fine otherwise, but it is not being called the way I want it.
As far as PHP is concerned (or really, a web server in general), an HTML page is nothing more complicated than a big string.
All the fancy work you can do with language like PHP - reading from databases and web services and all that - the ultimate end goal is the exact same basic principle: generate a string of HTML*.
Your big HTML string doesn't become anything more special than that until it's loaded by a web browser. Once a browser loads the page, then all the other magic happens - layout, box model stuff, DOM generation, and many other things, including JavaScript execution.
So, you don't "call JavaScript from PHP", you "include a JavaScript function call in your output".
There are many ways to do this, but here are a couple.
Using just PHP:
echo '<script type="text/javascript">',
'jsfunction();',
'</script>'
;
Escaping from php mode to direct output mode:
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
You don't need to return a function name or anything like that. First of all, stop writing AJAX requests by hand. You're only making it hard on yourself. Get jQuery or one of the other excellent frameworks out there.
Secondly, understand that you already are going to be executing javascript code once the response is received from the AJAX call.
Here's an example of what I think you're doing with jQuery's AJAX
$.get(
'wait.php',
{},
function(returnedData) {
document.getElementById("txt").innerHTML = returnedData;
// Ok, here's where you can call another function
someOtherFunctionYouWantToCall();
// But unless you really need to, you don't have to
// We're already in the middle of a function execution
// right here, so you might as well put your code here
},
'text'
);
function someOtherFunctionYouWantToCall() {
// stuff
}
Now, if you're dead-set on sending a function name from PHP back to the AJAX call, you can do that too.
$.get(
'wait.php',
{},
function(returnedData) {
// Assumes returnedData has a javascript function name
window[returnedData]();
},
'text'
);
* Or JSON or XML etc.
I always just use echo "<script> function(); </script>"; or something similar. You're not technically calling the function in PHP, but this is as close as you're going to get.
Per now (February 2012) there's a new feature for this. Check here
Code sample (taken from the web):
<?php
$v8 = new V8Js();
/* basic.js */
$JS = <<< EOT
len = print('Hello' + ' ' + 'World!' + "\\n");
len;
EOT;
try {
var_dump($v8->executeString($JS, 'basic.js'));
} catch (V8JsException $e) {
var_dump($e);
}
?>
You can't. You can call a JS function from HTML outputted by PHP, but that's a whole 'nother thing.
If you want to echo it out for later execution it's ok
If you want to execute the JS and use the results in PHP use V8JS
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
You can refer here for further reference:
What are Extensions in php v8js?
If you want to execute HTML&JS and use the output in PHP http://htmlunit.sourceforge.net/ is your solution
Thats not possible. PHP is a Server side language and JavaScript client side and they don't really know a lot about each other. You would need a Server sided JavaScript Interpreter (like Aptanas Jaxer). Maybe what you actually want to do is to use an Ajax like Architecture (JavaScript function calls PHP script asynchronously and does something with the result).
<td onClick= loadxml()><i>Click for Details</i></td>
function loadxml()
{
result = loadScriptWithAjax("/script.php?event=button_clicked");
alert(result);
}
// script.php
<?php
if($_GET['event'] == 'button_clicked')
echo "\"You clicked a button\"";
?>
I don't accept the naysayers' answers.
If you find some special package that makes it work, then you can do it yourself! So, I don't buy those answers.
onClick is a kludge that involves the end-user, hence not acceptable.
#umesh came close, but it was not a standalone program. Here is such (adapted from his Answer):
<script type="text/javascript">
function JSFunction() {
alert('In test Function'); // This demonstrates that the function was called
}
</script>
<?php
// Call a JS function "from" php
if (true) { // This if() is to point out that you might
// want to call JSFunction conditionally
// An echo like this is how you implant the 'call' in a way
// that it will be invoked in the client.
echo '<script type="text/javascript">
JSFunction();
</script>';
}
Ordering It is important that the function be declared "before" it is used. (I do not know whether "before" means 'lexically before' or 'temporally before'; in the example code above, it is both.)
try like this
<?php
if(your condition){
echo "<script> window.onload = function() {
yourJavascriptFunction(param1, param2);
}; </script>";
?>
you can try this one also:-
public function PHPFunction()
{
echo '<script type="text/javascript">
test();
</script>';
}
<script type="text/javascript">
public function test()
{
alert('In test Function');
}
</script>
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
You may not be able to directly do this, but the Xajax library is pretty close to what you want. I will demonstrate with an example. Here's a button on a webpage:
<button onclick="xajax_addCity();">Add New City</button>
Our intuitive guess would be that xajax_addCity() is a Javascript function, right? Well, right and wrong. The cool thing Xajax allows is that we don't have any JS function called xajax_addCity(), but what we do have is a PHP function called addCity() that can do whatever PHP does!
<?php function addCity() { echo "Wow!"; } ?>
Think about it for a minute. We are virtually invoking a PHP function from Javascript code!
That over-simplified example was just to whet the appetite, a better explanation is on the Xajax site, have fun!
For some backend node processing, you can run JS script via shell and return the result to PHP via console.log
function executeNode($script)
{
return shell_exec('node -e \'eval(Buffer.from("'.base64_encode($script).'", "base64").toString())\'');
}
$jsCode = 'var a=1; var b=2; console.log(a+b);';
echo executeNode($jsCode);

How to pass javaScript values to PHP

How to pass javaScript values to PHP, my code is following
<script>
function a{
var b = a;
}
</script>
<button onclick="a(2)">Values</button>
<?php
$select = mysql_query("select * from tabl1 where id='values'"); // values comes here
echo $select;
?>
There's a lot of thing you could do.
Principal things you have to know is that javaScript run on the client side (browser), while PHP is running on the server.
Then If you want to pass a variable from your JS to your PHP you have to make a server call.
There's various way you can use in order to send variable from client to server.
As I understand from your example, it looks like your php code and your javascript on the same file. so maybe call your file another time will be enough for you.
Let's say your file's name is index.php.
<script>
function yourJavascriptFunction(id) {
window.location.href = "index.php?id=" + id;
}
</script>
Then in change your PHP code to this:
<?php
$select = mysql_query("select * from tabl1 where id='".$_GET['id']."'"); // values comes here
echo $select;
?>
$_GET will get the variable you've sent in your Js function.
Doing like this will refresh the page.
May be you don't want to refresh the page? Then look at the ajax way.
I hope it helps you

PHP variable is empty when called in jQuery script

I'm having a little trouble calling a PHP variable into a jQuery script. Basically, I run a few functions to determine if a user is logged in and, if so, store that as $loggedin=1. If a person that is on a page is NOT logged in, when a button is clicked I want them to be prompted to sign in (I'll obviously still ensure the user is ACTUALLY logged in on the server side before any processing of data). I searched around, and found the easiest way to get that information over to jQuery is to create the script as a PHP file so I can echo it into the script. Here is the high level code I'm using:
Call up the script:
<?php
$loggedIn = 1;
<script src="../buttonScript.php"></script>
?>
Script:
<?php header("Content-type: application/javascript"); ?>
var buttonScript = function(){
var loggedIn = <?php if($loggedIn===1){echo "1";}else{echo "0";} ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
When I click the button in a situation where $loggedIn is equal to 1, the alert gives me 0. In fact, if I simply echo $loggedIn in the script itself, the value is completely empty and the script errors out and won't pop up an alert at all. I'm confident that the PHP variable $loggedIn actually has a variable, since if I echo the variable right before the script is called, I successfully see the number 1. What am I missing here?
Note: added a couple lines in the script calling just for clarity.
Try this
<?php
$loggedIn = 1;
require("/path/buttonScript.php");
?>
buttonScript.php
<script type="text/javascript">
var buttonScript = function(){
var loggedIn = <?php echo $loggedIn; ?>;
$("#button").click(function(){
alert(loggedIn);
});
};
$(document).ready(buttonScript);
</script>

Categories

Resources