Javascript not pulling php variables, page not loading php? - php

I have a site online to test and edit using "000webhost.com" which has php and mysql.
Either javascript is not pulling the PHP variables or the site is not loading php.
when I load the page I start up chrome code viewer to check the code live. when looking over the default.php (index page) it does not show my php variables.
Javascript
window.onload = function(){
var iso = "<?= $isop; ?>";
var meg = "<?= $megp; ?>";
var mex = "<?= $mexp; ?>";
var mor = "<?= $morp; ?>";
var noc = "<?= $nocp; ?>";
var pye = "<?= $pyep; ?>";
var tri = "<?= $trip; ?>";
var zyd = "<?= $zydp; ?>";
}
php page
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Str8nge Brew Calculator</title>
</head>
<body>
<?php
$isop = "1";
$megp = "1";
$mexp = "1";
$morp = "1";
$nocp = "1";
$pyep = "1";
$trip = "1";
$zydp = "1";
?>
<script type="text/javascript" src="calceve.js"></script>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
....
</body>

If you want your calceve.js file to render the PHP contained within, you'll need to change the file extension to .php, src="calceve.php". Whenever I have a javascript file that contains PHP, I use something like myfile.js.php, just to keep it straight in my head what the file actually is.

I fixed it by taking all the javascript code and moving it inside the tag on the php page. not sure why this fixes it exactly but it works. I did also move the window.onload so the var are first

Related

Alternatively load page via php if ajax fails

I am trying to replace the contents of a div with an external file via ajax. the code I am using to do so is :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
var x = null;
if (window.XMLHttpRequest) {
var x = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} else {
// fallback
}
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function() {
if(x.readyState == 4) {
if(x.status==200)
document.getElementById("aside").innerHTML = x.responseText;
else
document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is other content</div>
</body>
</html>
My Questions:
If JavaScript is enabled, then the above code works fine but if JavaScript is disabled, then php should load that file. How d I do this?
If you are going to make your code backward compatible without JavaScript then you really have no reason to use AJAX at all. If you just want the string into your aside Element then do something like:
//first the PHP page 'other_content_1.php'
<?php
$resp = 'Whatever String Response You Want';
?>
//now your other page
<?php
include 'other_content_1.php';
?>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN'
'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Test</title>
</head>
<body>
<div id='aside'><?php echo $resp; ?></div>
<script type='text/javascript' src='should_be_external.js'></script>
<body>
</html>
Note, that if you want this to happen besides onload then you would submit a form using $_POST or $_GET to handle the PHP response.
Have you considered trying the noscript option?
See: What do I do if Javascript is disabled by a client?
However, if you have a lot of pages this might be a lot of work if you use jquery/ajax throughout your pages - which I am guessing you do or loading them in with jquery/ajax would be slightly pointless.
By the time the web page is displayed in the browser and found that JS is not supported, PHP/server already served the page. You can try this.
#aside element can have text & link informing user about not having JS support and take another page
PHP can load the file and serve the content in the new page.
If JS is supported, your above code will be anyway replacing the above link.

How to insert javascript value into the php session variable

I want to insert javascript value into the php session variable but inside the javascript function.
Here is what I have tried and it is not working:
function languageChange()
{
var lang = $('#websites1 option:selected').val();
<?php $_SESSION['SESS_LANGUAGE']?> = lang;
alert(<?php echo $_SESSION['SESS_LANGUAGE']?>);
}
You cannot access it directly (the way you are doing). However, it can be done using AJAX.
Here is the perfectly working solution.
Here is the HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<label for="websites1">Websites</label>
<select name="websites1" id="websites1">
<option value="Design">Design</option>
<option value="Dev">Dev</option>
<option value="Ecom">Ecom</option>
</select>
</form>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function languageChange()
{
var lang = $('#websites1 option:selected').val();
return lang;
}
$('#websites1').change(function(e) {
var lang = languageChange();
var dataString = 'lang=' + lang;
$.ajax({
type: "POST",
url: "pass_value.php",
data: dataString,
dataType: 'json',
cache: false,
success: function(response) {
alert(response.message);
}
});
return false;
});
});
</script>
</body>
</html>
Here is the AJAX part:
//pass_value.php
<?php session_start();
$_SESSION['SESS_LANGUAGE'] = $_POST['lang'];
$_SESSION['SESS_LANGUAGE'] = 'This is my PHP session var --->'.$_SESSION['SESS_LANGUAGE'];
print json_encode(array('message' => $_SESSION['SESS_LANGUAGE']));
die();
?>
EDIT 1:
Once you run the code, simply select any of the other options from the dropdown menu and you will receive an alert that gives you the value of the php session variable along with the custom text that I added to it.
EDIT 2:
If you want to run my solution on your end, make sure you point to core jQuery js file correctly. My jquery code points to src="js/jquery_1.7.1_min.js". Make sure you update this.
Javascript does not have access to PHP-variables. The client (web browser/javascript) only has access to the Cookie or Cookieless ID (Querystring) associated with the session.
Sessions are used this way for the purpose of not letting the client modify settings associated with the session without going through the server. The less "secure" way is to use cookies for all settings. Something like language-setting might be a good idea to store in a cookie rather than the session.
In order to solve this, you could make a page which takes a session property name (like your "SESS_LANGUAGE") and a value which puts it in the session using php. I strongly advise against this because any user could then set any session variable.
The best way I can imagine is that you send an AJAX-call to a page saying that you want to change the language.
The called URL would be something like this:
changelanguage.php?lang=en_US
And the php-code for changelaguange.php:
$_SESSION['SESS_LANGUAGE'] = $_GET['lang'];

Passing js variable into php string

I need a little bit of help im trying to page a js variable into a url thats being parsed in php using file_get_contents. Im not sure where to start to do that.
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>
<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');
?>
any advice is appreciated, like i said im in the dark on this one.
Here's an example using jquery.
Javascript:
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
$.post("/somephp.php", {ticker: js_variable}, function(data) {
// returned from php
});
</script>
PHP:
<?php
$ticker = $_POST['ticker'];
$file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
?>
Expanding on what Jashwant says...
PHP is a server-sided language, which does work behind the scenes. Javascript is client-side, which runs and executes code on the local client's machine (ie through the browser).
You can however use AJAX (Asynchronous JavaScript and XML) so the local client sends HTTP requests to the server without reloading the current page. For instance, you can use AJAX to send the contents of the variable to the server.
For easier usage, you should check out jQuery's methods regarding ajax calls. See: http://api.jquery.com/jQuery.ajax/
Hope it works well.
Heres how you can do it with jquerys post() and then return json, you could build the result as you expect to output within the php part or you could use jquery to loop with each() through the result.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
if(!empty($_POST['s'])){
$ticker = $_POST['s'];
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');
header('Content-Type: application/json');
echo json_encode(array('result'=>$file));
}else{
echo 'Request not allowed!';
}
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";
$.post('this_script.php',{s: js_variable}, function(data) {
$('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>
<div id="divResult"><div>
</body>
</html>

How to pass value from javascript to php using address bar

I have .js and .php files and html pages. I am including js files in html files and php files in js files.
I want to pass 'cat' value from js file to php file using address bar when I go to this page;
/demo/convert.html?cat=volume
But I have no idea how to do this.
By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.
Test this sample code with an URL like :
http://sputnick-area.net/test/index.php?foobar=works_as_a_charm
<?php
$var = $_GET['foobar'];
echo <<<EOF
<html>
<head>
<title></title>
</head>
<body>
demo of using PHP GET variable in Javascript :
<script type="text/javascript">
alert("$var");
</script>
</body>
</html>
EOF
?>
Edit :
if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
alert(vars['foobar']);
</script>
</body>
</html>
Sure you can. When your JS function is called, you would have to do something like this:
function someFunction(someParameters) {
//Do whatever you need to do
window.location = "/demo/convert.html?variableName=" + variable;
}
This will cause a page reload with the new variable accessible through PHP in the $_GET array. For example:
<?php
$name = $_GET['variableName'];
if(length($name) < 3) {
echo "That is a short name!";
}
?>
A page reload (used here), is necessary to send value to PHP as it is run server side. Your only other solution would be to use AJAX and load page content dynamically. This, however, would be the simplest solution.
EDIT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var urlvariable = getUrlVars()['variableName'];

Problems with ajax div refreshed page calling to parent.window.location

I have a parent page that calls to a child page using the prototype.js library. I am having problems redirecting a user based on a php mysql check. I would like to redirect the user to a new page if he gets removed from a mysql table. I have all of the code working correctly except my javascript that is calling to parent.window.location = "http://www.mysite.com/index_use.php?bye";. I used this same exact code on another page and it works totally fine. What could I be missing.
Prototype code:
var myTimer5 = setTimeout("myFunction5();",5000);
function myFunction5() {
var refint5 = 5000;
var myAjax5 = new Ajax.Updater("userguestcheck","userguestcheck.php?id=<?php echo $pid; ?>&prevent_cache="+new Date().getTime(),{
method:'get',
onComplete:function(data) {
var a5 = setTimeout("myFunction5();",refint5);
}
});
}
userguestcheck.php code:
<?php
$iuajksdv = 9846598234;
include "include.php";
session_start();
//Added check for total user guest disconnect
$usercheck = mysql_query("SELECT nickname FROM useronline WHERE nickname = '".$_SESSION['username']."'");
$usercheckslect = mysql_num_rows($usercheck);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<?php
if($usercheckslect == '') {
echo '<script type="text/javascript">
parent.window.location = "http://www.mysite.com/index_use.php?bye";
</script>';
} else {
}
// end disconnnect
?>
</head>
<body>
</body>
</html>

Categories