Ajax rss feed - openweathermap - javascript

so I get the feed after choosing an option but its not "refreshing as new news come".
I have the same problem with openweather.
Is the "GET" my problem or browser or something else? I guess everything is cached but it should not.
Should it be POST and not GET how sould I change that with the current code?
thanks!
<script>
nocache = "&nocache" + Math.random()* 1000000
url = "$q"
out = "";
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 (this.readyState==4 && this.status==200) {
document.getElementById("rssOutput").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getrss.php?q="+str+nocache,true);
xmlhttp.send();
}
</script>
<?php
//get the q parameter from URL
$q = $_GET["q"];
//find out which feed was selected
if($q=="Baden-Württemberg") {
$xml=("https://verkehrsmeldungen.polizei-bw.de/TicRss.ashx?region=BW");
} elseif($q=="Bayern") {
$xml=("http://www.br.de/verkehr-static/verkehrsmeldungen-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<=5; $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>");
}
?>

From what you are saying or trying to accomplish, is to either use
polling
event or socket connection (socket.io)
Now with Polling, you set a particular interval to always go and check for new updates. This path is not too efficient as you might go to the server to retrieve new information and there might be none returned as at the time you sent the request.
Sample
var interval = 3000// milliseconds
function fetchFeeds(){
setTimeout(function(){
// goto the server here and manage returned record
}, interval);
}
For Events: you can check up on server side events here but for only HTML5, but nice stuff.
Will advise to go for socket instead, check socket.io

Related

HTML, js, ajax form action="", after first send XMLHttpRequest stop working

I'm using a XMLHttpRequest to get data from another server. The JS is executed from the keyup-event from a input-field in my html-document.
After i've sent the formular data one time to the same html-document the XMLHttpRequest stops working.
I used this example:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
HTML
<label for="lieferant">Lieferant:</label>
<input name="lieferant" id="eintragen_lieferant" value="' . $lieferant . '" type="text" maxlength="50" onkeyup="eintragen_get_lieferanten(this.value)">
<div id="eintragen_lieferanten"></div>
js
function loadxhtml(url, cfunc)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function eintragen_get_lieferanten(value)
{
loadxhtml("functions/eintragen_get_lieferanten.php?suchstring=" + encodeURIComponent(value) + "&lol=" + timestamp, function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("eintragen_lieferanten").innerHTML=xmlhttp.responseText;
}
}
);
}
php
$query = " SELECT * FROM lieferant WHERE name LIKE '%" . $suchstring . "%'";
$result = $con->query($query);
while($row = $result->fetch_assoc())
{
echo "<br>" . $row['name'];
}
?>
Can someone tell my, why the xhtmlrequest stops working after i've sent the data to the same php/html file (aciton="")?
Thanks for any advice.

pass PHP variable to AJAX call (JS)

I have a script that rotates some images from their current position, there are 4 available rotations(positions) of the image and they are present by the values 0,1,2,3. My problem is that I need two variables from the database in my AJAX call to make this happen. I need the rotation and the src. My PHP currently look like this; Please notice the query where I take out rotation and src.
<?php
$item_number = -1; //This value is -1 in order to make the list start on 0
$rowsize = 12;
$itemArray = array();
$finalArray = array();
$results = 0;
for ($i = 0; $i < $rowsize; $i++) {
$stmt = $mysqli->stmt_init();
$stmt->prepare('SELECT z, rotation, src, name FROM house_room1 INNER JOIN objects ON house_room1.object_id=objects.object_id WHERE house_room1.ref_id = ?');
$stmt->bind_param('i', $i
);
if ($stmt->execute()) {
$stmt->bind_result($z, $rotation, $src, $name);
while($stmt->fetch()) {
$results = 1;
$itemArray['number'] = $item_number;
$itemArray['name'] = $name;
$itemArray['ref_id'] = $z;
$itemArray['rotation'] = $rotation;
$itemArray['src'] = $src;
array_push($finalArray, $itemArray);
}
}
else {
echo 'Something went terribly wrong' . $mysqli->error;
}
$stmt->close();
$item_number++;
}
if($results == 1){
aasort($finalArray,"ref_id");
foreach($finalArray as $arr){
echo '<li id="item-' . $arr['number'] . '" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>' . $arr['name'] . '
<img class="rotate" id="img_'.$arr['number'].'" src="images/house/other/settings.jpg" onclick="rotateObject(this)" alt="'. $src.'">';
}
}
//create a function for sorting
function aasort (&$array, $key) {
$sorter=array();
$ret=array();
reset($array);
foreach ($array as $ii => $va) {
$sorter[$ii]=$va[$key];
}
asort($sorter);
foreach ($sorter as $ii => $va) {
$ret[$ii]=$array[$ii];
}
$array=$ret;
}
?>
It then makes an AJAX call to this file:
function rotateObject(e)
{
//e is handler which contains info about the item clicked. From that we can obtain the image id.
//since the id are of the form img_123(some number), we need to extract only the number.
var img_id = e.id.split("_")[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)
{
var getEle = document.getElementsByClassName('item' + img_id)[0];
var imagePath ="images/house/objects/stone_chair_1.png"; //This has to be
getEle.src = imagePath + xmlhttp.responseText;
}
}
xmlhttp.open("POST","database/update_settings_rotate.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("item_id="+encodeURIComponent(img_id));
}
This code is then supposed to have the imagePath equal to src. and then the rotation after it, but I don't know how I can get the src for that specific image from the database query made in the PHP file.
Any suggestions or advice on how I can pass that value? Thanks in advance.
One way to pass variables from php to javascript is:
<script>
var myJavascriptVariable = <?php echo $myPhpVariable; ?>
</script>
Hope this help you

redirect location after execution is wrong

I have been mulling over this for hours, to the point of myopia looking at this screen and I can't figure out what is causing the problem.
I can a script which redirects to a unique page (defined in variables) after execution. The script works fine but the location it redirects to is wrong every time.
For example. A user has 4 links to check, lets say they are new comments on his/her page. When he/she clicks the link it directs to the oldest one every time. Not the one they clicked on.
I have 2 parts of code:
<?
$result_s = mysql_query("SELECT * FROM pins a LEFT JOIN comments b ON a.id = b.pin_id WHERE b.to_id = '$myid' AND b.status = '0' ORDER BY date DESC");
$rows = array();
while ($row = mysql_fetch_assoc($result_s)) {
$jS = '"'.$row[id].'"';
$boardid = $row['board_id']; // collection id
$postid = $row['pin_id']; // post id
$posturl = $row['pin_url']; // post id
echo "<table width='100%'><tr>";
echo "<td align='center'><a href='javascript:setActive(".$jS.")'><img src='".$posturl."' height='100'><br>".$boardid."/".$postid."</a></td>";
echo "</tr></table>";
}
?>
and
<script type="text/javascript">
function setActive(ObjID) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
//Return Value. Handle as you wish. Display or ignore.
var x = xmlhttp.responseText;
if (document.getElementById(ObjID).style.color == 'black') document.getElementById(ObjID).style.color='red';
else document.getElementById(ObjID).style.color='black';
document.getElementById(ObjID).innerHTML = '<center><font face="Century Gothic">' + x + '</font></center>';
}
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>";
}
</script>
I have tried using different variables in the location part of the script but nothing works. I'm not educated in this so maybe I'm missing something that is glaringly obvious to some programmers out there, which is my reason for asking here.
Can you see what the problem might be?
There are a few issues
The A in Ajax stands for asynchronous. So whatever you do right after the .send is executed BEFORE the Ajax call (The use of XMLHttpRequest is called Ajax)
You call the function with an ObjID which is then acted upon in the RETURN of the Ajax call (whatever is inside the xmlhttp.onreadystatechange) but not known in there since ObjID is not global and not copied to the scope (closure)
Try this
function setActive(ObjID) {
var xmlhttp = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
var ID = ObjID
xmlhttp.onreadystatechange = function(id) {
return function() {
if (this.readyState != 4) return;
if (this.status == 200) {
var obj = document.getElementById(id); // id is passed now
var style = obj.style; // but please use CSS intead
style.color = style.color == 'black'?'red':'black';
style.fontFamily = "Century Gothic";
style.textAlign="center";
obj.innerHTML = xmlhttp.responseText;
setTimeout(function() {
location.href="/board/pins/<?php echo $boardid; ?>/<?php echo $postid; ?>"
},3000); // assuming this is what you want
};
}(ID); // passing the ObjID
}
var p_str = "a="+ObjID;
xmlhttp.open("POST","/application/views/setActive.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(p_str);
}

Ajax POST request not working in Internet Explorer

I'm building a PHP script that sends an email to people on their birthdays. I also need a small web interface where I can turn the entire program on or off, watch who is celebrating his birthday today and see if any mails could not be send. The php on the server is working, but I'm struggling with the html and javascript interface. Specifically the Ajax request that gets the information from the server. it works fine in firefox, chrome and opera, but in Internet Explorer 8 I don't get a response from the server. The readyState switches to 4, but the status remains 0 and the responseText is empty.
After googling I found out that a lot of people advice JQuery, but I couldn't get that to work in any browser. I want to find out more about it, because it seemed pretty easy, but for now I would like to know how to do this without JQuery.
edit
In response to questions from the comments, switching the if and else statements yields the same results. As does changing the connection from 'open' to 'close', incidentally, it is supposed to be close, I can't remember why I changed it, probably just trying something out of frustration. Finally I added the server side php code. The server sends back string data in case 'action' is switchonoff or, just a header with no text if action is clearlog and a jsonarray if action is initialize. Whatever the request the server's HTTP status is always 0.
<script type="text/javascript">
function loadXMLDoc(action) {
var parameters = "action="+encodeURI(action);
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.open("POST",'http://mailer.test/App/postscript.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "open");
xmlhttp.send(parameters);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status==200) {
if(action == 'switchonoff'){
document.getElementById("onoffbutton").innerHTML=xmlhttp.responseText;
} else if(action == 'initialize'){
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("onoffbutton").innerHTML=response['onoff'];
document.getElementById("birthdays").innerHTML=response['birthdays'];
document.getElementById("errors").innerHTML=response['errors'];
} else if(action == 'clearlog'){
document.getElementById("errors").innerHTML="";
}
}
}
}
window.onload = function() {
loadXMLDoc('initialize');
}
</script>
edit, here's the php script
<?php
include "settingschanger.php";
include "customercsv.php";
if (!isset($_POST['action'])) {
$_POST['action'] = 'dummy';
}
$post = $_POST['action'];
if(strcmp($post, "initialize") == 0) {
$settings = new SettingsChanger();
$onoff = $settings->getOnOff();
$csv = new CustomerCSV();
$csv->openFile((__DIR__).CustomerCSV::FILENAME);
$todaysbirthdays = $csv->getTodaysBirthdays();
$birthdays = "";
foreach ($todaysbirthdays as $row) {
$birthday = "";
foreach ($row as $data) {
$birthday .= $data . " ";
}
$birthdays .= $birthday . "<br />";
}
$errorLogArray = $settings->getErrorLog();
$errors = "";
foreach($errorLogArray as $line) {
$errors .= $line . "<br />";
}
$result = json_encode(array('onoff'=>$onoff, 'birthdays'=>$birthdays, 'errors'=>$errors));
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "switchonoff") == 0) {
$settings = new SettingsChanger();
$result = $settings->changeOnOff();
header("HTTP/1.1 200 OK");
print $result;
}
if(strcmp($post, "clearlog") == 0) {
$settings = new SettingsChanger();
$settings->clearLog();
header("HTTP/1.1 200 OK");
}
?>
Try with xmlhttp.send(parameters); after xmlhttp.onreadystatechange statement.
I had some issues with the returned content being empty in older versions of IE ( less than v9), but the success-function was triggered.
Then I found out that I was using HTML5 tags, and in IE, for some odd reason, HTML5 output via an AJAX-request doesn't work and returns an empty or no DOM.
Look at the last edit in "jquery .load() not inserting data in ie8 and below".
Well, I got the site to work. Instead of a post request I now use a get request and that seems to work. It's not perfect and I'll continue looking for a way to do it with a post request, but for now it'll work.

AJAX problem with IE9 (and other IE versions)

I am having problem with XMLHttpRequest object in IE9, IE8 and probably IE7 too, although have not tested in IE7. It works without problem in FF4, Opera 11.01 and Chrome 10.
First I would like to explain for what I use this code. I have a HTML select tag, with option Time defined in it. Then when the user clicks on a button, it dynamically updates select with time values from database. Now here is the code for creating XMLHttpRequest object:
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlhttp = false;
}
}
}
As you can see, if the creation of XMLHttpRequest object fails, it tries to create ActiveXObject.
Now the code for sending request and getting response:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(time).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getTime.php?d=" + str, true);
xmlhttp.send();
I send the parameters to getTime.php, and the response is written back to select tag with id=time. Now in IE9 and IE8 it does not want to populate the select tag with time from DB.
EDIT:
I will add code from getTime.php:
<?php
$username="something";
$password="";
$database="somethingDB";
$date = $_GET["d"];
$timestamp = strtotime($date);
$nextDay= $timestamp + (1 * 24 * 60 * 60);// 7 days; 24 hours; 60 mins; 60secs
$date2 = date('Y/n/j', $nextDay);
$link = mysql_connect('localhost', $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $link);
$query="SELECT TIME(Date) FROM someTable WHERE Date >= '" .$date. "' AND Date < '" .$date2. "'";
$result=mysql_query($query);
if (!$result) {
die('Could not query:' . mysql_error());
}
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option>" .$row[0]."</option>";
}
mysql_free_result($result);
mysql_close($link);
?>
EDIT2:
Ok, I have added wrap, according to this. Now I will also post the code select tag, which is now wrapped:
<div id="wrap">
<select id="Time1" name="Time1" disabled="disabled">
<?php if (empty($_GET['Time1'])) { echo "<option>Ura</option>"; } else { echo '<option>' . $_GET['Time1'] . '<option>'; } ?>
</select>
</div>
The code in getTime.php is now also changed, I will post only the section which is changed:
echo '<select id="Time1" name="Time1">';
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo "<option>" .$row[0]."</option>";
}
echo '</select>';
As you can see, I only added echo '....' before and after while statment. Guess what happens now. In FF, Opera and Chrome it works without a problem, but in IE9, it now gets the values, but it does not put them in the drop down menu, it just prints them as actual text. Also the drop down menu has dissapeard when the values are printed as text. Seems like it does not want to include select tag. I don't get it, why is that only with IE?
I have found the right solution here. I already had the select tag in the div box, the missing code was this part:
document.getElementById('box').style.display = 'block';
Apparently without this, the IE will just print it as actual text, instead of populating the select object.
IE has problem with 'select' tag. You cannot just replace the 'option' tags inside only, you have to replace the opening and closing 'select' tags also.

Categories