add php variable into ajax - php

how to work with php variable without jQuery?
My test.php file:
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "setCookie.php", true);
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
and my setCookie.php file is:
<?php
session_start();
$_SESSION['xxx'] = $language;
?>
If I put some simple echo statement in setCookie.php, it works and appears on my website. But why it can`t assign $language value to session['xxx']?

Beacuse ajax will be new request when its call so you have to pass value with it.
try this:
test.php
<?php
session_start();
$language = 'zzz';
?>
<!DOCTYPE html>
<html lang="en">
<body>
<button onclick = "setCookie()">test</button>
<p id="demo"></p>
<script>
function setCookie() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
language = '<?=$language?>'; //get value
xhttp.open("POST", "setCookie.php", true);
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.send("language=" + language); //send as post params
xhttp.send();
}
</script>
<?php
echo 'session: ' . $_SESSION['xxx'];
?>
</body>
</html>
setCookie.php
<?php
session_start();
$language = $_POST['language']; //retrive value
$_SESSION['xxx'] = $language; //assign to session
?>

Just Change your setCookie.php file like below.
<?php
session_start();
$_SESSION['xxx'] = $_POST['language'];
?>

Related

AJAX PHP not returning a value

I am not sure what I am missing. Is there anything wrong with my syntax on the below? I am trying to request an answer using an HTML form and then check the answer against a value with a PHP script.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innterHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>
And the PHP
<?php
//create correct answer for test question
$answer = "Ben";
$q = $_REQUEST["q"];
if($q == $answer) {
echo "correct answer";
} else {
echo "incorrect answer";
}
?>
It's not working, because you are calling .submit(); on form element, which in result refreshes a page and you don't see a result of XMLHttpRequest. Removing this line and fixing 'innterHTML' make your code working.
<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
// document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test">
<p id="servRes">replace</p>
</div>
</body>
</html>

Ajax call not replacing the content

What I want to do is replace the content of a div after a log in with a welcome message. I've read AJAX tutorials but I might've got it wrong.
Isn't the logIn function supposed to change the content of the element with the given id, with the content echoed by the php file?
Because right now, the log in is done but the content echoed by the php file is displayed in login.php instead of replacing the content of my "user_panel" div.
My html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>My awesome blog!</title>
<script>
function logIn(u,p) {
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<div class="nav">
<div class="container">
<div id="user_panel">
<ul>
<li>Login</li>
<li>Register</li>
</ul>
</div>
</div>
</div>
<form class="login" action="login.php" method="post">
<label class="login_label" for="username">Username:</label>
<input type="text" id="username" name="username">
<br>
<label class="login_label" for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="Login" onclick="logIn(document.getElementById('username'),document.getElementById('password'))">
</form>
</body>
</html>
my php
<?php
$server = "localhost";
$username = "root";
$password = "123456";
$dbname = "BlogDb";
// Create connection
$con = mysqli_connect($server, $username, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully2";
$u = $_POST['username'];
$p = $_POST['password'];
setcookie("User_in", $u, time() + (86400 * 30), "/");
// Set session variables
$_SESSION["user_on"] = $u;
$sql= "SELECT username,is_admin FROM User WHERE username ='".$u."' and password='".$p."'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<ul>";
echo "<li>";
echo "Welcome " . $row['username'] . "! How are you today?";
echo "</li><li>";
echo "<a href=logout.php>Log out</a>";
echo "</li></ul>";
}
mysqli_close($con);
?>
What am I doing wrong here?
the input type='sumbit' when clicked where submit this form so you must prevent this default event you can change this type='button'!
document.getElementById('username') where return node n't input value get input value can use
document.getElementById('username').value
below is my change code:
html:
<input type="submit" value="Login" onclick="logIn()">
js:
function logIn(e) {
e = e || window.event;
e.preventDefault();
var u = document.getElementById('username').value,
p = document.getElementById('password').value;
if (u== "" && p== "") {
document.getElementById("user_panel").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("user_panel").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","login.php?u="+u+"&p="+p,true);
xmlhttp.send();
}
}
*** This is a comment as I don't have access to the comment section I am adding as answer******
Hi Matt,
If Ajax is used there is no need to use html-->input-->submit. Use a <button> tag
and then invoke the js function.

Ajax search not Working whereas the XML already running?

I'm a newbie on Ajax, I have tried the tutorial Book, but it did not work. The code is for searching.
This is the script search.htm
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX + MySQL I</title>
<script type="text/javascript" src="search.js"></script>
</head>
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
<p><strong>Hasil Pencarian :</strong></p>
<div id="hasil" />
</body>
</html>
and the JS script search.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp) alert("Obyek XMLHttpRequest tidak dapat dibuat");
else
return xmlHttp;
}
function process()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
nama =
encodeURIComponent(document.getElementById("namaMhs").value);
xmlHttp.open("GET", "search.php?namaMhs=" + nama, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
setTimeout('process()', 1000);
}
function handleServerResponse()
{
if (xmlHttp.readyState == 4)
{
if (xmlHttp.status == 200)
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
nimArray = xmlRoot.getElementsByTagName("nim");
namaMhsArray = xmlRoot.getElementsByTagName("namamhs");
alamatArray = xmlRoot.getElementsByTagName("alamat");
if (nimArray.length == 0)
{
html = "Data tidak ditemukan";
}
else
{
// membentuk tabel untuk menampilkan hasil pencarian
html = "<table border='1'><tr><th>NIM</th><th>Nama
Mhs</th><th>Alamat</th></tr>";
for (var i=0; i<nimArray.length; i++)
{
html += "<tr><td>" + nimArray.item(i).firstChild.data +
"</td><td>" +
namaMhsArray.item(i).firstChild.data +
"</td><td>" +
alamatArray.item(i).firstChild.data +
"</td></tr>";
}
html = html + "</table>";
}
document.getElementById("hasil").innerHTML = html;
setTimeout('process()', 1000);
}
else
{
alert("Ada masalah dalam mengakses server: " +
xmlHttp.statusText);
}
}
}
and the last script in php search.php
<?php
header('Content-Type: text/xml');
echo '<hasil>';
$namaMhs = $_GET['namaMhs'];
mysql_connect("localhost","root","*******");
mysql_select_db("mahasiswa");
$query = "SELECT * FROM mhs WHERE namamhs LIKE '%$namaMhs%'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil))
{
echo "<mhs>";
echo "<nim>".$data['NIM']."</nim>";
echo "<namamhs>".$data['NAMAMHS']."</namamhs>";
echo "<alamat>".$data['ALAMAT']."</alamat>";
echo "</mhs>";
}
echo '</hasil>';
?>
Please help me to fix this script. The XML on search.php is already running but my searching is not. Any help is appreciated.
You are submitting the script on load, before there is even a value in the text field:
<body onload='process()'>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
</form>
You should either add a value to the text field as such:
<input type="text" value="testname" id="namaMhs" />
Or as a better option, add a submit button and don't run the function on load, but rather on submit:
<body>
<h1>Student Search</h1>
<form name="form1">
Masukkan Nama Mahasiswa: <input type="text" id="namaMhs" />
<input type="button" value="Search" onclick="process();" />
</form>
There may be more or even many more problems with your code, I am not looking through it all, but this should get you off to a good start.

Go automatically to another page using html

I have two pages, a html that send value to a php page, and than, the php page returns the result in a div, in the html page.
In the first test it has only a message with error, and in the else clause it must redirect to another html page, so the script in the php page will be shown in html. I've used javascript but it doesn't do it for me.
This is all the codes that i've used:
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
header('location:infosInt.html');
//echo "<script> window.open('infosInt.html')</script>";
//echo "<script> window.location = 'infosInt.html'</script>";
}
EDIT
my html page :
<!DOCTYPE html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script src="jquery-ui.js" charset="ISO-8859-1"></script>
<script src="jquery-1.9.1.js" charset="ISO-8859-1"></script>
<script type="text/javascript" src="jquery.crypt.js" ></script>
<LINK rel="stylesheet" type="text/css" href="android.css">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Login Form</title>
<script>
function connexion(evt)
{
var x=document.getElementById('code');
var cde = x.value;
var str = $().crypt({
method: "md5",
source: cde
});
if (cde=="")
{
// document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
var url ="http://localhost/filename/page.php";
var params="q="+ str;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
};
</script>
</head>
<body>
<div class="login">
<p></p>
<form method="" action="" id= "codeform" onsubmit="connexion();return false;">
<p> &nbsp &nbsp &nbsp &nbsp</p>
<input type="password" id="code" ></p>
<p class="submit"><input type="submit" id="connect" value="Connexion" ></p>
</form>
<div id ="txtHint"></div>
</div>
</body>
</html>
and this is page.php:
<?php
$host = "localhost";
$port = port;
$socket = "";
$user = "root";
$password = "";
$dbname = "base";
$con = new mysqli($host, $user, $password, $dbname, $port, $socket);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$q =$con->real_escape_string($_POST['q']);
mysqli_select_db($con,"ajax_demo");
$sql="query where column ='".$q."'"; // ex
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==0)
{
echo" Code erroné ";
}
else
{
echo"<head><meta http-equiv='refresh' content='5; URL=infosInt.html'></head>";}
mysqli_close($con);
?>
The thing is, you are calling your php script with ajax, so you can't use header('Location: ...') or an html redirection. You should return a flag in your php script and test it when you get the response with javascript :
PHP (at the end of page.php):
if (mysqli_num_rows($result)==0)
{
echo "Code erroné";
}
else
{
echo "redirect"; // the flag
}
Javascript (on the xmlhttp.onreadystatechange event) :
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == 'redirect') { // if flag is sent we redirect
document.location.href = 'infosInt.html';
} else {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}

How to send variable to php with ajax?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function load(thediv, thefile)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP)');
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(thediv) .innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
//connection to db and mysql query
$result = mysql_query($query) or die(mysql_error());
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["idProducts"];
$thing=$row["country"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
mysql_close();
?>
<SELECT id="countrySearch" NAME=countrySearch onchange="load('divtest', 'step2.search.php')";>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
<div id="divtest">
test
</div>
</body>
step2.search.php consists of:
<?php
echo "I want it to store the users selection as a variable for php to use";
?>
The problem I have is I want to store what the user selects from the drop down box and use it in php to do a mysql query using the variable from the user select form to form the WHERE part of the mysql statement. Then use ajax to put new data in "divtest".
How can I store the user selection into a variable then send it to be used in step2.search.php?
See Code Below
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
function load(thediv, thefile,selectvalue)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP)');
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(thediv) .innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET",thefile+"?q="+selectvalue,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<?php
//connection to db and mysql query
$result = mysql_query($query) or die(mysql_error());
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["idProducts"];
$thing=$row["country"];
$options.="<OPTION VALUE=\"$id\">".$thing.'</option>';
}
mysql_close();
?>
<SELECT id="countrySearch" NAME=countrySearch onchange="load('divtest', 'step2.search.php', this.value)";>
<OPTION VALUE=0>Choose
<?=$options?>
</SELECT>
<div id="divtest">
test
</div>
</form>
step2.search.php
<?php
Simple grab this variable
$id = $_GET['q'];
//do your query stuffhere
?>

Categories