ChatScript Bot on Localhost - php

I have created a chatbot using chatscript. It works perfectly in .cmd when I execute a chatscript.exe program.
Now I am trying to run the chatbot the browser using xampp.
I have done the following steps:
I have installed XAMPP on C drive.
In XAMPP > HTDOCS folder I have added the Chatscript folder in it.
I am using Better web interface provided by chatscript.
When I try to run the index.php file, the bot doesn't reply.
Please find below code used in the web interface.
Index.php
<!DOCTYPE HTML>
<html>
<head>
<title> CHATSCRIPT SERVER
</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
#responseHolder {
min-width: 600px;
min-height: 300px;
width: 80%;
height: 300px;
overflow: auto;
margin: 10px auto;
background-color: pink;
}
</style>
</head>
<body class="bgimg">
<div id="responseHolder"></div>
<form id="frmChat" action="#">
<p>
Enter your message below:
</p>
<table>
<tr>
<td>Name:</td>
<td>
<input type="text" id="txtUser" name="user" size="20" value="" />
<input type="hidden" name="send" />
</td>
</tr>
<tr>
<td>Message:</td>
<td><input type="text" name="message" id="txtMessage" size="70" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="send" value="Send Value" /></td>
</tr>
</table>
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
var botName = 'rose'; // change this to your bot name
// declare timer variables
var alarm = null;
var callback = null;
var loopback = null;
$(function(){
$('#frmChat').submit(function(e){
// this function overrides the form's submit() method, allowing us to use AJAX calls to communicate with the ChatScript server
e.preventDefault(); // Prevent the default submit() method
var name = $('#txtUser').val();
if (name == '') {
alert('Please provide your name.');
document.getElementById('txtUser').focus();
}
var chatLog = $('#responseHolder').html();
var youSaid = '<strong>' + name + ':</strong> ' + $('#txtMessage').val() + "<br>\n";
update(youSaid);
var data = $(this).serialize();
sendMessage(data);
$('#txtMessage').val('').focus();
});
// any user typing cancels loopback or callback for this round
$('#txtMessage').keypress(function(){
window.clearInterval(loopback);
window.clearTimeout(callback);
});
});
function sendMessage(data){ //Sends inputs to the ChatScript server, and returns the response- data - a JSON string of input information
$.ajax({
url: 'ui.php',
dataType: 'text',
data: data,
type: 'post',
success: function(response){
processResponse(parseCommands(response));
},
error: function(xhr, status, error){
alert('oops? Status = ' + status + ', error message = ' + error + "\nResponse = " + xhr.responseText);
}
});
}
function parseCommands(response){ // Response is data from CS server. This processes OOB commands sent from the CS server returning the remaining response w/o oob commands
var len = response.length;
var i = -1;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == '\t') continue; // starting whitespace
if (response.charAt(i) == '[') break; // we have an oob starter
return response; // there is no oob data
}
if ( i == len) return response; // no starter found
var user = $('#txtUser').val();
// walk string to find oob data and when ended return rest of string
var start = 0;
while (++i < len )
{
if (response.charAt(i) == ' ' || response.charAt(i) == ']') // separation
{
if (start != 0) // new oob chunk
{
var blob = response.slice(start,i);
start = 0;
var commandArr = blob.split('=');
if (commandArr.length == 1) continue; // failed to split left=right
var command = commandArr[0]; // left side is command
var interval = (commandArr.length > 1) ? commandArr[1].trim() : -1; // right side is millisecond count
if (interval == 0) /* abort timeout item */
{
switch (command){
case 'alarm':
window.clearTimeout(alarm);
alarm = null;
break;
case 'callback':
window.clearTimeout(callback);
callback = null;
break;
case 'loopback':
window.clearInterval(loopback);
loopback = null;
break;
}
}
else if (interval == -1) interval = -1; // do nothing
else
{
var timeoutmsg = {user: user, send: true, message: '[' + command + ' ]'}; // send naked command if timer goes off
switch (command) {
case 'alarm':
alarm = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'callback':
callback = setTimeout(function(){sendMessage(timeoutmsg );}, interval);
break;
case 'loopback':
loopback = setInterval(function(){sendMessage(timeoutmsg );}, interval);
break;
}
}
} // end new oob chunk
if (response.charAt(i) == ']') return response.slice(i + 2); // return rest of string, skipping over space after ]
} // end if
else if (start == 0) start = i; // begin new text blob
} // end while
return response; // should never get here
}
function update(text){ // text is HTML code to append to the 'chat log' div. This appends the input text to the response div
var chatLog = $('#responseHolder').html();
$('#responseHolder').html(chatLog + text);
var rhd = $('#responseHolder');
var h = rhd.get(0).scrollHeight;
rhd.scrollTop(h);
}
function processResponse(response) { // given the final CS text, converts the parsed response from the CS server into HTML code for adding to the response holder div
var botSaid = '<strong>' + botName + ':</strong> ' + response + "<br>\n";
update(botSaid);
}
</script>
</body>
</html>
ui.php
<?php
// ============= user values ====
$host = "localhost"; // <<<<<<<<<<<<<<<<< YOUR CHATSCRIPT SERVER IP ADDRESS OR HOST-NAME GOES HERE
$port = 8080; // <<<<<<< your port number if different from 1024
$bot = "rose";
// <<<<<<< desired botname, or "" for default bot
//=========================
// Please do not change anything below this line.
$null = "\x00";
$postVars = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
extract($postVars);
if (isset($send))
{
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$userip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
$userip = $_SERVER['REMOTE_ADDR'];
}
$msg = $userip.$null.$bot.$null.$message.$null;
if(!$fp=fsockopen($host,$port,$errstr,$errno,300))
{
trigger_error('Error opening socket',E_USER_ERROR);
}
// write message to socket server
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}
Please find below screenshot of the issue:
Issue while accessing chatbot on localhost:8080
I am having difficulty in connecting my chatscript server and localhost. Please let me know what should I change in UI.php so that bot will send the reply.
Thanks in advance.

There is one error in the UI.php file. The $ret variable breaks because it is not declared. If you add $ret = ''; just above fputs the code should work:
// write message to socket server
$ret = '';
fputs($fp,$msg);
while (!feof($fp))
{
$ret .= fgets($fp, 512);
}
fclose($fp);
exit($ret);
}

Besides the $ret correction, upon running in XAMPP, as the web host is Apache, so client uses port 8080 or 8088, upon using CS over Web.
ChatScript as server, start the ChatScript system with using port 1024 ( or user-defined) is needed.
Furthermore, Harry Bot is also called in index.php file, change to Rose as in ui.php file.
I have CS responses after doing these.

Related

XmlHttpRequest doesn't terminate request processing

I've implemented long polling mechanism using XMLHttprequest. My problem is that after the browser is closed, the server side process continues to run and doesn't shutdown.
The web server is httpd apache and the process is a php script .
I do want the php script to close after the browser closes .
i discovered that php doesn't discover connection close unless it tries to output data back to the browser .
this is a problem, since it will compromise the objective of minimizing bandwidth usage .
the client side script, uses onreadystatechange to try and read partial data without requiring new XMLHttprequest for each communication .
some browsers will not allow to read partial data until the whole response is finished :
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type"></meta>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(NewReq);
var mode = 0;
function NewReq() {
var Req = new XMLHttpRequest();
var url = 'a.php';
if (mode) {
url += '?mode=' + mode;
}
Req.open('GET', url);
Req.onreadystatechange = function(event) {
var handler = ReadyState[this.readyState];
if (typeof handler == 'function') {
handler(this);
}
};
inc_mycookie();
Req.send();
}
var ReadyState = [
//'NotInit', 'ReqRec', 'ConEst'
null , null, null,
partial // 'Proccessing'
,
complete //'Finishied'
];
function partial(Req) { //'Proc'
if (mode == 1) {
return;
}
try {
var strings = Req.response.split(';');
strings.pop();
var data = JSON.parse(strings.pop());
$('#message').text(data);
mode = 2;
}
catch (e) {
$('#message').text(e.message);
mode = 1;
}
return;
}
function complete(Req) {
var last = $('#message').text();
$('#output').text(last);
NewReq();
}
function inc_mycookie() {
var matches = document.cookie.match(/(?:^|;)mine=([^;]+);?/);
if (matches) {
var inc = parseInt(matches[1]) + 1;
document.cookie = 'mine=' + inc;
}
}
</script>
</head>
<body>
<h3> output </h3>
<div id="output"></div>
<h3> partial </h3>
<div id="message"></div>
</body>
</html>
and here is the php script (apache has "php_value output_buffering Off") :
<?php
header('Content-type: application/json');
if (!isset($_COOKIE['mine'])) {
setcookie('mine', 23);
$_COOKIE['mine'] = 23;
}
$mode = isset($_GET['mode']) ? $_GET['mode'] : 1;
print json_encode('test_' . $_COOKIE['mine']) . ';';
if ($mode == 2 ) {
$iter = 8;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
// if i remove this line, then erro_log will continue to show even when browser is closed
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
}
?>
in the case where browser support partial response, the damage is not too bad .
but if browser require the whole response to finish, then the damage will be a complete compromise of long polling, meaning a repetitive request every 5 seconds .
one possible solution is to add interval :
<?php
$iter = 200;
while($iter) {
sleep(2);
$iter--;
error_log('a.php:' . $iter);
if (update_exist()) {
print json_encode('test_' . $_COOKIE['mine'] . '_' . $iter) . ';';
}
else if (($iter-200)%20 == 0) { // 180, 160, 140 ... 40, 20, 0
print json_encode('check connection : ' . $iter) . ';';
}
}
Even though this is almost 5 years old, consider
XMLHTTPRequest.abort()
The javascript in the question would need to be redesigned in the following ways:
Make Req a global variable, so that
Req.abort() could be called, in (for instance)
window.addEventListener('unload', function() { Req.abort(); })
so that closing the page could cause the client to terminate the connection to the server.

Uploading video with documented Phonegap example and PHP not working

I'm trying to implement the sample code on this page:
http://docs.phonegap.com/en/2.9.0/cordova_media_capture_capture.md.html#CaptureImageOptions
under capture.capture.Video (Full Example)
I've changed "cordova-x.x.x.js" to "cordova.js" (that seems to be how this distro names the file) and the server to my local Mac.
I can upload video files to the server from another PC on the same network, but when I run this code from Xcode on my tethered iPhone 4S (6.1.3) I can see the file being temporarily written to the /private/var/tmp/ folder but it is not moved to the webserver folder; it just disappears. (When I do this from the other PC, I can see it written temporarily and then sucessfully moved and renamed.)
This is the code from that example page:
<!DOCTYPE html>
<html>
<head>
<title>Capture Video</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="json2.js"></script>
<script type="text/javascript" charset="utf-8">
// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {
var i, len;
for (i = 0, len = mediaFiles.length; i < len; i += 1) {
uploadFile(mediaFiles[i]);
}
}
// Called if something bad happens.
//
function captureError(error) {
var msg = 'An error occurred during capture: ' + error.code;
navigator.notification.alert(msg, null, 'Uh oh!');
}
// A button will call this function
//
function captureVideo() {
// Launch device video recording application,
// allowing user to capture up to 2 video clips
navigator.device.capture.captureVideo(captureSuccess, captureError, {limit: 2});
}
// Upload files to server
function uploadFile(mediaFile) {
var ft = new FileTransfer(),
path = mediaFile.fullPath,
name = mediaFile.name;
ft.upload(path,
"http://192.168.0.3/~me/index.php",
function(result) {
console.log('Upload success: ' + result.responseCode);
console.log(result.bytesSent + ' bytes sent');
},
function(error) {
console.log('Error uploading file ' + path + ': ' + error.code);
},
{ fileName: name });
}
</script>
</head>
<body>
<button onclick="captureVideo();">Capture Video</button> <br>
</body>
</html>
This is my PHP:
<?php
if (!empty($_FILES))
{
$file_src = 'video/'.$_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], $file_src)):
echo 'Your file has been uploaded sucessfully';
else:
echo 'Error';
endif;
}
?>
Any idea of what I am doing wrong?
Thanks
OK, this code worked on the webserver:
<?php
$file_src = "new.mov";
move_uploaded_file($_FILES["file"]["tmp_name"], $file_src);
?>
...though I'm not sure what part of the PHP wasn't working.

nonce token after ajax response and hash problems using ajax jquery type json

i have login with my own code at php, now i dont so good at jquery ajax and so on,
my login using ajax jquery type json , i take all vals and post them to server side php which check all details , and response answer via the same jquery ajax .
the problem is i added nonce token that maded in php to the login form and every time after user try to login the nonce change , the problem is only when i refresh the login page the nonce changed to the good nonce else its will keep the same nonce token and will send with the post not the updated one because the ajax didnt refresh the page after login .
So the question is how i trigger the ajax to refresh the nonce token after every response ?
the nonce token is write in php.
and more thing about the hash nonce token , its make that hash string sometime:
asdaskjn34kj+sdf/sd=
now the ajax jquery auto remove the '+' from the hash string so its send wrong token in the POST,
here my hash function :
public static function RandomBytes($count, $printable=FALSE)
{
$bytes = '';
// supress warnings when open_basedir restricts access to /dev/urand
if(#is_readable('/dev/urandom') && ($hRand = #fopen('/dev/urandom', 'rb')) !== FALSE)
{
$bytes = fread($hRand, $count);
fclose($hRand);
}
if((strlen($bytes) < $count) && function_exists('mcrypt_create_iv'))
{
// Use MCRYPT_RAND on Windows hosts with PHP < 5.3.7, otherwise use MCRYPT_DEV_URANDOM
// (http://bugs.php.net/55169).
if ((version_compare(PHP_VERSION, '5.3.7', '<') && strncasecmp(PHP_OS, 'WIN', 3) == 0))
$bytes = mcrypt_create_iv($count, MCRYPT_RAND);
else
$bytes = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
}
if((strlen($bytes) < $count) && function_exists('openssl_random_pseudo_bytes')) // OpenSSL slow on Win
{
$bytes = openssl_random_pseudo_bytes($count);
}
if ((strlen($bytes) < $count) && #class_exists('COM'))
{
// Officially deprecated in Windows 7
// http://msdn.microsoft.com/en-us/library/aa388182%28v=vs.85%29.aspx
try
{
$CAPI_Util = new COM('CAPICOM.Utilities.1');
if(is_callable(array($CAPI_Util,'GetRandom')))
{
$bytes = $CAPI_Util->GetRandom(16,0);
$bytes = base64_decode($bytes);
}
}
catch (Exception $ex)
{
}
}
if (strlen($bytes) < $count)
{
// This fallback here based on phpass code
$bytes = '';
$random_state = microtime();
if (function_exists('getmypid'))
$random_state .= getmypid();
for ($i = 0; $i < $count; $i += 16) {
$random_state =
md5(microtime() . $random_state);
$bytes .=
pack('H*', md5($random_state));
}
$bytes = substr($bytes, 0, $count);
}
if ($printable)
return base64_encode($bytes);
else
return $bytes;
}
any one know how to change this function to make the strings without '+' in the hashesh?
To change hash function, if only '+' is the problem you may keep a check while creating the string,
next_char = Randomly-created-char;
if(next_char == '+'){
//do nothing
} else{
hash .= next_char;
}
Here is how the html and php files should be like.
The ajax call is shown in the .html file.
.php that loads your form for the first time.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#check").click(function(){
$("#keyvalue").text($("#key").val());
});
$("#submit").click(function(){
var text = $("#text").val();
var key = $("#key").val();
$.ajax({
url: 'trial.php',
data: {text: text, key:key},
type: 'POST',
dataType: 'json',
success: function(data) {
if(data.status == "fail"){
$("#status").html(data.message);
}else{
$("#status").html(data.message);
$("#key").val(data.key);
$("#keyvalue").text('');
}
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="trial.php" onsubmit="return send_form();">
<input type="text" name="text" id="text"/>
<input type="hidden" id="key" name="key" value="<?php echo $key?>"/> //Look here.
<button id="submit">Send data and get new key</button>
</form>
<br><br>
<div id="status"></div>
<br><br>
<button id="check">What's current value of key?</button> --------> <span id="keyvalue"></span>
<div id="response"></div>
</body>
</html>
.php
<?php
//You get the form contents here.
$key = isset($_POST['key']) ? $_POST['key'] : "error";
$text = isset($_POST['text']) ? $_POST['text'] : "empty";
//Check them if it matches with DB's entry, if doesn't you set $key = "error";
if($key=="error"){
$status = "fail";
$message = "There was some error processing your form.";
exit;
} else{
//You generate another random key.
$random ='';
for ($i = 0; $i < 10; $i++) {
$random .= chr(mt_rand(33, 126));
}
//Now here in steps save it to your DB. So that when next form is submitted you can match it.
//And send back response to html file, where ajax will refresh the key.
$status = "success";
$message = "
Your form was processed succesfully<br>
The text you sent was ".$text.", and the key you sent was ".$key.".
The new key sent to you can be seen by pressing the button below, has value, ".$random."<br><br>
";
}
echo json_encode(array("status" => $status, "message" => $message, "key" => $random));
?>
Hope this helps you.
While generating the form for the first time, you have to give the key and nonce without any ajax, the ajax function will be called when this following keys have been used.
echo "<input type='hidden' id='key' name='key' value='".$key."'>";
echo "<input type='hidden' id='nonce' name='nonce' value='".$nonce."'>";
This was really useful as I had encountered the same problem - I had considered an auto page refresh for the login but this is a real inconvenience to the user - I also added a block so that the ip and/or user are blocked after 5 failed attempts

drag-and-drop image upload not working on server

I am trying to implement a drag-and-drop image upload.
I found a rather simple script online and adapted to my use.
On my local installation the file uploads perfectly fine, but not on the server.
From my debugging attempts the $_SERVER['HTTP_X_FILENAME'] does not even get set by php.
I tried the following:
- Making sure that the upload folder is set to 755
- Changing the php temporary upload path and increasing the maximum allowed file size
No php or js errors of any kind occur.
Since I have the die(print_r($_SERVER)); in the php, I get the $_SERVER dump using the chrome inspector, it does not contain HTTP_X_FILENAME index.
My php is:
<?php
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
// AJAX call
file_put_contents(
'../usr/photos/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
else {
// form submit
if(!$_FILES['fileselect']) die(print_r($_SERVER));
else $files = $_FILES['fileselect'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'../usr/photos/' . $fn
);
echo "<p>File $fn uploaded.</p>";
}
}
}
The js is as follows:
//Drag and drop photo upload
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
/*Debug*/
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p>" +
//"<strong>" + file.name + ":</strong><br />" +
'<img width="130" height="100" src="' + e.target.result + '" />' +
'<br />' +
'<input type="text" name="photo_name" value="'+ file.name +'" />' +
'<br />' +
'<input type="text" name="photo_caption" value="Caption" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && (file.type == "image/jpeg" || file.type == "image/png") && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.style.display = "none";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
Thank you in advance.
You probably will have solved your problem now, but I'm posting this solution here to help others who come here with the same problem. In your js, there is a line that reads
xhr.setRequestHeader("X_FILENAME", file.name);
but should read
xhr.setRequestHeader("X-FILENAME", file.name);
since underscores are deprecated in later Apache releases (see also
Header names with underscores ignored in php 5.5.1 / apache 2.4.6)
I had this problem on one of my Ubuntu WAMP installations. Your upload URL (the POST URL specified on the Javascript side of things) needs to be a fully qualified path not a relative path. I can't see the value however but seems to be the value of whatever $id("upload").action is in your code. You can confirm this is the cause by looking at the apache logs if you have access to them. If you see 404 errors when trying to send a file then this is your problem. Thats assuming the request even hits your server at all.

Why does this work with Mysql but not Postgres

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.

Categories