calling javascript method with a php retrieved argument - javascript

I have a javascript method in separate js file that I want to call from a HTML page with a php argument.
<?php
include "connection.php";
$selectedpatient = $_POST['patient_dropdown'];
$myquery = "SELECT * FROM `patient_info` patient_info.Name = '$selectedpatient' ";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
$tempdata = json_encode($data);
?>
<script> data_arrival($_tempdata); </script>
And I defined the source for the javascript file in the HTML header. It displays two errors:
1) Parse error in the javascript file - that's understandable as I included the javascript file in header and the file gets executed before the php actually retrieves any data.
2) data_arrival method is undefined
How can I fix this ?? I want to pass the $tempdata (after its populated by php) to data_arrival method as an argument.
Thanks in advance !

First of all: it's PHP that's executed first, not JavaScript. It can't be the other way round in your example.
data_arrival is undefined... because either you haven't defined it at all, or because it is defined after it's called.
To pass the value from PHP to JavaScript in your case, you can use:
data_arrival(<?php echo $_tempdata; ?>);
It will generate something like:
data_arrival([a, b, c, d, ...]);
Of course, data_arrival function need to be defined prior to its execution.
Edit
And maybe it's good to use the same variable name: $_tempdata vs $tempdata.

Related

How to pass a php variable to javascript that is being executed by php

I have some javascript code that is executed by php. The reason for this is I tried to print to a printer but I couldn't get php code to do it.
But the javascript code can. And I need to post a variable to the javascript so it knows what to print. Therefore I know I can post to php and from there echo the javascript to connect and print to my label printer. The last hurdle is passing in the variable received by POST to the javascript.
$val = "variable";
echo '<script>
var val = "<?php echo $val; ?>"; \\ trying to put the variable into the javascript
var format_start = "^XA^LL200^FO80,50^A0N36,36^FD";
var format_end = "^FS^XZ";
BrowserPrint.getDefaultDevice(\'printer\', function(printer) {
default_printer = printer
...
While I agree with the comenters about not doing this, there is a simple misunderstanding in your code:
You are running PHP to output JS from the echo, you do not need to output the PHP tags, you can just output the variable, and when the page renders, the variable substitution will occur.
So, this:
var val = "<?php echo $val; ?>";
Should be
var val = "$val";
The JS at page render, visible via view source, will now look like:
var val = "myValVarContents";
I hope that helps, even though as said, this is generally a bad idea
D

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;
?>

Javascript code not working inside PHP

This is the code I am executing inside PHP condition
<?php
if(is_null($model)) {
echo "<script>window.parent.closeIframe(true)</script>";
}
?>
It doesn't work even If I put alert or calling a function inside my PHP condition.
Is it possible to run a Javascript code inside PHP ?
Is there any PHP extensions needed to be enabled ?
Was working on a recent project to execute JavaScript after PHP was finished executing. Try placing the script tag after the PHP tag:
test.php:
<?php
echo "hello";
include("example.html") // To insert HTML page
?>
<script>
alert("hello");
</script>
This worked for me. You can try it. I forced $model to be null.
<?php
$model = null;
if(is_null($model)) {
echo "<script>alert('Hello World')</script>";
}
?>
You can't call close from client Javascript from server PHP.
but you can call from HTML client. put close in bottom of HTML body tag
and make sure Javascript is turned on in your browser.
Hi if you are executing a query and then checking if result is null then this script to run then please correct. PHP is_null is true when it get NULL php datatype and a query never returns this. So if i am right then you can use this one this is my example which i used to check your method.
<?php
$con = mysqli_connect("localhost","root","","user") or die("error");
$res = mysqli_query($con, "select * from user where id =-99");
$model = mysqli_num_rows($res);
if(empty($model)) {
echo "<script>window.parent.closeIframe(true)</script>";
}
?>
just to check you can refer
$model = 0;
<?php
if(empty($model)) {
echo "<script>alert("hello")</script>";
}
?>

Is json_encode extremely picky?

It appears that json_encode is being VERY picky about what other stuff can be inside my PHP file. Which is fine, because I just do what I normally would do in file A (with json_encode) in it's own file.
I just thought I would ask because I am storing a variable in the $_SESSION instead of updating my database with the variable because json_encode doesn't seem to want to work when I have all of the code in its file.
For instance, this code doesn't work:
<?php
session_start();
include 'dbcon.php';
$sessionID = uniqid();
echo json_encode($sessionID);
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
When going to the file in my browser, I do in fact get the json_encode results, however when my Javascript calls it it doesn't seem to correctly import it.
So, for now I simply have two PHP files:
<?php
session_start();
$sessionID = uniqid();
$_SESSION["sessionID"] = $sessionID;
echo json_encode($sessionID);
?>
Which echo's the same thing as in the first file, but this time my JavaScript correctly imports it.
and
<?php
session_start();
include 'dbcon.php';
if(isSet($_POST['clearSession']) == '1')
{
$query = "UPDATE currentID SET id=('0')";
$execute = $mysqli->query($query) or die($mysqli->error.__LINE__);
} else {
$sessionID = $_SESSION["sessionID"];
$query = "UPDATE currentID SET id=('$sessionID')";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
}
?>
I guess my question is, why does this happen? It seems kind of silly that I have to store the uniqid in a SESSION so that my other PHP file can add it to the database. Whereas if I simply had it in one file, then I could just update the database when I generate a new uniqid and avoid having to use $_SESSION in the first place.
You have this:
$sessionID = uniqid();
echo json_encode($sessionID); // "53d4c17abfe87"
Since uniqid() produces a plain string, your output is not valid JSON as per the format specification. You'll need something like this instead:
$sessionID = uniqid();
echo json_encode(array($sessionID)); // ["53d4c17abfe87"]
Why does json_encode() generate invalid JSON in the first place? Because some times it's useful to generate partial JSON. For instance, it's a handy trick to inject values into generated JavaScript code:
var foo = <?=json_encode($sessionID)?>;
It's also documented:
PHP implements a superset of JSON - it will also encode and decode
scalar types and NULL. The JSON standard only supports these values
when they are nested inside an array or an object.
So to answer the question title:
Is json_encode extremely picky?
On the contrary, it's fairly relaxed!
You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.
So, what you would want would be something like this:
echo json_encode(array('sessionID' => $sessionID));
And then when you parse the JSON with JavaScript you can access it like this:
obj = JSON.parse(jsonObj);
alert(obj.sessionID);
Obviously, jsonObj is the JSON passed from the server.
Hope this helps!

how to get php data at javascript variable

This is a php file below named getques.php at server. In this php file, the variables subnm1, chpno1 and qnumber1 are posted from a html-javascript file from client side. With these, a database at server is accessed and the output of SQL query is stored in a variable $px.
<!DOCTYPE html>
<html>
<body>
<?php
$x = $_POST["subnm1"];
$y = $_POST["chpno1"];
$z = $_POST["qnumber1"];
$con=mysqli_connect("localhost","compete7_bhunia","pr393ss","compete7_iitmock");
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$result = mysqli_query($con,"SELECT question, optiona, optionb, optionc, optiond,
coroption FROM $x WHERE qnumber = $z AND chapno = $y");
while($row = mysqli_fetch_array($result))
{
$px = $row['question'];
}
mysqli_close($con);
?>
</body>
</html>
This $px is showing its desired data that has been retrieved from database. Now, I want that this variable $px should be passed to the same html-javascript file. How to get it at javascript. The relevant part is as below.
<script type="text/javascript">
var abc = "<?=echo $px ?>";
alert(abc);
</script>
This is not showing the value of $px. Pl. help.
Avoid using short open tags.May be in your php short open tags is not enabled. So try like this..
var abc = "<?php echo $px ?>";
short_open_tag directive) with PHP 5.3 or below (but since PHP 5.4.0,
Actually, in the php.ini-production file provided with PHP 5.3.0, they are disabled by default:
$ grep 'short_open' php.ini-production
; short_open_tag
short_open_tag = Off
So, using them in an application you want to distribute might not be a good idea: your application will not work if they are not enabled.
Use like this :
<?php echo $px ?>";
As others have stated, you have a syntax error, your output line should read like
var abc = "<?php echo $px ?>";
However, this is not safe (and don't use short open tags <?=, as they may be disabled in PHP < 5.4): consider that $px contains a double quote, then your syntax will be malformed; it is even possible to inject JavaScript code this way. Don't do this!
A safer method is to use json_encode:
var abc = <?php echo json_encode($px) ?>;
(Note that you don't need to surround this with quotes.)
On a side note, you are vulnerable to SQL injection. Please use prepared statements to prevent this.

Categories

Resources