Calling PHP from document.ready - php

Is there a way in document ready to call php scripts?
I want to do something like this.
<script>
$(document).ready(function($) {
<?php require("readenglish.php"); ?>
<?php require("readfrench.php"); ?>
<?php require("readspanish.php"); ?>
<?php
$opload = $_GET['opload'];
if ($opload == "reade") {
}
else if ($opload == "readf") {
echo "<script type=\"text/javascript\">\n";
echo "document.f1.r1[0].checked = false;\n";
echo "document.f1.r1[1].checked = true;\n";
echo "SelectRead();\n";
echo "</script>";
}
?>
});
</script>
The three php scripts create divs and add information to them from an external domain php script.

You're mixing client and server side with no interface there. You're going to have to use $.ajax to pull in the content from the php scripts and update your DOM accordingly.
Of course... you could also design your site in a way that makes sense. This method looks suspicious at best and almost positively has a much better, exclusively server side solution.

You could do something like this in your page:
$(document).ready(function($) {
$('#result').load('test.php', function() {
alert('Load was performed.');
});
});
Where, on the server, test.php contains your code:
<?php require("readenglish.php"); ?>
<?php require("readfrench.php"); ?>
<?php require("readspanish.php"); ?>
<?php
$opload = $_GET['opload'];
if ($opload == "reade") {
}
else if ($opload == "readf") {
echo "<script type=\"text/javascript\">\n";
echo "document.f1.r1[0].checked = false;\n";
echo "document.f1.r1[1].checked = true;\n";
echo "SelectRead();\n";
echo "</script>";
}
This then needs to be added back into the DOM on the client side. Not good design though.

I would recommend using jQuery. They have a load method that does exactly what you're asking: http://api.jquery.com/load/

you may want to read this article http://www.developer.com/tech/article.php/923111/Client-side-Versus-Server-side-Coding---Part-1.htm

Related

Session Flag doesn't work in Javascript

I use session flag in javascript for IF function. If session flag is 1, the javascript will show a specifict div on click. I have tried it manually, but the code doesn't seem to work.
This is my JS code:
$(document).ready(function(){
check = <?= $_SESSION['flag'] ?>;
$("#bag").click(function(){
if(check==0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
});
And this is the session in the head of html file:
<?php #session_start();
$_SESSION['flag']=0;
?>
Please check it in the fiddle: http://jsfiddle.net/9mm5ougu/
config-haslogin.php
<?php
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
mysql_connect("mysql.com","name","password") or die("cannot connect");
mysql_select_db("databasename") or die("Fail here");
$myemail= $_POST['myemail'];
$mypassword= $_POST['mypassword'];
$sql= "SELECT * FROM user WHERE myemail='".$myemail."' and mypassword='".$mypassword."'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1)
{
echo "Login successful";
$_SESSION['flag']=0;
header("Location:index.php");
}
?>
You can't put PHP code into a JavaScript file, because PHP is interpreted on the server side, while JavaScript is interpreted on the client side (at least here in your use case).
If you really have to do conditional treatment based on the PHP $_SESSION value, you have multiple choices (listed from the worst to the best one IMHO):
Solution 1: use a dynamic JavaScript file (the worst)
Put PHP code in your JavaScript file, but use the .php extension instead of .js. Your JavaScript code would look like something like this:
file.js.php
$("#bag").click(function(){
<?php if ($_SESSION['flag'] === 0): ?>
$("#login").show();
$("#notlogin").hide();
<?php else: ?>
$("#login").hide();
$("#notlogin").show();
<?php endif; ?>
});
And you can include this PHP file as a JavaScript file:
index.php
<script src="file.js.php"></script>
This is the worst solution:
- as you're mixing both languages, your file will soon become unreadable
- because the file is now dynamic, the user's browser can't put it on the client-side cache
- you're using PHP server's resources where it's not really necessary
- you can't deploy your file on a CDN, or on a simple server dedicated to serve static file
- you can't minify your JavaScript file
Solution 2: use two different JavaScript files
Create two different JavaScript file, one for logged in user and one for logged out. Load the correct file using the $_SESSION value.
loggedOut.js
$("#bag").click(function(){
$("#login").hide();
$("#notlogin").show();
});
loggedIn.js
$("#bag").click(function(){
$("#login").show();
$("#notlogin").hide();
});
index.php
<body>
<!-- page content here -->
<?php if ($_SESSION['flag'] === 0): ?>
<script src="loggedIn.js"></script>
<?php else: ?>
<script src="loggedOut.js"></script>
<?php endif; ?>
</body>
This solution is better than the first one because it resolves almost all points: the file is cached on the client and you don't mix PHP and JavaScript code. But this is not the best solution you can have, because it brings a lot of code duplication and it would be harder to maintain the code base.
Solution 3: bring the model client side (or sort of)
You can pass your data model to the JavaScript file, and use it directly from there. As an example, you can have a class name on the <body> tag that depends on the $_SESSION['flag'] value, and your JavaScript file will behave differently based on this value. Here is an example:
index.php
<?php
$className = $_SESSION['flag'] ? 'logged-in' : 'logged-out';
?>
<body class="<?php echo $className; ?>">
<!-- page content here -->
<script src="yourFile.js"></script>
</body>
yourFile.js
$(document).ready(function(){
var isLoggedIn = $('body').hasClass('logged-in');
$("#bag").click(function() {
if (isLoggedIn)
{
$("#login").show();
$("#notlogin").hide();
}
else
{
$("#login").hide();
$("#notlogin").show();
}
});
});
If this class is only used by the JavaScript code (it means this class will no be used in the CSS code), you should prefix it with this js- to differentiate it from real CSS class names.
While you are accessing PHP variables inside Javascript, enclose that within quotes like
check = "<?= $_SESSION['flag'] ?>";
Check this fiddle.
Use AJAX to get the data you need from the server.
For example create get-data.php:
<?php #session_start();
_SESSION['flag'] = 0;
json_encode(_SESSION['flag']);
?>
Call it from ajax:
$(document).ready(function(){ // your DOM loaded
$.ajax({
url: '/get-data.php',
success: function(response){
$("#bag").click(function(){
if(JSON.parse(response) == 0){
$("#login").show();
$("#notlogin").hide();
} else {
$("#login").hide();
$("#notlogin").show();
}
});
},
error: function(){
alert('data not loaded');
},
complete: function(){
}
})
})

running javascript from php?

I don't know if this is possible as i know php is server side and javascript is client side.
But i am trying to run this javascript code from an if isset inside a php page.
I am using this code:
<?php
if( isset($_POST['submit2'])){
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
});
</script>";
}
?>
this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should.
So, I don't know what the issue is here>
can some one please help me out with this?
I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; echoing a javascript boolean into my JS block using php. This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM.
So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same):
<?php
if( isset($_POST['submit2'])){
$varSet = "var set2 = 1;";
} else {
$varSet = "var set2 = 0;";
}
?>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
<?php echo $varSet; ?>
if(set2 == 1){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
}
});
</script>
</head>

PHP output value of JS function

<html>
<script type="text/javascript">
function show_alert()
{
alert("I am an alert box!");
}
</script>
<body>
<?php
$x = 8;
if($x ==10){
echo "Hi";
}
else{
echo 'show_alert()';
}
?>
</body>
</html>
How do I get the echo to output the value of show_alert() ?
Change
echo 'show_alert()';
to
echo '<script>show_alert()</script>';
so that the browser knows to treat show_alert() as a function call and not regular HTML text.
You need to wrap it in a script tag:
if($x ==10){
echo "Hi";
}
else{
echo '<script type="text/javascript">show_alert();</script>';
}
Note, this will not wait until the page has finished loading to call show_alert(). The alert will be displayed as soon as the browser reaches this point in the page rendering, which may be otherwise incomplete behind the alert box. If you want it to wait until the whole page is loaded, place the condition to be called in <body onload>
<body <?php if ($x != 10) {echo 'onload="show_alert();"';} ?>>
<?php
if ($x == 10)
{
echo "Hi!";
}
?>
</body>
If you mean call showAlert() when the browser renders/evaluates that line:
echo '<script type="text/javascript">show_alert();</script>';
If you mean get the value of showAlert() in PHP, you can't - PHP is a server-side language.
This:
echo 'show_alert()';
will simply print "showAlert()" on the page, unless you have already opened a <script> tag.
I think you may be confused about the difference between client side and server side code.
HOWEVER, if you are using the two correctly, and you want to make it appear:
echo '<script type="text/javascript">show_alert();</script>';
It depends largely upon when you want the show_alert() javascript function to be called. Guessing by the PHP code that you're using, I am going to assume that you want the javascript function to be called as soon as the page loads, in which case you might want to use PHP before the body loads, and add an "onload" attribute event handler to your body tag:
if($x ==10){
echo '<body>';
}
else{
echo '<body onload="show_alert();">';
}

<?PHP ?> tag can be used in javascript

Can we use the<?php ?> tag in javascript? If yes then my next question is; can we use session in this tag? Example:
success:function(data)
{
if(data)
{
<?php
if(isset($_SESSION['UserId']))
{ ?>
window.location.href="coll_delivery_det.php";
}
else
{
?> window.location.href="courier.php"; <?php
}
} ?>
}
If I understand what your looking to do you would want to use php to echo out your javascript commands.
success:function(data)
{
if(data)
{
<?php
if(isset($_SESSION['UserId']))
{
echo "window.location.href=\"coll_delivery_det.php\";";
}
else
{
echo "window.location.href=\"courier.php\";";
}
} ?>
}
Yes. But only if the page is executed as actual PHP page.
If you use PHP code through your javascript or HTML I suggest using templatish statements, like so:
<?php if ($someVariable) : ?>
var i = 0;
<?php else : ?>
var i = 2;
<?php endif; ?>
It'll be much more clear what statements are closed. Instead of the following:
<?php if ($someVariable) { ?>
var i = 0;
<?php } else { ?>
var i = 2;
<?php } ?>
In fact, you can't use PHP tags in JavaScript.
You can only generate either whole JS code or only some data for it using PHP.
The specific solutions posted here address your current situation, I'd just like to touch on the reasoning behind them.
Javascript logic is executed in your browser.
PHP logic is executed on the server.
Embedding conditional PHP statements directly in javascript won't do what you want, but you can use PHP to generate the javascript your browser needs to execute.
Yes as long as you are doing this within a file that will be executed as PHP but your code is syntactically incorrect from what I can see. Try this instead:
success:function(data) {
if(data) {
<?php if(isset($_SESSION['UserId'])) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
}
It is worth noting that you cannot go the other way. Javascript variables cannot be used in PHP code as by the time the users browser executes the Javascript the PHP execution cycle is terminated. The only way to pass it back this way would be to make an Ajax request.
Also the PHP will only be run once each page load so using your code if $_SESSION['UserId'] is set then the users browser would just see:
success:function(data) {
if(data) {
window.location.href="coll_delivery_det.php";
}
}
Otherwise if it is not set it will just be rendered from PHP as:
success:function(data) {
if(data) {
window.location.href="courier.php";
}
}
In this way javascript is generated from your PHP code.
Yes, php can generate anything: html, css and JavaScript as well. So you can do something like that on your .php page:
function() {
<?php if($data) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
However you need to remember that PHP is generating JavaScript as any other text, so you can't use Javascript variables in PHP script. eg. something like that will not work:
function test(){
var r=1;
<?php if ($r==1){ ?>
alert('r = 1');
<?php }?>
}
If you're using apache you can create a .htaccess file in your javascript directory with the following contents:
AddHandler php-cgi .js
This will make your .js files run as php, but retain its original extension.
the easiest way is to create a page that generates a dynamic javascript and includes the header for the javascript.
mysite.com/js.php
<?php header("Content-type: application/x-javascript");?>
success:function(data) {
if(data) {
<?php if(isset($_SESSION['UserId'])) { ?>
window.location.href="coll_delivery_det.php";
<?php } else { ?>
window.location.href="courier.php";
<?php } ?>
}
}
but you probably dont want to do that.. browsers save the included javascript files on cache, and you could have some problems with that..
the best way to proceed is to have your js files separated and and pass some parameter to the functions or classes using a <script> tag inside your <header>

Run a JavaScript function from a php if statement

I am using PHP conditions and want to know if I can run a JavaScript function without some one have to click on it using JavaScript:
if($value == 1)
{
JavaScript to run the function
}
How would I do that?
First of all keep in mind that your PHP code is evaluated on the server, while JavaScript runs in the browser on the client-side. These evaluations happen in different places, at different times. Therefore you cannot call a JavaScript function from PHP.
However with PHP you can render HTML and JavaScript code such that it is only rendered when your PHP condition is true. Maybe you may want to try something like this:
if($value == 1) {
echo "<script>";
echo "alert('This is an alert from JavaScript!');";
echo "</script>";
}
Javascript is client-side code, PHP is server-side, so you cannot execute javascript while building the page in PHP.
To execute javascript on the client-side as soon as the page has loaded, one way is to use the body onload handler to call your function:
<?php
echo '<script type="text/javascript">';
echo 'function myFunction(){ /* do_something_in_javascript */ };';
echo '</script>';
if ($value == 1) {
echo '<BODY onLoad="myFunction()">';
}
?>
Better yet, if you can afford the bandwidth, use jQuery and use $(document).ready():
<?php
if ($value == 1) {
echo '<script type="text/javascript">';
echo '$(document).ready(function(){ /* do_something_in_javascript */ });';
echo '</script>';
}
?>
I've found that you cannot do something like this in IE and other browsers. It does work in Firefox though. You have to echo out each line as posted in the other method.
<?php
if(somecondition)
{
?>
<script>
Some javascript code
</script>
<?php
}
?>
I know this thread is old but I just came across it and wanted to add my technique.
You can also echo the php variable into JavaScript and do something based on its value. I use it to place database values into js so the user can do math on the page with them
<script>
var jsvar = <?php echo $phpvar ;?>
if (jsvar = x){ do something...}
</script>
After some tinkering, I was able to get the following to work within a .php file.
This doesn't work in a .html file though.
<?php
if (isset($_SESSION['loggedin'])) {$login='t';}else{$login='f';}
?>
<script>
var login = "<?php echo $login ?>";
console.log(login);
if (login == 'f'){ .. do something..}

Categories