Using AJAX to update multiple fields from SQL - php

I'm sure there's an easy answer to this but I've looked everywhere and can't seem to find an answer. I have a dropdown box at the start of a form for office names being populated from an sql table. Depending on which office the user selects, I want the other fields to be filled out with the corresponding information for that record. I used the w3schools php ajax database page as a my guide but it only shows how to update one id in the page and I need to update the input field for address, city, state, zip, and contact.
Here's the relevant code which isn't working. The Code for to trigger the script for the dropdown:
<select name="users" onchange="showOffice(this.value)" class="field select" tabindex="1" >
The Script on that page:
<script>
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").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("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>
And then my getoffice.php code:
<?php
$q=$_GET["q"];
$host="********"; // Host name
$db_username="******"; // Mysql username
$db_password="******"; // Mysql password
// Connect to server and select database.
$con = mysqli_connect("$host", "$db_username", "$db_password");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"*****");
$sql="SELECT * FROM initial_practice WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
$row=mysql_fetch_array($result);
?>
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
<?
mysqli_close($con);
?>
Any help would be greatly appreciated.

Your problem is you aren't using the response text back correctly. This can be fixed in a couple steps. The AJAX request pulls back everything that is printed out from getoffice.php.
First
We're gonna want to change these lines on the on-page script from this:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("practice_name").innerHTML=xmlhttp.practice_name;
document.getElementById("contact").innerHTML=xmlhttp.contact;
document.getElementById("address").innerHTML=xmlhttp.address;
document.getElementById("city").innerHTML=xmlhttp.city;
document.getElementById("state").innerHTML=xmlhttp.state;
document.getElementById("zip").innerHTML=xmlhttp.zip;
}
}
To something a bit easier (I tend to separate readyState and status if statements, my delusional belief that it can randomly fail when combined):
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if(xmlhttp.status==200)
{
eval(xmlhttp.responseText);
}
}
};
Now we're simply evaluating all we get back from the request. Also, note that I added a semi-colon to the end of the onreadystatechange function.
Second
Change the following lines in getoffice.php from:
var practice_name = <? echo $row['practice_name']; ?>
var contact = <? echo $row['contact']; ?>
var address = <? echo $row['address']; ?>
var city = <? echo $row['city']; ?>
var state = <? echo $row['state']; ?>
var zip = <? echo $row['zip']; ?>
To:
document.initialpractice.practice_name.value = <?php echo $row['practice_name']; ?>
document.initialpractice.contact.value = <?php echo $row['contact']; ?>;
document.initialpractice.address.value = <?php echo $row['address']; ?>;
document.initialpractice.city.value = <?php echo $row['city']; ?>;
document.initialpractice.state.value = <?php echo $row['state']; ?>;
document.initialpractice.zip.value = <?php echo $row['zip']; ?>;
Now, when we get the response back from the server, the javascript will evaluate the above response appropriately and fill in the fields. At least it should, providing the query doesn't fail.
Also, you can change mysqli_fetch_array() to mysqli_fetch_assoc(), since you only need the associative array.
Note: We could have solved the problem by just adding eval(xmlhttp.responseText); below the readyState/status checks and removing xmlhttp. in front of all the innerHTML variables.

Finally figured it out. For any of you having the same trouble here's a fix.
php code:
$row=mysqli_fetch_assoc($result);
$name = $row['practice_name'];
$contact = $row['contact_name'];
$address = $row['address'];
$city = $row['city'];
$state = $row['state'];
$zip = $row['zip'];
echo $name."#".$contact."#".$address."#".$city."#".$state."#".$zip;
On-page Script:
function showOffice(str)
{
if (str=="")
{
document.getElementById("practice_name").innerHTML="";
document.getElementById("contact").innerHTML="";
document.getElementById("address").innerHTML="";
document.getElementById("city").innerHTML="";
document.getElementById("state").innerHTML="";
document.getElementById("zip").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)
{
if(xmlhttp.status==200)
{
var data = xmlhttp.responseText.split("#");
var name = decodeURIComponent(data[0]);
var contact = decodeURIComponent(data[1]);
var address = decodeURIComponent(data[2]);
var city = decodeURIComponent(data[3]);
var state = decodeURIComponent(data[4]);
var zip = decodeURIComponent(data[5]);
document.initialpractice.practice_name.value = name;
document.initialpractice.contact.value = contact;
document.initialpractice.address.value = address;
document.initialpractice.city.value = city;
document.initialpractice.state.value = state;
document.initialpractice.zip.value = zip;
}
}
};
xmlhttp.open("GET","getoffice.php?q="+str,true);
xmlhttp.send();
}
</script>

Related

Echo SQL query result to JS [duplicate]

I have a problem with my code.
case like this:
I have a dropdown, if selected "personal" it appeared the new dropdown that contains the data that is retrieved from a database query, if selected "public", then the dropdown disappear.
HTML code like this:
<select name="use" class="dropdown" id="sender" onChange='changeSend()'>
<option value=1>Public</option>
<option value=0>Personal</option>
</select>
<div id='send2'></div>
Query like this:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$id = array();
$name = array();
while($data = mysql_fetch_array($query)){
//id from result database query
$id[$i] = $data['id'];
//name from result database query
$name[$i] = $data['name'];
$i++;
}
?>
JavaScript code like this:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$('#send2').html("<select class='dropdown'><option value='-id from result database-'>-name from result database query-</option></select>");
} else {
$('#send2').html('');
}
}
I dont know how to send value/result ($id[0],$name[0],$id[1],$name[1], etc..) to javascript code(value and name in select options).
In javascript you have to make an ajax call to your php file:
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("send2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
And in your php file you have to echo your data in JSON format:
echo json_encode(array('id'=>$id,'name'=>$name));
UPDATE
in your case use the following code:
(not tested)
php code:
<?php
$query = mysql_query("select * from data where id_user = '$id_user' order by date asc");
$i = 0;
$options = array();
while($data = mysql_fetch_array($query)){
$options[$data['id']] = $data['name'];
}
echo json_encode($options);
?>
javascript code:
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){
var response = JSON.parse(xmlhttp.responseText);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
document.getElementById("send2").innerHTML= select;
}
}
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
xmlhttp.open("GET","yourFile.php",true);
xmlhttp.send();
}
else {
$('#send2').html('');
}
}
USING jQuery
javascript code:
function changeSend() {
var selectBox = document.getElementById("sender");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
if (selectedValue==0) {
$.get("yourFile.php", function(data){
var response = JSON.parse(data);
var select = '<select class='dropdown'>';
for( var index in response ){
select = select + "<option value='"+ index +"'>"+response[index]+"</option>";
}
select += "</select>";
$("#send2").html(select);
});
}
else {
$('#send2').html('');
}
}
The best way would probably be with an ajax call, anyway if you are declaring the script in the same page with the php, you can json encode the array with the options so that you will be able to access it into the javascript, like this:
var optionIds = <php echo json_encode($id); ?>
var optionNames = <php echo json_encode($name); ?>

AJAX not sending parameters over

I'll get straight to the point.
I have a a list which shows everyone in the db who has confirmed that they'll be attending a match. I want the list to change depending on what group is chosen from a select box.
Here's what I have so far: html & AJAX
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("attendYes").innerHTML = "";
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) {
document.getElementById("attendingYes").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","attending.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a group:</option>
<option value="CMA">CMA</option>
<option value="CM1">CM1</option>
<option value="CP2">CP2</option>
<option value="CBBC">CBBC</option>
</select>
</form>
<br>
<div id="attendYes"><b>Person info will be listed here...</b></div>
</body>
</html>
And here is the 'attending.php' page that the choice is meant to be sent to:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('-----','-----','-----','-----');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"handsomejack_co_forms");
$sql="SELECT * FROM stats WHERE activity='".$q."' AND attend='0' ORDER BY username ASC";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>User</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I have changed the sql from ".$q." to a defined choice - like CMA - and it worked, so I know the issue comes from sending q over.
Any ideas as to what could be the problem?
Cheers.
There are two three things i would suggest:
A.)
Change the id of the target div. as you have attendYes and you are using txtHint.
B.) # js
You can try sending the query in the .send() like below.
xmlhttp.open("GET","attending.php",true);
xmlhttp.send("q=" + encodeURIComponent(str));
C.) and # php:
You should not use intval() although i am not very good at php but as per documentation it is something else. so i suggest you to change this:
$q = intval($_GET['q']);
to this:
$q = $_GET['q'];
There's no element like document.getElementById("txtHint"). Update it with correct one:
document.getElementById("attendYes").innerHTML = xmlhttp.responseText;
Why don´t you use Jquerys $.ajax Method instead.
It´s easier to implement and it´s runing in all Major Browsers.

php javascript working to show one value in textbox but cant get the multiple

i have this code below of javascript:
<script>
function showUser(str)
{
if (str=="")
{
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;
}
}
xmlhttp.open("GET","includes/get_user.php?q="+str,true);
xmlhttp.send();
}
</script>
and the php sql script is given below:
<?php
$testQrys = "SELECT * FROM test where status = 1";
$testdbResults = mysql_query($testQrys);
?>
<select size='5' width='925' style='width: 925px' name='users' onchange='showUser(this.value)' multiple>
<?php while($test = mysql_fetch_array($testdbResults )) { ?>
<option class='h4' value='<?php print($test[9]); ?>'>
<?php print($test[5]);echo" ( ";print($test[9]);echo" )"; ?>
</option>
<?php } ?>
</select>
<div id="txtHint"></div>
and the get_user.php code is:
<?php
$q=$_GET["q"];
$con = mysqli_connect('localhost','root','','airways');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM test WHERE m_email = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo "<input type='text' name='staff_no[]' value='".$row['m_staff_no']."'>";
}
mysqli_close($con);
?>
now what i want is when i select one user in the select option it shows the staff no of that user but when i select multiple users it does not show the staff no of other users i select.
please help me with the change in code so i can get the staff no of users like (22344, 44333, 33344, 55443, 11125, 25263) in the text box
waiting for the kind and prompt responses.
Thanks in advance
The error is coming from showUser(this.value). This returns only the first selected element's value. You need to cycle through all options and concatenate them together to make a string that you will be able to send as a parameter.
Change your javascript code to something along those lines. Note that you will need to change your PHP code in order to separate the emails, sanitize them and create a working WHERE m_email IN () query.
You will need to add id="users" to your HTML code first.
var usersList = document.getElementById('users');
var emailString = '';
for (user_counter = 0; user_counter < usersList.options.length; user_counter++) {
if (usersList.options[user_counter].selected) {
emailString += usersList.options[user_counter].value;
}
}
Then send emailString as the parameter to the PHP script. Test it again with log.txt in case you get an error.

Automatic update in JavaScript using PHP code

I'm trying to make auto update on my page using JavaScript and php code to read the data from the server
<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var myVar=setInterval(function(){myTimer()},5000);
}
function myTimer()
{
document.write("<?php
session_start();
$userdata = $_SESSION['views'];
$name = $userdata[1];
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
echo "<br>";echo "<br>";
?>");
}
</script>
</head>
<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
</form>
</body>
</html>
this code works fine but only display what found in the DB first time
but if I add more rows in the DB this new rows doesn't appear on the page.
thanks All
I changed some of my code to be like this
<html>
<head>
<script type="text/javascript">
function timeMsg()
{
var myVar=setInterval(function(){myTimer()},1000);
}
function myTimer()
{
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","phptest.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<input type="button" value="Display alert box in 3 seconds"
onclick="timeMsg()" />
<div id="txtHint"></div></p>
</form>
</body>
</html>
and the php file
<?php
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
?>
and it works fine to me. Thanks for your help
You doin it wrong - the content of your JavaScript function is interpreted on the server and always the same. Your JavaScript function have to send a request to the Server and handle the response.
If you use JQuery this could look i.e. like this
$.get('ajax/script.php', function(data) {
$('.result').html(data);
});
and inside script.php, you could output the database results
javascript is a client side language.
You cannot print out some php with javascript because it happens in the clients browser.
You need to do it on the server, so I think what you want is an ajax request (XMLHttpRequest) to a server-side php script which look like the content of your document.write.
A very simple and nice cross-browser way doing this is to use jquery.ajax.
http://api.jquery.com/jQuery.ajax/
simple tutorial:
http://viralpatel.net/blogs/jquery-ajax-tutorial-example-ajax-jquery-development/
Use Ajax to combine client and server side languages!
steven is right, here is how I would do with jquery:
In javascript:
function myTimer()
{
$.ajax({
url:'path/to/your-script.php',
type:"POST",
data:"ajax=true",
success:callBackMyTimer
});
}
function callBackMyTimer(data)
{
alert(data);
}
In your-script.php
<?php
if(isset($_POST['ajax']) && $_POST['ajax'] == 'true')
{
session_start();
$userdata = $_SESSION['views'];
$name = $userdata[1];
$mysql_host = 'localhost';
$mysql_user = 'root';
$connection = mysql_connect($mysql_host,$mysql_user);
mysql_select_db("twitter2", $connection);
$query = "SELECT * FROM `logindata`";
$result =mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['loginname'];
}
echo "<br>";echo "<br>";
}
exit;
?>

In php, mysql how to run a loop only if record exist

I have a php script which has series of calculations and FORM RELOADS based on user Selection/Inputs, I need to run these only IF a record ADDITION is done to the table and not on FORM RELOADS, how to run a loop with this condition.
my PARTIAL php script bill-detail.php:
HOPE THIS WOULD SUFFICE:
<html>
<head>
<title>Cash Bill Detail</title>
<script language="javascript">
function reload(form)
{
document.location.href = 'bill-detail.php'
}
function showecr(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","billecr.php?q1=" + str,false);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect("localhost","svga","a!##");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("svga", $con);
$user = $_SESSION['user'];
//<!--------------VALIDATIONS ------------------->
echo "<form name='form1'>";
echo "ECR: <input type='text' size='10' maxlength='10' name='ecrn' onchange=\"showecr(this.value);\"><br>";
echo "Product Type";
echo "<select name='product' onchange=\"reload(this.form);\">>";
echo "<option value='Gas'>Gas</option>";
echo "<option value='Others'>Others</option>";
echo "</select>";
echo "</form>";
//---As per user inputs copying value to variables---------------------
$hdr=mysql_query("SELECT * FROM BILLHDR_draft WHERE usr='$user'");
$hdr2=mysql_fetch_assoc($hdr);
$numrows=mysql_num_rows($hdr);
if ($numrows>0)
{
$cust_code=$hdr2['Ac_code'];
$product=$hdr2['prod_desc'];
//--Searching BILL DETAILS TABLE as per the user inputs from BILL HEADER Table------
$recs=mysql_query("SELECT * FROM BILLDTLS WHERE Ac_code='$cust_code' AND Prod_desc='$product'");
while ($rec2=mysql_fetch_assoc($recs))
{
mysql_query("INSERT INTO DEMURAGE (DC_No, DC_date, Ac_code, Product_Desc) VALUES ('$rec2[dc]', '$rec2[dcdate]', '$rec2[accode]', '$rec2[product]'");
}
}
mysql_close($con);
?>
You can add a boolean variable before the loop that you can use to track on whether a record has been added already. The following code is largely concept being that you didn't provide much of an example of code yourself, but hopefully you get the idea.
// Set to false initially
$recordAdded = FALSE;
if( $num_rows > 0 && $recordAdded == FALSE )
{
// Code to execute
// Set value to to TRUE after initial successful execution
$recordAdded = TRUE;
}

Categories