I am busy learning Ajax and need to use Postgres for the backed DB. I found an example for Mysql which works but when I convert it to Postgres, it stops working. I have not made any changes to the HTML code when swapping from Mysql to Postgres.
When I execute the php code at command line (php test.php), it works and outputs the correct number of rows and data.
Here is the php
<?php
$dbh = pg_connect("host=192.168.0.8 dbname=test user=test password=test");
if (!$dbh) {
die("Error in connection: " . pg_last_error());
}
// execute query
$sql = "SELECT * FROM users";
$result = pg_query($dbh, $sql);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
// iterate over result set
// print each row
while ($row = pg_fetch_array($result)) {
echo "Name: " . $row[1];
echo "<BR />";
}
// free memory
pg_free_result($result);
// close connection
pg_close($dbh);
?>
And here is the html
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "test.php";
var fn = document.getElementById("name").value;
var vars = "name="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
document.getElementById("name").value = "";
}
</script>
<script type="text/javascript">
function setFocus()
{
document.getElementById("name").focus();
}
</script>
</head>
<body onload="setFocus()">
<div>
<form name="input" action="" onsubmit="ajax_post(); return false;">
Barcode : <input type="text" id="name" size="30"><br />
</form>
</div>
<div style="background-color: lightyellow; border: 1px solid black; width: 400; height: 300;">
<div id="status"></div>
</div>
</body>
One thing I have noticed is that when I run the test.php file at command line with postgres, anew-line character is always appended to the end of the data.
Thanks
O
Install Firefox and the Firebug add-on. In Firebug, you can conveniently watch the whole communication between your HTML and PHP page, and there's also a great JS debugger with breakpoints etc. included. You don't seem to have a good idea what the error exactly is, but you should still be able to spot it with these tools.
Related
I need to know what can done to display data from mysql database in cordova app.
I made a php file placed it on the server.
then i made the html with json code to fetch data from mysql database.
The data from mysql database should be displayed in the div with id="demo".
I have done this till now.
My Php file looks like this:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
include "../../webConfig/web.config.php";
$conn = connect();
$q = $conn->query("SELECT name FROM 'online_' ORDER BY DESC");
$rows=$conn->query($cb);
$rows=$conn->query($cb);
foreach($rows as $row){
echo $row["ID"];
echo $row["first_name"];
echo $row["middle_name"];
echo $row["last_name"];
}
echo json_encode($rows);
?>
My HTML file Looks like this.
<div data-role="content">
<div class="container-fluid">
Online Application
<p id="demo">
.....
</p>
<script>
var obj, dbParam, xmlhttp;
obj = { "table":"online", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "http://localhost/admin/notify/test.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</div>
</div>
I have been trying to do this using json But my html file dosen't show anything apart from those dots.
I tried placing the php file on the web server as well, but still it did not show anyhing.
At the moment, everything is working fine with the script, I insert data in my database, I refresh and I get the username with the new message. However I'm trying to figure out how to have the message added onto the page as soon as the database is updated without having to refresh.
Simple HTML, Here's where the messages load up
<div id="msg">
</div>
Whenever the page is done loading, I'm calling AJAX to get the data
<script type="text/javascript">
$(function(){
//AJAX
var hr = new XMLHttpRequest();
var url = "exampleclass.php";
var msg = document.getElementById("msg");
hr.onreadystatechange=function()
{
if (hr.readyState==4 && hr.status==200)
{
document.getElementById("msg").innerHTML=hr.responseText;
}
}
hr.open("GET", url, true);
hr.send();
});
</script>
Here is my PHP form that retrieves data
<?php
include('inc/connect.php');
$query = "SELECT message, user_name "
. "FROM chat "
. "WHERE (user_name='bryan' or user_name='derek') "
. "AND (user_to='derek' or user_to='bryan')";
while ($retrievedata = mysql_fetch_assoc($sql)){
echo $retrievedata['user_name'].": ".$retrievedata['message']."<br/>";
}
?>
I know nothing about javascript, but I'm using javascript in a couple places on my site to make it look a little nicer. One of these places is where when a user clicks a div, it can open a nice looking popup with more information. However, I also want to save the number of clicks a div has.
I know how I could do this with php, and I've managed to find some javascript code that could increment a variable, but I don't think those two can be combined unless the js saves the var as a cookie, which I think could have some security flaws if I'm then reading the js variable back into the database.
The javascript code I have is
/*Click counter*/
var clicks = 0;
function count()
{
document.getElementById( "cc" ).value = ++clicks;
}
and I'm not sure of where to start with the php since I don't know the javascript. But querying the database to increment the column that stores the number of clicks will be simple. I just don't know how to tell php that a click has been made using javascript. I don't think it can be done in php, unless the link goes to a php file which handles all of this first and then redirects, which won't work in this case since the popup wouldn't be loaded in the new page.
Any ideas or pseudo-code to help?
You should use AJAX to update the server database if you want to keep the counter up to date on the server side.
Based on this tutorial, here's a quick example:
mydiv.phtml:
<?php $_GET['id']=isset($_GET['id'])?$_GET['id']:1; include 'count.php'; ?>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
var clickerid = <?php echo $_GET['id'] ?>; //counter id allows easy implementation of other counters if desired
var clicks = <?php echo $clicks ?>;
var clickLock = false;
var maxClickRate = 1000; //maximum click rate in ms, so the server won't choke
//Browser Support Code
function count(){
if (clickLock) {
alert('you\'re clicking too fast!');
return;
}
clickLock=true;
setTimeout('clickLock=false;',maxClickRate);
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){
document.getElementById('cc').innerHTML = ++clicks;
}
}
// Now pass clicks value to the
// server script.
var queryString = "?id=" + clickerid + "&update=true";
ajaxRequest.open("GET", "count.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<div onclick='count()'>
<form name='myForm'>
<input type='button' value='clickOnDiv'/>
</form>
</div>
Clicks so far: <span id='cc'><?php echo $clicks; ?></span>
</body>
</html>
count.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
if (!isset($_GET['update'])){
$stmt = $dbh->prepare('SELECT count
FROM clicks
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$clicks = $result['count'];
} else {
$stmt = $dbh->prepare('UPDATE clicks
SET count = count + 1
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
}
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>
set_database.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost', 'user', 'password');
$dbh->query('CREATE DATABASE test;');
$dbh->query('CREATE TABLE test.clicks (id INT KEY, count INT);');
$dbh->query('INSERT INTO test.clicks VALUES (1,0);');
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>
I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)