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>        </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;
}
}
Related
This is the html file.
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
return;
} else {
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)
{
var doc = window.document.createElement("doc");
var a = JSON.parse(xmlhttp.responseText);
document.getElementById("stuname").value=a.first;
document.getElementById("branch").value=a.second;
document.getElementById("year").value=a.third;
document.getElementById("category").value=a.four;
}
}
xmlhttp.open("GET","test2.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
Roll Number:<br>
<input type="text" name="rollno" id="rollno" onblur="showUser(this.value)">
<br>
Student Name:<br>
<input type="text" name="stuname" id="stuname" value="">
Branch:<br>
<input type="text" name="branch" id="branch" value="">
Year:<br>
<input type="text" name="year" id="year" value="">
Category:<br>
<input type="text" name="category" id="category" value="">
</form>
<br>
</body>
</html>
test2.php file
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$q = $_GET['q'];
$con=mysqli_connect("localhost","root","neel","sitams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT rollno,stuname,branch,category FROM studet where rollno='".$q."' and academic='2014-2015'";
if ($result=mysqli_query($con,$sql))
{
while ($obj=mysqli_fetch_object($result))
{
$queryResult[] = $obj->rollno;
$queryResult[] = $obj->stuname;
$queryResult[] = $obj->branch;
$queryResult[] = $obj->category;
}
}
$textboxValue1 = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
echo json_encode(array('first'=>$textboxValue1,'second'=>$textboxValue2,'third'=>$textboxValue3,'four'=>$textboxValue4));
?>
</body>
</html>
I could not able to load values to the text boxes where is fault. Even I have seen stackoverflow but I could not able to get it. when I type test2.php by passing rollno value to q it will display data but when I pass a value from html it could not able to set the values to the textbox fields.
Remove any html tags from test2.php . An ajax document does not need any html tags.
Hi this one will be helpful to you .
<html>
<head>
</head>
<body>
<input type="button" onclick="showUser('ok');" value="click to ru me" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function showUser(str)
{
if (str=="")
{
return;
}
else
{
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//var doc = window.document.createElement("doc");
var parsed = JSON.parse(xmlhttp.responseText);
for(var x in parsed)
{
var First=parsed[x].first;
var Second=parsed[x].second;
var Third=parsed[x].third;
var Fourth=parsed[x].fourth;
console.log("first="+First+" second="+Second+" third="+Third+" fourth="+Fourth);
document.getElementById("stuname").value=parsed[x].first;
document.getElementById("branch").value=parsed[x].second;
document.getElementById("year").value=parsed[x].third;
document.getElementById("category").value=parsed[x].fourth;
}
}
}
xmlhttp.open("GET","phpex.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input type="text" id="stuname" />
<input type="text" id="branch" />
<input type="text" id="year" />
<input type="text" id="category" />
</body>
</html>
Ajax File Name phpex.php . ajax page code is below
<?php
echo '[{"first":"1111","second":"2222","third":"3333","fourth":"4444"}]';
?>
So I've been learning to use xmlhttp and I couldn't get this simple script working:
<!DOCTYPE html>
<html>
<head>
<script>
function print_stuff(){
document.getElementById("two").innerHTML="working";
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("one").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","index.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("email=" + document.getElementByName("email").value + "&name="+ document.getElementByName("name").value);
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Name: <input type="text" name="name"/></br>
Email:<input type="text" name="email"/></br>
<button onclick="print_stuff()">Button</button></br>
<span id="one"></span>
<div id="two"></div>
</body>
</html>
And the index.php:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
echo "Name: ",$name,"</br> Email: ", $email;
?>
The idea behind this is very simple: you get user's name and email and print it out using "POST" method. I have a sense it's a very simple mistake, though I can't find it... Any help appreciated!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
Name: <input type="text" name="name" id="name"/></br>
Email:<input type="text" name="email" id="email"/></br>
<button onclick="print_stuff()">Button</button></br>
<span id="one"></span>
<div id="two"></div>
</body>
</html>
<script>
function print_stuff(){
var email = document.getElementById("email").value;
var name = document.getElementById("name").value;
if (window.XMLHttpRequest)
{
var xmlhttp=new XMLHttpRequest();
}
else
{
var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
array = new Array(4);
array = xmlhttp.responseText.split("##"); //slicing string into array to get separate result
document.getElementById("one").innerHTML = array.slice(0,1);
document.getElementById("two").innerHTML = array.slice(1,2);
}
}
xmlhttp.open("GET","index.php?email="+email+"&name="+name,true);
xmlhttp.send();
}
</script>
index.php:
<?php
$name = "Name: ".$_GET["name"];
$email = "Email: ".$_GET["email"];
echo $name."##".$email;
?>
I am trying to send ID and sent from ajax_form.php to ajax_test.php()
my ajax_form.php is:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
//var sent = document.getElementsByName('sent')[0].value || '';
//var id = document.getElementsByName('id')[0].value || '';
var sent = form.elements['sent'].value;
var id = form.elements['id'].value;
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(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" />
<input type="" name="id" style="display: none"/>
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label><input type="text" name="id"><br>
<label>Enter the sentence:<input type="text" name="sent"></label><br />
</pre>
<input type="submit" class="submit" value="submit" name="update"/>
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
and ajax_test.php is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body >
<?php
$s = $_POST['sent'];
echo "Entered sentence : $s";
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
//database stuff
mysqli_close($con);
}
// -------------------------------UPDATE --------------------------
if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
// you say update but you are actually inserting below
$s = $_POST['sent'];
$flag = 1;
echo "Entered sentence : $s";
//database stuff
mysqli_close($con);
}
?></html > </body >
Neither content outside if() get executed correctly nor if
I get error:
Notice: Undefined index: sent in /opt/lampp/htdocs/test/ajax_test.php on line 6
Just Entered sentence : get printed.
Where is the problem in post? Ideally I should able fetch id and sent !
You need to set the Content-Type on the request before sending it to application/x-www-form-urlencoded. See documentation.
My ajax_form.php page is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script>
function showUser(form, e) {
e.preventDefault();
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
if (sent==""){
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(e) {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value);
}
</script>
<form action="ajax_test.php" method="POST">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)">
</form>
<br>UPDATE <br>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
Enter the ID : <input type="text" name="id"><br>
Enter the sentence: <input type="text" name="sent"><br>
</pre>
<input type="submit" class="submit" value="submit" name="update" >
</form> <br>
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
and ajax_test.php is:
<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body >
<?php
// $q = $_POST["q"];
// you never process the $q var so i commented it
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;#]*)/',
shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
$matches)){ //Values stored in ma.
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
}
echo "<br>",
"Positive count :$x",
"<br>",
"Negative count :$y",
"<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2
(id,sent,pcount,ncount,flag)
VALUES
('','".$_POST['sent']."',' $x ','$y','$flag')";
if (mysqli_query($con, $sql1)) {
echo "1 record added";
} else {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
// -------------------------------UPDATE --------------------------
if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
// you say update but you are actually inserting below
$s = $_POST['sent'];
$flag = 1;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;#]*)/',
shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
$matches)) //Values stored in ma.
{
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
}
echo "<br>",
"Positive count :$x",
"<br>",
"Negative count :$y",
"<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2
(id,sent,pcount,ncount,flag)
VALUES
('','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes
if (mysqli_query($con, $sql1)) {
echo "1 record added";
} else {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?></html > </body >
In form1 I have put function call on button click event, which works fine. But on button click it load the page and redirects to ajax_test.php. can we say it proper use of ajax?
In second form I have kept function call in form itself and coded as required in script. But on button click on action takes place. Is it wrong function call or any other mistake?
How can I show result without page load(refresh) in both cases?
The problem is with your sent parameter - it's looking for an input named "sent", which doesn't exist. And then, if it's not set, it's exiting the showUser function.
Here's the offending snippet (which I removed below):
if (sent==""){
document.getElementById("txtHint").innerHTML="";
return;
}
In addition to that problem, you also had no close </head> or open <body> tags, which in themselves are not the problem, but a pretty major formatting issue. Also, always put a type on your <script> element. Finally, you should close <meta />, <input /> and <br /> elements inline. Formatting your code consistently (sibling elements on their own lines, 4-space tabs for each heirarchical level) helps you find little formatting issues like the missing open body, etc.
That said, this works for me:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
<meta content="utf-8" http-equiv="encoding" />
<script type="text/javascript">
function showUser(form, e) {
e.preventDefault();
var xmlhttp;
var submit = form.getElementsByClassName('submit')[0];
var sent = document.getElementsByName('sent')[0].value || '';
var id = document.getElementsByName('id')[0].value || '';
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(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
}
</script>
</head>
<body>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<label>Enter the sentence: <input type="text" name="sent"></label><br />
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)" />
</form>
<h4>UPDATE</h4>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
<label>Enter the ID:</label>
<input type="text" name="id"><br>
<label>Enter the sentence:</label>
<input type="text" name="sent"><br>
</pre>
<input type="submit" class="submit" value="submit" name="update" />
</form>
<br />
<div id="txtHint">
<b>Person info will be listed here.</b>
</div>
</body>
</html>
I am having trouble to get my code working. As a user types in a username it checks the database to see if it exists and if it does sets the <P id="checkusername"> to "Username Taken." and if not sets it to "Not Taken." I can't see why my code is not working.
1-register.html
<html>
<body>
<CENTER>
<form name="register" action="register.php" method="post">
Username: <input type="text" name="username" onkeyup="checkUsername(this.value)" />
<P id="checkusername">checker</P>
<input type="submit" value="Login" />
</form>
</CENTER>
<script type="text/javascript">
function checkUsername(){
var xmlhttp;
var username=document.forms["register"]["username"].value;
if(username.length==0){
document.getElementById("checkusername").innerHTML="Empty";
return;
}
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "login.php";
var params = "header=checkusername&username="+username+"&password="";
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.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("checkusername").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send(params);
}
</script>
</body>
</html>
2-register.php
<?php
$header = $_POST["header"];
if(header=="checkusername"){
checkusername($_POST["username"]);
}else{
echo "No match: " . $header;
}
function connection(){
$con = mysql_connect(URL, username, password);
if(!$con){
die('Could not connect: ' . mysql_error());
}
return $con;
}
function checkusername($username){
$con = connection();
mysql_select_db(database, $con);
$result = mysql_query("SELECT * FROM users WHERE username = \"" . $username . "\";");
while($row = mysql_fetch_array($result)){
if(($row['username'] == $username)){
echo "Username Taken.<br/>";
return;
}
}
echo "Not Taken.";
}
mysql_close();
?>
Read this Blog http://papermashup.com/jquery-php-mysql-username-availability-checker/