auto fill text field after pressing enter key - php

i got an useful tutorial where if you input 'id' [or first 1-2 letter of your id], the rest of form's field will filled automatically by pulling data from mysql database. this thing will happen without pressing ENTER key! now, what i'm trying to do is, i'll input the full 'id' & press ENTER key to fill the rest of form's field! what modification would need for this code below? here is my index.html file:
<html>
<body>
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var http; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
http = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var url = "getagentids.php?param=";
var idValue = document.getElementById("agid").value;
var myRandom = parseInt(Math.random()*99999999); // cache buster
http.open("GET", "getagentids.php?param=" + escape(idValue) + "&rand=" + myRandom, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
function handleHttpResponse() {
if (http.readyState == 4) {
results = http.responseText.split(",");
document.getElementById('agfn').value = results[0];
document.getElementById('agsal').value = results[1];
document.getElementById('agtel').value = results[2];
document.getElementById('agid').value = results[3];
}
}
}
</script>
<form name="schform">
<table>
<tr>
<td>Contact ID:</td>
<td><input id="agid" type="text"
name="contactid" onKeyUp="ajaxFunction()"></td>
</tr>
<tr>
<td>Tel Number:</td>
<td><input id="agtel" type="text"
name="contacttel"></td>
</tr>
<tr>
<td>Name:</td>
<td><input id="agfn" type="text"
name="contactfullname"></td>
</tr>
<tr>
<td>Salutation:</td>
<td><input id="agsal" type="text"
name="contactsalutation"></td>
</tr>
<tr>
<td><input type="reset" value="Clear"></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>
and here is my getagentids.php file:
<?php
error_reporting(0); // turns off error reporting
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("contactdetail", $con);
mysql_select_db("contactdetail");
$param=$_GET['param'];
if (strlen($param) > 0) {
$result = mysql_query("SELECT * FROM contact
WHERE contactid LIKE '$param%'");
if (mysql_num_rows($result) == 1) {
while ($myrow = mysql_fetch_array($result)) {
$agentname = $myrow["contactfullname"];
$agenttel = $myrow["contacttel"];
$agentsal = $myrow["contactsalutation"];
$agentid = $myrow["contactid"];
$textout .= $agentid . ", " . $agentname . ", " . $agenttel . ", " . $agentsal;
}
} else {
$textout = " , , ," . $param;
}
}
echo $textout;
?>

first create a javascript function to detect if the Enter key is pressed and call the ajaxFunction from within it:
function run(e) {
if (e.keyCode == 13) {
ajaxFunction();
return false; //disable the default Enter behavior
}
return true;
}
change the onKeyUp="ajaxFunction()" call in the Contact ID text input into onKeyUp="run()"

You can change your ajaxFunction like (just paste the code at the top of your ajaxFunction)
function ajaxFunction(e){
var e=e || window.event;
var keycode=e.which || e.keyCode;
if(keycode!==13 || (e.target||e.srcElement).value=='') return false;
// rest of your code
}​
And change your onKeyUp with this (notice event in the argument)
<input id="agid" type="text" name="contactid" onKeyUp="ajaxFunction(event)">​
Just for an idea.

Related

While loop updation value

I am developing online attendance.But I stuck in while loop condition
I want to show my code first
<tbody>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value = "<?php echo $ro22['user_id'] ?>"/></td>
<td><?php echo $ro22['first_name'] ?> <?php echo $ro22['last_name'] ?></td>
<td><?php echo $ro22['parent_contact'] ?></td>
<td><input type="button" value="<?php echo $ro22['ai'] ?>" id="pres" name="pres" onclick="return change(this);" onBlur="checkAvailability()" class="w3-button w3-teal"/></td>
</tr>
<?php } ?>
</tbody>
This is output
What I want
I want update present,absent value based on 101,102,103... value
I tried many but failed. Please help me out
Thanks in advance
You need to place a call to the page on a click and pass the user_id. This is easy to do with jQuery:
function change(row) {
$.post('thispage.php', { user_id: $(row).val() }, function(){ window.location.reload(); } );
}
And then receive the post in the PHP:
if (!empty($_POST['user_id'])) {
/* toggle admission status */
}
After the request completes and the status is toggled, the page will reload.
Here is a general example. It's consisted of your PHP program (the AJAX sender) which I rewrote to be they way I think you wanted, a javascript file (containing the AJAX function) and another PHP file (the AJAX request receiver).
You can get different use-cases by altering the database query in the receiving PHP file.
Javascript file (AJAX):
// Send the `id` of the element
function checkAvailability(id)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
// This `if` underneath is success. It means we got a response back
if (this.readyState == 4 && this.status == 200)
{
if(this.responseText == "OK")
{
alert('ID: ' + id + ' changed. Response: ' + this.responseText);
document.getElementById("demo").innerHTML = 'The student has been updated.';
}
else if(this.responseText == "Not OK")
{
alert('Something went wrong with id: ' + id);
}
}
};
// For example you send a request to attendance.php sending `id` info
// - attendance.php just needs to echo the response to answer back
xhttp.open("GET", "attendance.php?id=" + id, true);
xhttp.send();
}
Main PHP page (the file that sends the request):
// U need jQuery to be able to send AJAX requests. Copy this, add to your html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$database = new Database();
$db = $database->getConnection();
$user = new User($db);
$stmt = $user->atten();
echo '<table>
<tr>
<th>Student ID</th>
<th>Student name</th>
<th>Phone number</th>
<th>Today\'s attendance</th>
</tr>';
while($ro22 = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>
<td><input name ="uname" id ="uname" onBlur="checkAvailability2()" style ="border:none" value="'.$ro22['user_id'].'"/></td>
<td>'.$ro22['first_name'].' '.$ro22['last_name'].'</td>
<td>'.$ro22['parent_contact'].'</td>
<td><input type="button" value="'.$ro22['ai'].'" id="pres" name="pres" onclick="change(this.id);" onBlur="checkAvailability(this.id)" class="w3-button w3-teal"/></td>
</tr>';
}
echo '</table>';
?>
The receiver file:
<?php
$conToDatabase = ... // Here goes DB connection data
if(isset($_GET['id']) && ctype_digit($_GET['id']))
{
$clean['id'] = $_GET['id'];
}
// Query your DB here using variable $clean['id'] as ID
$querySuccess = ...
// if query successful echo 'OK';
// else echo 'Not OK';
?>

fetching data from mysql using Ajax

I am trying to calculate the sum of prices sold between two specific dates. My query is okay but it isn't returning anything when i use in PHP. It works when i directly execute in database.
Here is my code,
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var queryString = "?startdate=" + startdate ;
queryString += "&enddate=" + enddate;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Start Date: <input type='date' id='startdate' /> <br />
End Date: <input type='date' id='enddate' /> <br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Here is my PHP Code
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "temp";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
//build query
$query = "SELECT SUM(price) FROM ajax_example WHERE daterec >= '$startdate'";
$query .= " AND daterec <= '$enddate'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
echo "Query: " . $query . "<br />";
?>
What am i doing wrong? Thank you in advance
Satisj Rajak! you are right!
check mysql_query
first, this function will be deprecated after PHP 5.5.0, try to dont use it.
second, to get the results you have "transform" the variable in an associative array using this example code:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field_name'];
}
and if you use ajax, try to send a json format response.
hope my answer help you.
In your button click handler, try returning false. My first instinct would be that your form is being submitted by that button and your AJAX request is never being completed.
<input type='button' onclick='ajaxFunction(); return false;' value='Query MySQL'/>
If that doesn't solve it, open up google chrome and the network debugging tools. When you execute the AJAX request, check the request and response data.
In addition, you should optimize your JavaScript to be more effective.
Here is a snippet of JS which could be used in your situation:
var get = function(path) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', path);
request.onload = function() {
if (request.status == 200)
resolve(request.response);
else
reject(Error(request.statusText));
};
request.onerror = function() {
reject(Error(request.statusText));
};
request.send();
});
}
function fetchQueryResults() {
get('/test.php').then(function(response) {
var el = document.getElementById('results');
el.innerHTML = response;
}).catch(function(error) {
// Something went wrong, handle the error here
});
return false;
}

Why does not insert these values in database using Ajax

I used tutorialspoint to guide me to insert the values from input text into the db, but unfortunately, it will not insert to the database. Is this correct implementation for AJAX?
Here's my index.php
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gen = document.getElementById('gen').value;
// var queryString = "?age=" + age ;
queryString += "&fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
First Name: <input type='text' id='fname' /> <br />
Last Name: <input type='text' id='lname' /> <br />
Sex:
<select id='gen'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "my_db";
$con = new mysqli($dbhost, $dbuser, $dbpass,$dbname);
$query="INSERT INTO table1 (fname, lname, gender)
VALUES
('$_GET[fname]','$_GET[lname]','$_GET[gen]')";
$qry_result = $con->query($query);
?>
change your code to the bellow
var queryString;
queryString = "fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php?" + queryString, true);
and make sure ajax.php is in the same folder as index.php
Try this in ajax.php:
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$gen=$_GET['gen'];
$query="INSERT INTO table1 ('fname', 'lname', 'gender')
VALUES('$fname','$lname','$gen')";
Declare Form method="POST"
and
$query="INSERT INTO table1 (fname, lname, gender) VALUES
('".$_POST['fname']."','".$_POST['lname']."','".$_POST['gen']."')";

sending multiple parameters to mysql database

this code is to autosave form in mysql database
i am unable to send multiple parameters
the main issue is here
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
php code
<?php
$user_id = 1;
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$saved_text = mysql_real_escape_string($_POST["saved_text"]);
$sql = "UPDATE asave SET saved_text = '".$saved_text."' ";
$sql.= "WHERE user_id = $user_id";
mysql_query($sql) or die(mysql_error().$sql);
echo "Your data has been saved ".date("h:m:s A");
exit;
}
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
html code
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input id="test" type="text" value="<?php echo $content;?>">
<input type="submit" value="save now" />
</form>
</body>
You're not posting saved_text in your javascript. You're posting params (that is missing a delimiter).
To post multiple parameters check this post: Posting parameters to a url using the POST method without using a form

AJAX: Display Chart data as IMG

I want to show a (chart) image using AJAX. I'm not sure what's wrong, but I'm getting the following 'error' and an incorrect image:
"|xtt�I������{饗BBBN�:��}�̛7oРA7n�0l߾} QQQIIIeee�aLHH������ضm��wm���v��U�&�Z���o�# Art]]]����{���#""��'���v|�ҥKqqq���ح�~;11�ȑ#����޺u��ںm6O�7o���.��ի��?~Ȑ!��~��۷��O�0A.�cv�����TäR)�� ����˗{N����5<��&0� ���ҷo��#�NХ<0�j�0��=���]�t��۷�j�T*5�\����۳g�F�����gfm���ݻ�'OF....."
The code I'm using:
ajax_select.php:
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="test_ajax.php";
url=url+"?q="+str+"&a="+age;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint").innerHTML="<IMG SRC='" + xmlhttp.responseText + "'/>";
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
</head>
<body>
<form>
<select id="users" name="users">
<option value="">Select a person:</option>
<?php
$con = mysql_connect(***);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<select id="age" name="age">
<option value="">Select a person:</option>
<?php
$con = mysql_connect('***');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***", $con);
$sql="SELECT ***";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
}
mysql_close($con);
?>
</select>
<input type='button' value='Refresh Data' onclick="showUser(document.getElementById('users').value,document.getElementById('age').value)">
</form>
<br><br>
<div id="txtHint"><b>chart will be displayed here.</b></div>
</body>
</html>
ajax_select_NEW.php:
<script type="text/javascript">
var xmlhttp;
function showUser(str,age)
{
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
</script>
test_ajax.php:
<?php
/* Include the pData class */
include("class/pData.class.php");
include("class/pDraw.class.php");
include("class/pImage.class.php");
/* Get user from AJAX resquest */
$user_id=$_GET["q"];
$q=$_GET["q"];
$a=$_GET["a"];
/* Create the pData object */
$MyData = new pData();
/* Connect to the MySQL database */
$db = mysql_connect("***");
mysql_select_db("***",$db);
/* Build the query that will returns the data to graph */
$Requete = "
SELECT ***
";
***
/* Render the picture (choose the best way) */
$myPicture->autoOutput("examples/example.drawBarChart.png");
?>
I have hard coded the variables in the SQL code for now. (in test_ajax.php) So if I open that page it just shows the correct chart image. But when I open the ajax_select.php page I get the error in the picture above. (so it's not a wrong chart code information, since it's okay if I open the php page directly)
I have searched a lot, but can't find the solution. Hopefully someone can help me here, would be much appreciated!
You're trying to put the binary image data into the src attribute of the img. This attribute is meant for the source URL of the image, you can do this entirely without XmlHttpRequest, just insert your image by using test_ajax.php as the src.
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
As for the broken rendering of the image, have you included a Content-Type-header?
header('Content-Type: image/png');
$myPicture->autoOutput("examples/example.drawBarChart.png");
This is what ajax_select_NEW.php should look like:
<script type="text/javascript">
function showUser(str, age) {
var url = 'test_ajax.php';
url += '?q=' + str + '&a=' + age + '&sid=' + Math.random();
document.getElementById('txtHint').innerHTML = '<img src="' + url + '" />';
}
</script>

Categories