Jquery if/else statement with dependencies on php session variable [duplicate] - javascript

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>

In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');

PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not

Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>

Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.

alert("Delete entry <? echo $row['id']; ?> ")

If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

Related

how to convert this code to insert it in .js file

I'm trying to make my website multilingual, i have the php code also and i have translated files, but my site has also js file where is this words which i want to translate, there is example of this php code and how to insert it to js file?
There is JS code
// Update search list
rsParent.html($('<div>').attr({id: 'relatedSearches', class: 'contentBox'})
.append($('<div>').addClass('cbHead').text('Related Searches'))
.append($('<div>').addClass('cbBody').html(list)));
}
});
and the word "Related Searches" i want to replace with this php code
<?php echo $lang['CHARTS']; ?>
It is not possible to do it directly since PHP is a serverside language which is executed once on a webserver, unlike javascript that is executed in client's browser.
What you can do is encode your PHP array $lang to JSON and then output it as inline javascript and assign it to a variable in javascript.
<?php
echo "<script>";
echo "var lang = " . JSON_encode($lang) . ";";
echo "</script>";
?>
Make sure this php code is placed (executed) before your javascript file because variable lang has to be declared before your javascript is executed.

PHP - how to give path to read pdf?

Select file name and redirect..
index.php
<?php
$book_name = ["Jenkins_Essentials","Asterisk","phalcon"];
echo "<select><option selected>Book Name</option>";
foreach ($book_name as $key => $value) {
echo "<option name='$key'>$value</option>";
}
echo "</select>";
?>
<script type="text/javascript">
$(document).ready(function(){
$("select").on("change",function(){
location.href = "reading.php?title="+$(this).val();
});
});
</script>
reading.php
$title = $_GET["title"];
header("Content-type: application/pdf");
header('Content-Disposition: inline; filename="$title.pdf"');
#readfile('D:\Learning\$title.pdf');//this is my issue
When I redirected it show Failed to load PDF document..
My running script file location is as we know C:\xampp\htdocs But pdf file place is as shown in above D: drive !How to give path to it?
On your last two lines, PHP isn't including the $title variable, as you are using single quotes and you are using backslashes. Try one of these:
header('Content-Disposition: inline; filename="'.$title.'.pdf"');
#readfile('D:/Learning/'.$title.'.pdf');
or:
readfile("D:/Learning/$title.pdf");
Backslashes are used for escaping characters, so use forward slashes as much as you can. On Windows, you can use both in file paths. Also, for outputting the file, try using this instead of #readfile:
$pdf = file_get_contents('D:/Learning/'.$title.'.pdf');
echo $pdf;
Another note - you should check if the file exists before accessing it. Place at the top of your script:
if(!file_exists('D:/Learning/'.$title.'.pdf')) {
echo "File doesn't exist.";
exit();
}
Hope this helps. Wish you the best.
Is the file name 'D:\Learning\$title.pdf' literally $title.pdf with the dollar ($) sign.
PHP variable interpolation works on the " double quote meaning that your variable is literally a string and not recognized as a variable by php.
You'll most likely want to change that to
readfile("D:\Learning\$title.pdf");
OR ( personally I would avoid this because of the back slash escaping ) However it's worth noting that windows will accept the forward slash ( Unix style )
readfile('D:\Learning\\'.$title.'.pdf');
readfile('D:/Learning/'.$title.'.pdf'); //this works fine on windows and avoids escaping the \
OR what I prefer.
readfile("D:\Learning\{$title.pdf}");
Otherwise it's looking for a file named $title.pdf literally

Value is not transferring with GET method

Whenever I write echo $_GET['sec']; then it shows the value of sec
but when I try the following code:
$(document).ready(function() {
setInterval(function () {
$('#div_id').load('../data.php?id_to=<?php $_GET['sec'];?>')
}, 100);
});
The value of "sec", which is coming from another page does not transfer to
data.php with id_to variable.
What's wrong with my code?
I can see the value of $_GET['sec']; in current page but the value is not available on the data.php file.
Code is okay so variable if available should be passed
So what can you try is:
You have simple mistake you don't echo
change <?php $_GET['sec'];?> to <?php echo $_GET['sec'];?> or <?= $_GET['sec'] ?>
also:
what's the output of this php code is it ile '../data.php?id_to=VALUE' If output is okay then variable will be passed via GET method
In your data.php try doing echo $_GET['id_to'] maybe you try to output sec and this causes problem?
You can always try print_r($_GET); on data.php
You're not outputting the GET variable into your JS string.
Replace:
$('#div_id').load('../data.php?id_to=<?php $_GET['sec'];?>')
With:
$('#div_id').load('../data.php?id_to=<?php echo $_GET['sec'];?>')
// That was missing ^
Alternatively, there's a shorthand available for a php echo:
$('#div_id').load('../data.php?id_to=<?= $_GET['sec'];?>')
While the syntax highlighter on here may make it seem like the nested single quotes will interfere, they won't. <?= $_GET['sec'];?> will literally be replaced by the value in sec, resulting in a valid JS string.

How to get PHP string value in javascript?

Hi have looking on various questions but none of them seem to help me. I have a php variable in my php code and I am trying to access that in my javascript when I do. . .
var thing = "<?php echo($phpvariable); ?>";
then when I do
alert(thing);
It comes out to be "<?php echo($phpvariable); ?>" in the alert statement
What am I doing wrong?
Your PHP is obviously not being parsed. Are you in a .php file? If you're in a .js file, you'll need the server to parse those (or, more safely, put the PHP part somewhere in the DOM that the JS can access)
However, you're doing it wrong:
var thing = <?php echo json_encode($phpvariable); ?>;
Note: no quotes. json_encode will take care of that for you.
If this code is in a function in javascirpt that executes on click or at a specific event, then:
You are writing PHP Syntax in javascript, there is no way that you load the page then you run the php code. PHP code runs on the server side, so before any other HTML Javascript code executes
Else if you want to dynamically set the variable thing in javascript when the page is first loaded, then most probably you meant to write in the php file:
var thing = <?php echo '"'.$phpvariable.'"'; ?>;

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