Hello friends a newbie question. I am new to programming hence please be gentle.
I am trying to post multiple session variables using JavaScript so that I can use them later in my PHP at multiple places.
My index.php file
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if ((empty($_SESSION['function1Val'])) & (empty($_SESSION['function2Val'])) && (empty($_SESSION['jsStatus']))) {
echo '<script type="text/javascript" src="vals.js"></script>
<script type="text/javascript">
var session=false;
var jsStatus;
var function1Val;
var function2Val;
</script>';
} else {
echo '<script type="text/javascript">
var session=true; var jsStatus=' . $_SESSION['jsStatus'] . ';
var session=true; var function1Val=' . $_SESSION['function1Val'] . ';
var session=true; var function2Val=' . $_SESSION['function2Val'] . ';
</script>';
}
?>
</head>
<body>
<?php
echo $jsStatus;
echo $function1Val;
echo $function2Val;
session_destroy ();
?>
</body>
</html>
My vals.js file
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// Set value to variable jsStatus
jsStatus = 'enabled';
// Call function to get function1
function1();
// Call function to get function2
function2();
// Make ajax call to php page to set the session variable
setSession();
}
}
function function1() {
// code to get value goes here
function1Val = 'result1';
}
function function2() {
// code to get value goes here
function2Val = 'result2';
}
function setSession() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","session.php?function1Val=" + function1Val,true);
xmlhttp.send();
// like this I want to transfer other values of 'function2Val' and 'jsStatus'
}
My session.php file
<?php
session_start();
// check if it is already set if you like otherwise:
$_SESSION['function1Val'] = $_REQUEST['function1Val'];
$_SESSION['function2Val'] = $_REQUEST['function2Val'];
$_SESSION['jsStatus'] = $_REQUEST['jsStatus'];
?>
I know the code is messy but I don't know how to write the correct syntax. I actually tried to modify a single variable code but failed. hence need help.
The idea is to post various values derived out of various JavaScript functions to the session for use by PHP.
Please help.
UPDATE:
It has to be this way as the values to the said variables can be calculated with the help of JavaScript only.
You have to concatenate the parameters with an ampersand (&).
Use this line
xmlhttp.open("POST","session.php?function1Val=" + function1Val+"&function2Val=" + function2Val+"&jsStatus=" + jsStatus,true);
BTW: I would really suggest to use jQuery or a similar library for AJAX requests. Furthermore I would use JSON for exchanging the data or a Javascript array where the key names are those of the variables.
Related
This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 5 years ago.
I tried to use a simple echo function with JS in it to show alerts and prompts, in a php page which is called using AJAX. I looked at lot of other SO posts, but couldn't find any working solution, like this one. Here is my code:
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
And
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
</body>
</html>
No need to echo the script out, just use it as html.
//selectknown.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
alert("Hello world! This is an Alert Box.")
</script>
</body>
</html>
Firstly, if you wish to put a script tag in an echo statement, it is possible. I think your problem is that you are running the code as a .html file instead of running it as a .php file. Just name the file something like file_loader.php
The code needs to run on a server. PHP is a server side scripting language.
Or you could copy and paste the code below into a php playground to quickly see it working.
<html>
<head>
<body>
<?php
echo '
<script type="text/javascript">
alert("Hello world! This is an Alert Box.");
var accepted = prompt("enter the letters \'yes\' here");
</script>
';
?>
<div id='debug'>Waiting for file to load.....</div>
<script>
//AJAX
function callPhp(opt, algorithm, arrayReq, solArrayReq) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("debug").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "selectknown.php?q="+opt+"&alg="+algorithm, true);
xmlhttp.send();
</script>
</body>
</html>
Secondly, in order to load the file from the ajax code, you need to add an element that is identified by the specified Id - debug e.g.
<div id='debug'>Waiting for file to load.....</div>
Hope you find that helpful.
I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status== 200) {
document.getElementById("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?
I'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
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>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
I am trying to server device specific layout and also content based on the browser viewport. I have a heavey site and I am not using Media Queries for some specific reasons primarily page load speeds. I need to accomplish this task in this manner only.
OK the situation is like this.....
I have 2 files index.php and viewport.php both residing in a folder http://localhost/test/
To get the browser viewport and convert the values to PHP variable, I am using the following script:
<?php
if (isset($_GET['width'])) {
$layoutType = $_GET['width'];
if ( $layoutType >= 240 && $layoutType <= 600 ) {
$layoutType = 'mobile';
} else if ($layoutType >= 601 && $layoutType <= 900 ) {
$layoutType = 'tablet';
} else {
$layoutType = 'desktop';
}
} else {
echo "<script language='javascript'>\n";
echo " location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
. "&width=\" + document.documentElement.clientWidth;\n";
echo "</script>\n";
exit();
}
?>
My questions:
Q1. How can I store $layoutType as a Session Variable so that I can use it multiple times? What would be the correct syntax for it?
Q2. How can I run the file viewport.php from index.php and get only the $layoutType and no other data. This is because by using the <?php require_once ?> method I am getting my URL like this:http://localhost/test/index.php?&width=1600. I want the URL to display like http://localhost/test/ only. What will be the correct syntax I need to use in my index.php file?
Q3. Skipping the Ajax part is there a way to get rid of index.php?&width=1600 from the URL? I tried via .htaccess but it gives me the error saying "The page is not redirecting properly"
Please note: I do not intend to use and JavaScript Libraries like jQuery and MooTools as this is the only JavaScript function in my entire website and it wont make sense to load an entire library for it.
Firstly, PHP happens server side, so once the page loads the only way to use PHP again (without loading a page) is to make an ajax call, presumably to another php page that performs a certain function and returns a value.
If you want to store a value as a session variable so that it can be used continuously, you can do the following:
when they first land on your site have php check for the existence of a session and if it does not exist, call a Javascript function to get the layoutWidth and make an ajax call to a php page that will store it as a session variable and then reload the page and include the correct layout file.
I would probably not use this method and actually look at ways to do this with JavaScript/JQuery instead. But this is how you have asked to do it.
For your example, I have not used JQuery at all, but I would as the include is only about 19kb or so and it makes life SO much easier.
Example:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<?php
if (empty($_SESSION['layoutWidth'])) {
echo '<script type="text/javascript"> var session=false; var layoutWidth;</script>';
} else {
echo '<script type="text/javascript"> var session=true; var layoutWidth=' . $_SESSION['layoutWidth'] . ';</script>';
}
?>
<script type="text/javascript" src="js/viewport.js"></script>
</head>
<body>
<?php
if (!empty($_SESSION['layoutWidth'])) {
$layoutWidth = $_SESSION['layoutWidth'];
if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
include('layout1.php');
} else if ($layoutWidth > 900 && $layoutWidth <= 1200 ) {
include('layout2.php');
} else {
include('layout3.php');
}
}
?>
</body>
</html>
js/viewport.js
// JavaScript Document
window.onload = function() {
// if there is no session (session = false)
if (!session) {
// call function to get the screen size
getScreenWidth();
// make ajax call to php page to set the session variable
setSession();
}
}
function getScreenWidth() {
layoutWidth = screen.width;
}
function setSession() {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Reload the page
window.location.reload();
}
}
xmlhttp.open("POST","set_session.php?layoutWidth=" + layoutWidth,true);
xmlhttp.send();
}
your php file to set the session the parameter is passed from your ajax call:
set_session.php
<?php
session_start();
// you can check if it is already set if you like otherwise:
$_SESSION['layoutWidth'] = $_REQUEST['layoutWidth'];
?>
layout1.php
<?php
echo '<div>This is layout1.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
layout2.php
<?php
echo '<div>This is layout2.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
layout3.php
<?php
echo '<div>This is layout3.php</div>';
echo '<div>Your screen width is: ' . $_SESSION['layoutWidth'] . '</div>';
?>
This method means you dont have to pass parameters around in your URL. it will all be hidden.
Q1) $_SESSION['layoutType']=$layoutType;
Q2&Q3 ) I think you're making it too complex for yourself. Best way to achive what you want with restrictions that you have is to combine the power of cookie and session, you'll have a faster and neater code. So what you can do is check if the session layoutType is set, if not, inject a javascript code that'll get the layoutType for you and puts it in a cookie, and next time you include viewport.php in a a page, it'll check to see if the cookie is set and will transfer it to session for future use, so you can change viewport.php to this :
<?php
if(isset($_SESSION['layoutType'])){
//write the code for when session is set here
}elseif(isset($_COOKIE["layoutType "])){
$_SESSION['layoutType']=$_COOKIE["layoutType "];
}else{
$script = "<script language='javascript'>function SetCookie(cookieName,cookieValue) { var today = new Date(), expire = new Date(), nDays=1;expire.setTime(today.getTime() + 3600000*24*nDays);document.cookie = cookieName+'='+escape(cookieValue)+ ';expires='+expire.toGMTString();SetCookie('layoutType',document.documentElement.clientWidth}";
echo $script;
}
?>
I'm trying to find a good example on how to retrieve records using PHP from a table and refresh it say every 2 minutes using Ajax.
Anyone can point me to that tutorial?
I don't think you'll find a tutorial that specific, but you just need to learn AJAX and then make the AJAX call every two minutes using JavaScript's setInterval method.
EDIT
Meh, I'm bored enough to write this example. This isn't tested, but I don't think it has errors.
<html>
<head>
<script type="text/JavaScript">
window.onload = function()
{
// call your AJAX function every 2 minutes (120000 milliseconds)
setInterval("getRecords()", 120000);
};
function getRecords()
{
// create the AJAX variable
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// set up the response function
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
/*
Your code goes here. 'xmlhttp.responseText' has the output from getRecords.php
*/
document.getElementById("txaRecords").innerHTML = xmlhttp.responseText;
}
}
// make the AJAX call
xmlhttp.open("GET", "getRecords.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<textarea id="txaRecords"></textArea>
</body>
</html>
This is a bit of code that I wrote for this exact purpose. Adapt as appropriate.
AJAX code:
function timer()
{
var t=setTimeout("check()",2000);
// At an appropriate interval
}
function check(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText!=""){
var output = xmlhttp.responseText;
// Do what you need to do with this variable
}
}
}
xmlhttp.open("GET","backend.php",true);
// Set file name as appropriate.
xmlhttp.send();
timer();
}
PHP code:
<?php
// This assumes you have already done mysql_connect() somewhere.
// Replace as appropriate
$query = "SELECT * FROM table_name";
// Perform the query
$result = mysql_query($query);
// Get the results in an array
while($row = mysql_fetch_array( $result )) {
// Echo the message in an appropriate format.
echo "<br />" . $row['column_name'];
}
?>
Remember to initiate one of the JS functions as you load the page:
<body onload="timer()">