Ajax rss feed not working on localhost - ajax

I'm trying to get the following code from w3schools to work oh my localhost through IIS. When I run it, I can see that it is trying to retrieve the requested rss feed but unfortunately it never executes. It only allows me to see the options to chose from but never displays them.
Many thanks in advance for any help.
<html>
<head>
<script>
function showRSS(str)
{
if (str.length==0)
{
document.getElementById("rssOutput").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("rssOutput").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select onchange="showRSS(this.value)">
<option value="">Select an RSS-feed:</option>
<option value="Google">Google News</option>
<option value="MSNBC">MSNBC News</option>
</select>
</form>
<br>
<div id="rssOutput">RSS-feed will be listed here...</div>
</body>
</html>
And the php file
<?php
header('Access-Control-Allow-Origin: *');
//get the q parameter from URL
$q=$_GET["q"];
//find out which feed was selected
if($q=="Google")
{
$xml=("http://news.google.com/news?ned=us&topic=h&output=rss");
}
elseif($q=="MSNBC")
{
$xml=("http://rss.msnbc.msn.com/id/3032091/device/rss/rss.xml");
}
$xmlDoc = new DOMDocument();
$xmlDoc->load($xml);
//get elements from "<channel>"
$channel=$xmlDoc->getElementsByTagName('channel')->item(0);
$channel_title = $channel->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$channel_link = $channel->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$channel_desc = $channel->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
//output elements from "<channel>"
echo("<p><a href='" . $channel_link
. "'>" . $channel_title . "</a>");
echo("<br>");
echo($channel_desc . "</p>");
//get and output "<item>" elements
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
$item_link=$x->item($i)->getElementsByTagName('link')
->item(0)->childNodes->item(0)->nodeValue;
$item_desc=$x->item($i)->getElementsByTagName('description')
->item(0)->childNodes->item(0)->nodeValue;
echo ("<p><a href='" . $item_link
. "'>" . $item_title . "</a>");
echo ("<br>");
echo ($item_desc . "</p>");
}
?>

Maybe this is a cross platform problem.
If you're using Chrome, try opening it like this :
chrome.exe -allow-file-access-from-files

Because the html code does this:
Checks if an RSS-feed is selected; then
Creates the function to be executed when the server response is ready; then
Sends the request off to a file on the server,
Are you using this on your mac? I think that the localhost cannot give a server response in os x. Or, you have to unlock something using terminal to make it work.
This code is correct because it does work on my server.

Related

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 javascript function refresh

I think my question is odd… I’m learning here, and would like to use AJAX & JSP to display some other JSP pages in order.
i.e. click button: page1.jsp displayed, click button again: page2.jsp displayed, …
I got the JSP to add the ‘1’ after page and JSP does increment the variable. But it does not change the value past page 1…
It increments correctly in the function if I do a location.reload(), but that of course brings me back to page one…
I’m sure there are other ways to do this, but I simply want this to work using JSP… Any ideas
<!DOCTYPE html>
<html>
<head>
<%! int n = 0;%>
<script>
function loadDoc() {
<% n = n+1; %>
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","page<%=n%>.jsp",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Using AJAX to display next page</h2></div>
<button type="button" onclick="loadDoc()">Change Page</button>
</body>
</html>
n is 0 each time. You need to save n. Try using a
<input type="hidden" value="0" id="countvariable" />
in your html somewhere.
Then inside loadDoc() put
var n = 1 + parseInt(document.getElementById("countvariable").value);
document.getElementById("countvariable").value = n;
This should hold your variable. Also, the parseInt is a must otherwise javascript will append the 2 together and you will get 10 as n instead of 1.
Updated: If you want to go back after a certain amount of pages then add this to the end.
if(n == 2)
{
document.getElementById("countvariable").value = 0;
}

server crashes when i use onreadystatechange

I am trying to create a chat for my website.
To load the new data, i run a function every 1.5''.
If i use asynchronous mode, my website is fast, my server does not crash, but browser freezes until the response.
When i use synchronous mode, my server crashes after a while, and i have to restart Apache (! ?).
I thought that i was requesting too much data and my (virtual) server crashes, but why in asynchronous mode works fine ?
function loadchat() {
xmllive.open('GET','live.php', false);
xmllive.send(null);
myelemen('dcdd').innerHTML = xmllive.responseText;
}
function loadchatv() {
xmllive.onreadystatechange=function() {
if (xmllive.readyState==4 && xmllive.status==200){
myelemen('dcdd').innerHTML = xmllive.responseText;
}
}
xmllive.open('GET','live.php', true);
xmllive.send();
Thank you for your answer, MMM. Since your response, i read about your suggestions.
(http://dsheiko.com/weblog/websockets-vs-sse-vs-long-polling).
I figured that, in Long Pooling the server makes a loop until finds new data and only then browser receives and makes a new request.
So, tell me please, what do you think about this solution (simplified):
/////////// html file //////////////
<script type="text/javascript" charset="utf-8">
var xmlff;
if (window.XMLHttpRequest) {
xmlff=new XMLHttpRequest();
} else {
xmlff=new ActiveXObject("Microsoft.XMLHTTP");
}
function waitForMsg(){
xmlff.onreadystatechange=function() {
if (xmlff.readyState==4 && xmlff.status==200){
document.getElementById('messages').innerHTML = xmlff.responseText ;
setTimeout('waitForMsg()', 1000 );
}
}
xmlff.open('GET','msgsrv.php' ,true);
xmlff.send();
}
</script>
</head>
<body>
<div id="messages">
</div>
<script type=text/javascript>
waitForMsg()
</script>
</body>
</html>
/////// php file ///////////
<?
do {
sleep(3);
$result = mysql_query("SELECT message FROM chat ");
while ($row = mysql_fetch_array($result)){
$msg .= $row[0];
}
} while (mysql_num_rows($result) == 0);
header("HTTP/1.0 200");
print $msg;
?>
Thanks in advance.

Simple Ajax / page refresh

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).

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