Simple Ajax / page refresh - ajax

I'm experimenting on this code that I got from the net (I'm trying to make a simple chat but i do the message insertion manually in mysql database). It refreshes the page every 3 seconds and displays the new message in the page fetched from database. It works well in chrome and firefox but it doesn't in IE. What I have observed in IE is it will only display the new message every time I clear the cache or delete the cookies in the browser. Can anyone help me to devise a solution for this please...
Please see code:
<html>
<head>
<script type="text/javascript">
function showResult(str) {
document.getElementById("livesearch").innerHTML="";
if (str.length==0) {
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.border="0px";
return;
}
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
var msxmlhttp = new Array(
'Msxml2.XMLHTTP.5.0',
'Msxml2.XMLHTTP.4.0',
'Msxml2.XMLHTTP.3.0',
'Msxml2.XMLHTTP',
'Msxml2.xmlHTTP
'Microsoft.XMLHTTP');
for (var i = 0; i <= msxmlhttp.length; i++) {
try {
xmlhttp = new ActiveXObject(msxmlhttp[i]);
}
catch (e) {
xmlhttp = null;
}
}
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
setTimeout("showResult('a')", 3000);
}
}
xmlhttp.open("GET","http://localhost/review/login/5/try.php",true);
xmlhttp.send();
}
</script>
</head>
<body onload="">
<script>
setTimeout("showResult('a')", 3000);</script>
<form>
<div id="livesearch"></div>
</form>
</body>
</html>
this is the code for try.php
<?php
require_once('config.php');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
//Create query
$qry="SELECT * FROM message where message like '%".$_GET['a']."%'";
$result=mysql_query($qry);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_assoc($result))
{
echo $row['message']."<br>";
//echo "<br> ".$member['message'];
}
}
?>
Please help...thanks...

Your best bet is to add the following headers to the top of your page that is to return the content you wish not to be cached
header('Last-Modified: Mon, 01 Jan 1970 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
This will allow you to control the cache on the server side rather then adding the "random" number hack at the end of the request.

It looks like a caching issue. You should try adding a random number to your URL. That will force IE to reload the page.
xmlhttp.open("GET","http://localhost/review/login/5/try.php?r=" + Math.random(),true);

I know that won't help you right now, at the first time, but I highly recommend you to use a JS library like jQuery. It makes ajax calls a lot simpler, and cross-browser. It will make your code clearer, and you will be able to focus on your logic instead of low level browser issues.

If you want to do AJAX stuff and have it work in multiple browsers I recommend taking a look at jQuery:
jQuery Home Page
It is reasonably easy to get started and it will make you much more productive.
In particular, take a look at jQuery.ajax():
jQuery.ajax()
You will probably initially experience the same problem with IE when using jQuery, but I think you can fix it by setting the cache parameter to false (as described on the page I link to above).

Related

A simple example of using AJAX with CodeIgniter?

Here I have a simple, working, AJAX example of a webpage that displays data from a text file, without having to refresh the page, through a simple button command.
ajax_test.php
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
I am trying to get this to work in the exact same way, except through CodeIgniter. My pages are displayed using the following coding.
pages.php
<?php
// To avoid outside users from accessing this file
if(!defined('BASEPATH')) exit('No direct script access allowed');
class Pages extends CI_Controller
{
// Default method if one has not been requested within the URL
public function view($page = "home")
{
if(!file_exists('application/views/pages/'.$page.'.php')) // If the page does not exist
{
// Whoops, we don't have a page for that!
show_404();
}
$data["main_url"] = $this->config->item("base_url")."z_my_folders/";
$data["title"] = ucfirst($page); // Capitalize the first letter
$this->load->view("templates/header", $data);
$this->load->view("pages/".$page, $data);
$this->load->view("templates/footer");
}
}
All this does is displays the webpage when the "view" method is called (for example, pages/view/ajax_test) whiles carrying the server's main URL as a string in order to allocate files such as images, CSS, and the jQuery library through the header.
header.php
<html>
<head>
<link href="<?php echo $main_url; ?>design.css" rel="stylesheet" type="text/css">
<title>Kurtiss' Website - <?php echo $title ?></title>
<script type="text/javascript" src="<?php echo $main_url; ?>jquery/jquery-1.10.2.min.js"></script>
</head>
The ajax_test.php file displays in CodeIgniter accordantly, however when the button is pressed, nothing happens. Again, the file works fine when it is not in CodeIgniter, however I am trying to make it so that it can.
I have tried researching it, except all I can find are complex examples where users are connecting to databases, creating complex login forms, registration forms, chat rooms, etc. I just want a simple example like this one that says "Yes, this is AJAX, and it works with CodeIgniter."
Many thanks.
I have edited the code as followed.
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else
{
alert("ERROR");
}
}
When testing it in CodeIgniter, the alert message pops up four times, so it might have something to do with the xmlhttp.readyState.
Now I know what the problem was; it just couldn't find the text file. In order for it to work, I had to either relocate the text file into the CodeIgniter's main directory, or specify where the text file was located.
Thanks for your help guys.

How to send data to 'post.php' using AJAX? (without Jquery)

I'm newbie on this webdeveloper matters. I have already made a form where i've used Ajax (JQuery lib) to create a chat box.
Now, i wanna try to do something similar without using Jquery to understand how Ajax works. First i just want to write my messages on log.html using AJAX, so then i can read them later. But i dont understand why i can't send my textarea data into post.php.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Teste</title>
<script type="text/javascript">
function sendXMLDoc(){
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");
}
var message=document.getElementById('msg').value;
xmlhttp.open("POST", "post.php", false);
xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xmlhttp.readyState == 0 ) {
alert("UNSENT");
}
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
xmlhttp.send(message);
}
</script>
xmlhttp.send(data) : Why im not sending my data to post.php?
Post.php is where i write my log.html (but i cant send my messages and i dont understand why):
<?php
$text = $_POST['message']; // WHY I CAN'T RECEIVE MY POSTED MESSAGE?
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".$text."<br>\n</div>\n");
fclose($fp);
?>
And this is my form.html
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc();">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit" value="Send"/>
</form>
</body>
have you taken a look at this link ?
It seems to have a complete explanation on how to build an AJAX request with PHP and MySql.
EDIT:
The problem in your code is both on your post.php, which has incorrect syntax (lacking double quotes before the last <br>), and should be something like :
post.php
<?php
$text = $_POST['message'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div>\n(".date("g:i A").")<br>".stripslashes(htmlspecialchars($text))."<br>\n</div>\n");
fclose($fp);
?>
and with the request header, which should have the content-type set (see code below)
I based this answer on w3.org.
The final html here presented shall help you understand how Ajax requests behave on different browsers. Try it out.
It seems though that for Firefox to load the request, you need to do something when the Status is OPENED (1), and I don't quite understand why.
Try this code on different browsers to see the different approaches to XMLHttpRequest.
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function sendXMLDoc(obj){
var message=obj["message"].value;
var data = "message=" + message;
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
url = "http://localhost/AjaxPhp/post.php"
xmlhttp.open("POST", url , true);
xmlhttp.onreadystatechange = display_data;
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
function display_data() {
if(xmlhttp.readyState == 1 ) {
alert("OPENED");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 2 ) {
alert("Headers Received");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 3 ) {
alert("Loading response entity body");//check if the data was revived successfully.
}
if(xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert("Data transfer completed");//check if the data was revived successfully.
}
}
}
}
</script>
</head>
<body>
<h1>Insert text on log.html</h1>
<form method="post" onsubmit="sendXMLDoc(this);">
<textarea name="message" maxlength="196" rows="8" ></textarea>
<br>
<input type="submit"/>
</form>
</body>
</html>
I don't truly understand the whys, but according to w3, the order of the requests should, in my understanding, be :
OPENED (after invoking the open method), HEADERS_RECEIVED (after setRequestHeader), LOADING (request body received). DONE (Data transfer completed, after send) .
Chrome handles the post.php but doesn't present any alert box (maybe its my popup settings, maybe not)
IE shows only the OPENED alert message
Firefox goes "Headers Received", "Data transfer completed","OPENED", "Data transfer completed".
Hope this helps understanding it a little bit more. Always go check w3.org for the ultimate source on the web. It might not be very user-friendly and intuitive, but provides some tips on the whys and the shoulds.

AJAX not working with XAMPP or is it just impossible

I'm still relatively new to AJAX and am trying to figure out why my simple test is not working. From what I read AJAX will not work under one domain, and other words pop up like cross-site and remote server. Anyways my problem is is that I'm not sure if my code is wrong or simply what I'm trying to do is impossible. I created a simple ajax request to submit data when I click on the button. Here is the code for the first script.
<html>
<head>
<script type="text/javascript" >
function load(thediv, thefile) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile, true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="submit" onclick="load('adiv', 'hello.php');">
<div id="adiv"></div>
</body>
</html>
Here is the code for the file hello.php
<?php
echo 'aaa';
?>
AJAX is just an http request done in the background. But yes, there are security restrictions that prevent you doing a normal ajax request to any arbitrary server.
What your code is missing is actually setting the URL that you're placing the request to. You've got hello.php as a parameter to your load() function, but you never actually USE it. So you're doing an AJAX request to... "nowhere".

Windows gadgets contacting webservices

Is it possible to create a Windows Gadget, which contacts a web service.
In this case calls the web service method which in turn returns the results of a pre-defined SQL Server query.
If so, what is an ideal approach to doing this.
Has anyone any experience in doing such a thing?
To answer your question, this is indeed very possible and fairly simply too.
On the client/gadget side you will need to use javascript to make an ajax request to your server. when this request is made your server will simply access your SQL database and print it, creating the response to that ajax call. Here is an example using php as the server side language. Please Comment if you need help.
Client side (javascript):
function GetContent(){
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 = xmlhttp.responseText;
document.getElementsById("RESULTS DIV").innerHTML = response
//or something else to be done with response
}
}
var time1 = new Date().getTime()
xmlhttp.open("GET","PHP SERVER ADDRESS?time="+time1,true);
// the time parameter is important to prevent caching the response -
// your server code does not need to handle it.
xmlhttp.send();
}
And The Server code in php
<?php
$con = mysql_connect("MYSQL SERVER ADDRESS","USERNAME","PASSWORD");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM TABLE_NAME");
while($row = mysql_fetch_array($result))
{
echo $row['COLUMN NAME'];
echo "<br />";
}
mysql_close($con);
?>

AJAX script not working in Firefox

I have written an AJAX script to read information from a database and inject it into a .php file as HTML. It works in IE8, Safari, Chrome but not Firefox. No errors displayed or anything, it just doesn't execute at all.
Here's the code:
function queryDatabase(query)
{
alert();
var xmlhttp;
if (window.XMLHttpRequest)
{
alert();
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
alert();
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "<center><span style=\"color: #ff7e00; font-size: 30px;\">LOADING...</div></center>";
}
}
xmlhttp.open("GET",query,true);
xmlhttp.send(null);
}
(The alerts were for testing purposes but none of them show up in Firefox)
Here's the divs it's used on:
<div onClick="queryDatabase('latestquery.php')" style="cursor: pointer;">TEST</div> <div onClick="queryDatabase('testtagquery.php')" style="cursor: pointer;">TEST</div>
Any help is appreciated :)
Thanks
Sam
Well for a start you can't do alert() in Firefox - the argument isn't optional. Change it to alert(0) and see what happens the.
Secondly, I don't see where you set content - is that a global variable you've got initialised somewhere?
You can check for script errors in Firefox by bringing up the Error Console (Tools -> Error Console or Ctrl + Shift + J).
To help even more, install firebug.
Edit: if content is just the id of an element you need to do document.getElementById(content).innerHTML = ...;
The best advice I can give you is to start using a javascript framework that implements the AJAX functionality for you and makes it much easier to write code using it.
Using jQuery this would look like:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js">
</script>
<script type="text/javascript">
$(function() {
$('#div1').click( function() {
queryDb(this,'lastestquery.php');
});
$('#div2').click( function() {
queryDb(this,'testtagquery.php');
});
});
function queryDB(div,url) {
$(div).load( url );
}
</script>
<div id="div1" style="cursor: pointer;">TEST</div>
<div id="div2" style="cursor: pointer;">TEST</div>
Note that I would probably also use a CSS class to assign the cursor as well.
<div id="div1" class="clickable">TEST</div>
Loaded via a CSS file
.clickable {
cursor: pointer;
}
Here's the lastquery.php file if this helps:
<?php
$con = mysql_connect("localhost","root","***");
mysql_select_db("main", $con);
//GET MOST RECENT POST ID
$last_id_query = mysql_query("SELECT * FROM articles");
$last_id_result = mysql_fetch_array($last_id_query);
$last_id = (int)$last_id_result['id'] - 2;
//USE MOST RECENT POST ID TO GENERATE LAST 5 ARTICLES SUBMITTED
$result = mysql_query("SELECT * FROM articles WHERE id > '$last_id' ORDER BY id DESC");
while($row = mysql_fetch_array($result))
{
echo "<div id=\"centralcontent\"><div class=\"articleheading\"><strong>".$row['title']."</strong></div><div class=\"tag\"> in ".$row['tag']."</div><div class=\"articleinfo\">".$row['date']."</div>";
echo "<div class=\"articlecontent\">".$row['content']."</div></div>";
}
mysql_close($con);
?>
Edit: This worked on the face of it, but it looks now like it was not the actual solution.
Taking your code above and moving the xmlhttp.open call to before you set the state change function worked for me. Like this:
xmlhttp.open("GET",query,true);
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
content.innerHTML = xmlhttp.responseText;
}
else
{
content.innerHTML = "..";
}
}
xmlhttp.send(null);

Resources