AJAX problem with IE9 (and other IE versions) - javascript

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.

Related

How to set the values of select boxes and input boxes based on a MySQL query, using AJAX

I have a web page with a large number of select boxes plus a few other types of inputs. I want to populate these select boxes and input boxes with values held in a MySQL database based on the values selected in two of the select boxes.
I have tried to use AJAX to request the data but cannot see how to return the data held in a database to a specific select box from the server php script.
jscript used to request the data is as follows
<script>
function venueChange(str) {
if (str == "") {
document.getElementById("Venue").innerHTML = "";
return;
} else {
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("Player1").innerHTML = this.responseText;
}
};
var opponent_name = document.getElementById("Opponents").value
var variables = "venue_name=str&opponent_name=Hello World";
xmlhttp.open("GET","getTeamPHP?" + variables,true);
xmlhttp.send();
}
}
</script>
The getTeamPHP files is as follows;
<?php
require '../../configure.php';
$q = intval($_GET['venue_name']);
$v = $_GET['opponent_name'];
$database = "matchmanagementdb";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,$database);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,$database);
$sql="SELECT * FROM user WHERE Opponents = '".$q."' AND Venue = '".$v."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo document.getElementById("Player1").innerHTML = $row['FirstName'] ;
}
mysqli_close($con);
?>
I have decided that the solution lies in creating three scripts to;
1) read the search details
2) search the database and populate the form
3) allow updates.
As per http://www.dynamicdrive.com/forums/showthread.php?45895-How-to-populate-php-html-form-with-MySQL-data.
So closing this question.

Ajax rss feed - openweathermap

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

How to use AJAX to create/update radio buttons?

I currently have a setup where I use a PHP script to create a list of radio buttons by loading the required information from my database. This script is in the HTML structure rather than a separate file, so it requires a page refresh to update the list.
I'd like to figure out how to delete and reload the list upon pressing a button, the ID of which is 'btnDelete' (the actual deletion of items in the database is a separate point that I won't go into here). The current code that I have will delete the list of radio buttons, but when the next line is added, nothing happens (including list deletion).
PHP (delCom.php)
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
JavaScript
function delComic()
{
var ajaxRequest;
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
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
$("#loadList").remove();
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?t=", true);
ajaxRequest.send(null);
}
HTML
<div id="divComics">
<p><u>Uploaded Comics</u></p>
<!-- find comics in database -->
<div id="loadList">
<?php
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '".$_SESSION['username']."' ORDER BY comicName ASC");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
</div>
<br>
<br>
<input type="button" onclick="delComic()" value="Delete Comic" name="deleteButton" id="btnDelete"/>
</div>
The code creates buttons correctly when run in the HTML, but not when in a separate php file.
Thanks in advance.
EDIT: Updated to fix a few misnamed things and to add the new line suggested. The loadList now empties but doesn't delete itself, as it should. The current problem is that the PHP file won't output the buttons again.
<?php
$username = $_GET['username'];
include_once('includes/conn.inc.php');
$query = ("SELECT comicID, comicName FROM comic WHERE username = '$username'");
$result = mysqli_query($conn, $query);
while ($row = $result->fetch_assoc())
{
echo "<br><input name='comicList' id='".$row['comicID']."' type='radio' value='".$row['comicID']."'>".$row['comicName']." </option>";
}
?>
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
document.getElementById('loadList').innerHTML="";
document.getElementById("divComics").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "delCom.php?username=MY_EXACT_NAME_I_KNOW_WORKS_HERE", true);
ajaxRequest.send(null);
There is no element with an id=comicList and you cannot remove it $("#comicList").remove(); in Javascript because it does not exist. Javascript is probably stopping execution at that point, and thereby not displaying your results from PHP.

continuous scrolling. AJAX, PHP, JAVASCRIPT, MYSQL

I am actually creating a forum. So, there would be a "order by" dropdown box i.e a select tag in html. Where the user selects any order like by time or like, etc. An ajax function is called which dynamically brings content into the page from mysql database.
Select menu
<select name="orderby" onchange="showposts(this.value)">
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
showposts function
function showposts(str){
orderby=str;
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("postsdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
Showposts.php page
$sql = "SELECT * FROM posts order by date desc ";
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."&nbsp&nbsp&nbsp&nbsp";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine'].";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
Problem
So, the problem here is, I want to use a continuous scroll option like the one which is used in facebook. All the javascripts and jquery libraries I saw use logic that when the user scrolls down to the page, the javascript then places some content after that. But, here I running a while loop which brings the data from database at a time. So, I couldn't implement the javascript code. So, is there any thing that I could do to achieve continuous scroll, like is there any possibility to break the while loop or retrieving entire data and display part by part or anything like that?
javascript for scrolling
function yhandler(){
var wrap=document.getElementById('postsdiv');
var contentheight=wrap.offsetHeight;
var yoffset=window.pageYOffset;
var y=yoffset+window.innerHeight;
if(y>=contentheight){
showposts();
}
}
window.onscroll=yhandler();
Use the PDO class built into php and the query from the database will return all the rows as an array of stdclass objects. Then use PDOStatement::fetchObject() to loop through the array
As you are retrieving the data from server using JavaScript, why don't you put the view with the help of JavaScript instead of PHP.
Try using Asynchronous Javascript Call (AJAX) instead of XMLHttpRequest. This will help you to load data asynchronously which means that even if the the result coming form server take time you can still execute your other javascript codes.
With AJAX implemented, let say you want to fetch 10 Posts at one time, then after fetching first 10 posts, you can print the data for those 10 using JavaScript and simultaneously make a call for another 10.
Prepare a successCallBack function, where you will parse the data received and put that as required for your HTML. You will need to append the posts, so that when the next AJAX returns the result, that gets appended after the last post.
http://www.jquery4u.com/demos/ajax/
You should look into MySQL LIMIT. The limit function takes 2 input variables, start and length. With these 2 variables you can create a paging system; that would go something among the lines of:
showposts function
//Add a global variable to save the current page:
var currentPage = 0;
var currentType = 0;
function showposts(str){
//ALL PREVIOUS CODE, UNCHANGED
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML+=xmlhttp.responseText;
}
}
if(str != undefined){
currentType = str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}
xmlhttp.open("GET","showposts.php?q="+currentType+"&p="+currentPage,true);
xmlhttp.send();
}
Showposts.php page
<?php
$currentPage = intval($_GET['p']);
$numPerPage = 30; //change this to the number of items you want each page
$sql = "SELECT * FROM posts order by date desc LIMIT ".($currentPage * $numPerPage).", ".$numPerPage;
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."&nbsp&nbsp&nbsp&nbsp";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
?>
Now you need to detect when a user has scrolled to the bottom of the page, then call the following function:
function nextPage(){
currentPage++;
showposts();
}

AJAX returning results plus the entire page contents (Using Javascript, PHP, MySQL but not JQuery)

I have an AJAX script running on my website that is supposed to update a dependent dropdown menu (a SELECT options menu) after a previous dropdown menu onchange event happens.
When I click on the first dropdown, the second dropdown does seem to be populated with the correct values from a MySQL database query. However, under my values I also seem to be pulling in the contents on the entire HTML webpage as a whole.
I'd like to know how to only bring in my values without loading the whole webpage again inside of my SELECT options menu.
My Javascript:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp_aris=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp_aris=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_aris.onreadystatechange=function()
{
if (xmlhttp_aris.readyState==4 && xmlhttp_aris.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp_aris.responseText;
}
}
xmlhttp_aris.open('GET','http://mywebdomain.com?ajax=true&q='+str,true);
xmlhttp_aris.send();
}
</script>
My PHP code:
// begin my ghetto code
if ($_GET['ajax'] == 'true') {
$q = $_REQUEST["q"];
$con = mysqli_connect('localhost','db_user','db_pass','db_name');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
$sql='SELECT DISTINCT
employees.firstName,
employees.lastName
FROM
sales_reps
INNER JOIN employees ON sales_reps.employeeId = employees.employeeId
INNER JOIN sales_campaign ON sales_campaign.salesCampId = sales_reps.saleCampId
WHERE
sales_campaign.marketId = '.$q.' AND
employees.isactive = 1';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
echo '<option value="' . $row['firstName'] . '">'
. htmlentities($row['firstName']) .' '.htmlentities($row['lastName']) .'</option>';
}
mysqli_close($con);
}
// end my ghetto code
My code on the page with the dropdown menus:
<select id="frm-marketid" name="frm-marketid" onchange="showUser(this.value)">
<option value="">Choose a Market</option>
<option value="74">Annapolis</option>
<option value="61">Anne Arundel</option>
<option value="26">Aventura</option>
<option value="63">Baltimore</option>
</select>
<br/>
<select id="txtHint"><b>Person info will be listed here.</b></select>
just kill your script after you output your response for ajax
...
}
mysqli_close($con);
exit;
}
...

Categories