How to send value from php to other php page without submitt? - php

I have made a deep search and tried a lot to send value automatically to other php page. I don't know is it possible or not. But if someone knows then please kindly tell me.
Here is the code what I am trying:
t.html // for browsing
<html>
<head>
<style>
#boox{
overflow:auto;
width:600px;
height:400px;
}
</style>
<script>
alert("hello");
</script>
<script>
function pict(str)
{ alert("hel");
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
xmlhttp = new XMLHttpRequest();
var picInput = document.getElementById('userfile').value;
var uploadpic = document.getElementById('upload').value;
document.getElementById('usf').innerHTML = picInput;
document.getElementById('upic').innerHTML = uploadpic;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// var resp = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
// alert(resp);
} alert("a");
xmlhttp.open( "POST", "show.php.php?q"="+str, true); //POST Because you use $_POST in php
xmlhttp.send();// not happening
}
}
</script>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="take.php">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<input name="upload" type="submit" onChange ="pict(this.value)" class="box" id="upload" value=" Upload ">
</tr>
</table>
</form>
<div id="txtHint">here div </div>
</body>
</html>
take.php // this is the page that i am trying to send without submit to other php
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con=mysql_connect("localhost","root",'');
mysql_select_db("project",$con) or die("error db");
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close($con);
echo "<br>File $fileName uploaded<br>";
// i am trying to send parameter that is "fileName" through header to show.php
header("location:show.php");
}
?>
show.php
<HTML>
<head>
<script>
#showpic
{
overflow:auto;
width:600px;
height:400px;
border:#000000 2px solid;
}
</script>
<script>
function changeThis(){
xmlhttp = new XMLHttpRequest();
var formInput = document.getElementById('theInput').value;
var title = document.getElementById('title').value;
/* formInput will be undefined */
document.getElementById('newText').innerHTML = formInput;
document.getElementById('ntitle').innerHTML = title;
/* also undefined */
// var xmlHttp = null;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var resp = xmlhttp.responseText;
document.getElementById("txtHint").innerHTML=resp;
alert(resp);
}
}
//alert("yes");
xmlhttp.open( "POST", "file2.php?q=+" , true); //POST Because you use $_POST in php
xmlhttp.send('theInput='+ encodeURIComponent(formInput) +
'&newText='+ encodeURIComponent(formInput) +
'&ntitle='+ encodeURIComponent(title));
}
</script>
</head>
<div id="showpic">
<?php
//header("location:event.php");
echo"heloo00";
$con=mysql_connect("localhost","root",'');
mysql_select_db("project",$con) or die("error db");
$sql="select * from upload";
$query=mysql_query($sql);
while($row=mysql_fetch_array($query))
{
$image=$row ['name'];
echo '<img src="data:image/png;base64,' . base64_encode( $row['content'] ) . '" />';
}
?>
</div>
<body>
<p> <span name id='ntitle'></span> </p>
<p>You wrote: <span id='newText'></span> </p>
<body>
<form method="GET" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Title :<textarea name="des" rows="1" cols="25" required></textarea>
<br>
Write :<textarea name="cht" rows="25" cols="25" required >write</textarea>
<input type=submit name="submit" onclick='changeThis() value ='Post event'/>
</form>
<?PHP
if(isset($_GET['submit']))
{
$u=$_GET['des'];
$k=$_GET['cht'];
$q="insert into event (title,detail) value('$u','$k')";
$con=mysql_connect("localhost","root","") or die ("connection Error");;
mysql_select_db("project",$con) or die ("db Error");
$r=mysql_query($q) or die ("Query Error");;
}
?>
</body>
</html>

To share data between php documents without explicitly passing that data, you can store it in a $_SESSION variable. This makes data available between php scripts when they are access by a user during the same session. Sessions are way to much to explain here, but you can read up on them in the PHP Manual section on session handling. When you have more specific questions, post them here and we can help you with them.

Related

PHP setting JSON values to Textboxes

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"}]';
?>

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.

PHP and AJAX login form

Hello
I know this subject has been proposed before, but no one has done the AJAX manipulation standard like i did. I'm newbie to AJAX and jQuery
The problem I have here is that I'm not sure that the js function "ajaxPostCallManip()" reaches to "login.php"!!
I've made a couple of alert()s but nothing appears...Please help
HTML CODE
<link rel="stylesheet" type="text/css" href="jQuery-Files/jquery.mobile-1.3.1.css"/>
<script type="text/javascript" src="jQuery-Files/jquery-2.0.2.js"></script>
<script type="text/javascript" src="jQuery-Files/jquery.mobile-1.3.1.js"></script>
<script type="text/javascript" src="js/ajax.js"></script>
<div data-role="page" id="loginDialog">
<header data-role="header">
<h3 style="margin-left: auto; margin-right: auto;">Login or <a href="#regpage"
data-transition="flip">Register</a></h3>
</header>
<div data-role="content">
<form method="POST" action="" onsubmit="check_login(); return false;">
<fieldset data-role="contolgroup">
<div data-role="fieldcontain">
<label for="login_username">Username</label>
<input type="text" name="login_username" id="login_username"
placeholder="username" />
<label for="login_pwd">Password</label>
<input type="password" name="login_pwd" id="login_pwd"
placeholder="password" />
<div style="margin: auto; text-align: center;">
<label for="login_submit" class="ui-hidden-accessible">
Submit</label>
<button onclick="this.form.submit()" value="Submit"
data-inline="true"></button>
<span class="error" id="login_err" name="login_err"
style="display: none; font-size: 12px;
text-align: center;">status</span>
</div>
</div>
</fieldset>
</form>
</div>
</div>
js CODE
// AJAX Call handler using method="POST"
function ajaxPostCallManip( str, url, toDoFunc )
{
var xmlhttp; // Request variable
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
function check_login()
{
// Construct the POST variables [username, password]
var postStr = "username=" + $('#login_username').val() + "&"
+ "password=" + $('#login_pwd').val();
// Call the general purpose AJAX Handler Function
ajaxPostCallManip(postStr, "login.php", function()
// toDoFunc to be performed when server response is ready
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
{
alert(xmlhttp.responseText);
switch(xmlhttp.responseText)
{
case "1":
$('#login_err').css({'color':'green','display':'block'})
.html('Successful Login');
break;
case "2":
$('#login_err').css({'color':'red','display':'block'})
.html('incorrect username/password')
break;
case "3":
$('#login_err').css({'color':'red','display':'block'})
.html('please fill in all fields')
break;
}
}
});
}
PHP CODE
<?php
include('dbManip.php');
echo '<script> alert("Inside login.php"); </script>';
$username = $_POST['username'];
$password = $_POST['password'];
// Just to check that the POST variables arrived safely
echo "<script> alert('username = ' + $username); </script>";
if(!empty($username) && !empty($password))
{
// Fetch data from database
$query = "
SELECT username,password
FROM users
WHERE username = '$username' and password = '$password';
";
// Execute query
$res = mysql_query($query);
// If there is a match for the credentials entered with the database
if(mysql_num_rows($res) == 1)
{
// Fetch information and double check credentials
while($row = mysql_fetch_assoc($res))
{
$db_username = $row['username'];
$db_password = $row['password'];
}
// Compare results with user input
if( $username == $db_username && $password == $db_password)
{
// Credentials are correct - response = 1
echo '1';
}
else
{
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// There is no match in the database
// Credentials are incorrect - response = 2
echo '2';
}
}
else
{
// If one or both fields are empty - response = 3
echo '3';
}
?>
First, you need to rewrite the submit button:
<button type="Submit" value="Submit"data-inline="true"></button>
Second, move the variable from a function that would make it a global:
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}
I think you need to rewrite this line of code:
<form method="POST" action="" onsubmit="check_login(); return false;">
And change it to:
<form method="POST" action="login.php" onsubmit="check_login(); return false;">
Make sure to save login.php in the same folder as your html file.
remove the method="post" and action="" attribute from the form tag because you are defining it in the ajax call
<button type="Submit" value="Submit"
var xmlhttp; // Request variable
function ajaxPostCallManip( str, url, toDoFunc )
{
if( window.XMLHttpRequest ) // For modern browsers
xmlhttp = new XMLHttpRequest;
else // For old browsers
xmlhttp = new ActiveXOBject("Microsoft.XMLHttp");
xmlhttp.onreadystatechange=toDoFunc;
xmlhttp.open("POST", url, true);
xmlhttp.send(str);
}

Showing ajax content in same page without page load

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>

Categories