Solved

Webpage Listbox Populating Erratically

Posted on 2013-01-13
14
553 Views
Last Modified: 2013-01-17
I have a webpage that when you click on an inage a listbox populates.  This however, is working quite strangly.  Some images you have to click on several times to get the listbox to load, or the page refreshes itself.  However; after you've gone through and clicked everything a couple of times the page settles down and works properly.  Not sure why this is happening, but its not good!

The link:
http://www.menuhead.net/index.php

The code responsible for the populating...
index.php

 
$(document).ready(function() {
$("input:image").click(function(evt) {
evt.preventDefault();
display( $(this).val() );})
})

function display(what)
{
$.getJSON("mydoggie.php?ajax=true", { "case" : what }, function(data) {
$("#Doggie").empty();
$.each(data, function(index, objRecord) {
$("#Doggie").append('<option value="' + objRecord.ID + '">' + objRecord.Name + '</option>');});
});
}

Open in new window


The other page...
mydoggie.php
<?php
$list_array = array();

if(isset($_GET['case'])) {
	
$dbc = mysql_connect('','','') or die('Error connecting to MySQL server.'); 
$case = mysql_real_escape_string($_GET['case']);
		
mysql_select_db('MyDB'); 
		
switch($case){
case 'Place':
$result = mysql_query("select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC");
break;
case 'Cuisine':
$result = mysql_query("select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
break;
case 'City':
$result = mysql_query("select CityID as ID, CityName as Name from tblCities order by CityName ASC");
break;
case 'State':
$result = mysql_query("select StateID as ID, StateName as Name from tblStates order by StateName ASC");
break;
case 'ZipCode':
$result = mysql_query("select LocationID as ID, ZipCode as Name from tblLocations order by ZipCode ASC");
break;
}
if($result)
while($row = mysql_fetch_assoc($result)) {
$list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);		
}
}
	
header('Content-type: application/json');
echo json_encode($list_array);
	
?>

Open in new window

0
Comment
Question by:DS928
14 Comments
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38772469
Shouldn't the lines be in the order like:
$(document).ready(function() {
$("input:image").click(function(evt) {
display( $(this).val() );
evt.preventDefault();
})
})

Open in new window

0
 

Author Comment

by:DS928
ID: 38772493
This is working much better now, thank you.  However; it still took four clicks for the first list to populate.  That is only if I click on Place.  If I try one of the others like Zipcode it took fourteen clicks!  It seems that the further you go down into the switch, the slower the load response is and you have to click like crazy!
0
 
LVL 27

Accepted Solution

by:
Lukasz Chmielewski earned 500 total points
ID: 38772499
I think this is working fine, just the script loading time is too long.
You should add a "loading" gif or something like that to see if the script is working while you wait.
0
 

Author Comment

by:DS928
ID: 38772504
Mmmmmmm. Could the script be sped up somehow?  If not how do you add a loading gif?Thank you.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38772506
$(document).ready(function() {
$("input:image").click(function(evt) {
$("#loadingdiv").css("display","block");
display( $(this).val() );
$("#loadingdiv").css("display","none");
evt.preventDefault();
})
})

Open in new window


... and the div
<div id="loadingdiv"><img src="loading.gif" /></div>

Open in new window


... and the css
#loadingdiv{display: none;}

Open in new window

0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38772509
You can create you own loader here:
http://www.ajaxload.info/

About the speed: the database code seems to be plain as possible, there's just a issue of fetched data amount... In other words, no, in my opinion there's not much you can do. Informing the user that the list is currently loading would be nice anyway...
0
 
LVL 10

Expert Comment

by:P1ST0LPETE
ID: 38772524
I tested in Chrome, Firefox, IE7, IE8, IE9.  Didn't notice any problems. What browser are you using and experiencing problems?

I'm not a php developer, so can't help you out much on that end.

As far as the jQuery goes - there are a few things you can do to make the code more efficient.

1. Whenever you need to make lots of node insertions to the DOM, it is best to use a Document Fragment.  This way you make all the insertions on the fragment and then insert the entire fragment into the DOM, which in effect is only one DOM redraw.

2. Whenever you need to create multiple elements it is best to use core JavaScript.  This is definitely not noticeable with only a few elements, but becomes much more noticeable as the number of elements scale up. I'm a huge proponent of jQuery, but lets not forget it's a wrapper to pure JavaScript, and thus has the potential to decrease performance.

This is how I would do it:
function display(what)
{
     $.getJSON("mydoggie.php?ajax=true", { "case" : what }, function(data)
     {
          var $doggie = $("#Doggie").empty();
          var fragment = document.createDocumentFragment();

          for (var i in data)
          {
               var option = new Option(data[i].Name, data[i].ID);
               fragment.appendChild(option);
          }

          $doggie[0].appendChild(fragment);
     });
}

Open in new window

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38772547
The document.ready event may fire before the entire DOM is complete.  For example, images may still be loading when the browser thinks the document is ready.

As far as the PHP goes, it looks minimalist and lacks error handling (which could be an issue) but it appears to be mostly functionally correct.  You might want to look into the idea of "coding standards" since that will make your code easier to read and debug.
<?php
$list_array = array();

if(isset($_GET['case'])) 
{
    $dbc = mysql_connect('','','') or die('Error connecting to MySQL server.'); 
    $case = mysql_real_escape_string($_GET['case']);
        
    mysql_select_db('MyDB'); 

    $result = NULL;
    switch($case)
    {
        case 'Place':
        $result = mysql_query("select RestID as ID, RestName as Name from tblRestaurants order by RestName ASC");
        break;
        
        case 'Cuisine':
        $result = mysql_query("select CuisineID as ID, CuisineName as Name from tblCuisines order by CuisineName ASC");
        break;
        
        case 'City':
        $result = mysql_query("select CityID as ID, CityName as Name from tblCities order by CityName ASC");
        break;
        
        case 'State':
        $result = mysql_query("select StateID as ID, StateName as Name from tblStates order by StateName ASC");
        break;
        
        case 'ZipCode':
        $result = mysql_query("select LocationID as ID, ZipCode as Name from tblLocations order by ZipCode ASC");
        break;
    }

    if($result)
    {
        while($row = mysql_fetch_assoc($result)) 
        {
            $list_array[] = array("ID"=>$row["ID"], "Name"=>$row["Name"]);        
        }
    }
}
header('Content-type: application/json');
echo json_encode($list_array);

Open in new window

0
 

Author Comment

by:DS928
ID: 38772591
Thank you, everyone.  I am going to play around with all of this info for a minute and reply back.  I am using IE9.
0
 

Author Comment

by:DS928
ID: 38772639
Roads_Roads  Where exactly would I put the div and the css for the loader?  I am going to try this.
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38772654
Just after <div class="content"> would be a fit.
Just put css inside your css section in head
<style type="text/css">
...
0
 

Author Comment

by:DS928
ID: 38772685
Thank you.  I was wondering, is there a way to make the connection to the database before the image is selected?  It seems that once the list is loaded in memory it runs fine, so I was think of a way to run the five querys without seeing them in the listbox, so that when you go to click on the image its already loaded?  Just barking up a tree!
0
 
LVL 27

Expert Comment

by:Lukasz Chmielewski
ID: 38774020
This is possible to load the lists into arrays and then switch the lists (somehow - I don't have a concept). You would have to store them in javascript and switch onclick of the image. But that would increase page loading time.
0
 

Author Closing Comment

by:DS928
ID: 38791849
The problem was in the Script.  After it was cleaned up.  It worked fine.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now