Automatic update in JavaScript using PHP code - php

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;
?>

Related

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.

Using AJAX to update multiple fields from SQL

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>

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.

ajax get method

UPDATE... this is the code I've implemented from the tutorial, within chrome dev tools in network i can see in header the variable is being sent and in preview i can see the drop down menu however it is not inserted into the loaded webpage
<script type="text/javascript">
$(document).ready(function() {
$('#selectEvidence').change(function(){
alert($(this).val());
});
});
function evidencesearch(str)
{
if (str=="")
{
document.getElementById("case").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("case").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","searchfunction.php?variable="+str,true);
xmlhttp.send();
}
</script>
<?php
$variable = $_GET['variable']; //used for second drop down menu
//echo "test test test $variable";
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db = 'fid';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
mysql_select_db($db);
echo '<label class="input" for="case" type="input">Specify: </label><select id="case" name="case"><option=value"null"></option>'; //Insert to loaded page
$resource = mysql_query("SELECT $variable FROM `evidence`");
if($resource && mysql_num_rows($resource)) {
while ($row = mysql_fetch_assoc($resource)){
echo '<option value="'.$row[$variable].'">'.$row[$variable].'</option></select>';//Insert to loaded page
}
}
mysql_close($conn)
?>
I think your problem sticks within POST/GET functions; try to call them synchronously and paste please the w3schools tutorial's link you mentioned. Maybe I can help you then by writing more detailed answer.
Cheers.

Javascript PHP synchronisation problem

I want to call a javascript function with parametars that are stored in MySQL. All this is happening on an onClick event.
Here is the javascript code:
function getFile() {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", "gmap.php", false);
AJAX.send("searchField=" + searchField.value);
return load(AJAX.responseText);
} else {
return false;
}
}
So, the gmap.php is echoing the parameters for the javascript load function. But it doesn't load the parameter because the function is called before the MySQL query in gmap.php is executed. I've tried sync and async AJAX.
If I try to call the javascript function from PHP, it doesn't get executed, because it is called on a onClick event, and this is inside a div.
Please help me, I'm doing this over a week now. I've tried everything.
Here is the php code with the MySQL query:
<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";
//connect sql
mysql_connect($dbhost, $dbuser, $dbpass);
//select db
mysql_select_db($dbname) or die(mysql_error());
//retrieve data
//$city=$_GET['city'];
//escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
//query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {
die("Database query failed: " . myql_error());
}
while($row=mysql_fetch_array($result)) {
$lat=$row['citystart'];
$lng=$row['cityend'];
}
echo $lat;
echo ", ";
echo $lng;
?>
pass the php url together with the variable to search.
if (AJAX) {
var url = "gmap.php?searchField="+ searchField.value;
AJAX.open("POST", "url", false);
AJAX.send(true);
return load(AJAX.responseText);
}
I think searchField.value does not contain anything.
Replace
searchField.value
With this
document.getElementById('searchField').value
assign the searchField as an id to the search box.
add this code after AJAX.open and before AJAX.send.
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", searchField.value.length);
AJAX.setRequestHeader("Connection", "close");
I have succesfully tested this
<html>
<head>
<script>
function load(response) {
alert(response);
}
function getFile() {
if (window.XMLHttpRequest) AJAX=new XMLHttpRequest();
else AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX) {
var params = "foo=" + searchField.value;
AJAX.open("POST", "http://localhost/test.php", true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", params.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.onreadystatechange = function() {
var ok;
try { ok=AJAX.readyState; } catch(e) { }
if(ok==4) load(AJAX.responseText);
}
AJAX.send(params);
}
}
</script>
</head>
<body>
<input type="text" id="searchField"/>
<input type="button" onclick="getFile()"/>
<script>
searchField = document.getElementById("searchField");
</script>
</body>
</html>

Categories