www.webdeveloper.com
Results 1 to 11 of 11

Thread: Using JS,JSON,PHP, and MYSQL to populate a form SELECT options

  1. #1
    Join Date
    Apr 2009
    Posts
    35

    Using JS,JSON,PHP, and MYSQL to populate a form SELECT options

    I cannot figure out what is wrong with this script:

    Code:
    	var url="json.php";
    	$.getJSON(url,function(data){
    	$.each(data.members, function(i,user){
    			selbox.options[selbox.options.length] = new Option(user.title,user.aid);
    
    	});
    	});
    The goal is to run json.php to get data from my MYSQL and take that data to create a SELECT in a form.
    I had thought the above code would create something like this:

    Code:
    selbox.options[selbox.options.length] = new Option('Private','13');
    selbox.options[selbox.options.length] = new Option('Public','14');
    selbox.options[selbox.options.length] = new Option('Friends','15');
    The PHP script json.php works. It gathers the data from the MYSQL and displays it as I want when I use this JS:

    Code:
    $(document).ready(function(){
    var url="json.php";
    $("#userdata tbody").html("");
    $.getJSON(url,function(data){
    $.each(data.members, function(i,user){
    var tblRow =
    "<tr>"
    +"<td>"+user.aid+"</td>"
    +"<td>"+user.title+"</td>"
    +"</tr>" ;
    $(tblRow).appendTo("#userdata tbody");
    });
    });
    });
    So far I get nothing populated in the SELECT dropdown

  2. #2
    Join Date
    Nov 2010
    Posts
    1,087
    what does the error console say? is selbox defined?

  3. #3
    Join Date
    May 2014
    Posts
    1,037
    You seem to be adding them to the select's OPTIONS, but not the DOM/markup -- if they don't exist on the DOM, dumping them into that array isn't gonna do jack.

    though this is another example of how the abstraction of a framework has separated you from what's really going on. Likewise, even if adding them to that array did something, this:

    selbox.options[selbox.options.length] = new Option(user.title,user.aid);

    should probably be this:

    selbox.options.push(new Option(user.title,user.aid));

    Same thing, just easier to do... not that I'm sure you can actually do "new Option" unless you defined that somewhere...

    ASSUMING selbox is ACTUALLY the SELECT tag and not some jQuery stupidity... (not a fan) I'd have my usual 'make' generator function:

    Code:
    function make(tagName, content, attribs, parent) {
    	var e = document.createElement(tagName);
    	if (content) e.appendChild(
    		typeof content == 'object' ? content : document.createTextNode(content)
    	);
    	if (attribs) for (var i in attribs) e[i] = attribs[i];
    	if (parent) parent.appendChild(e);
    	return e;
    }
    That inside the loop I'd call (assuming user.aid goes into 'value' and 'title' is the text inside the OPTION tag):

    make('object', user.title, { value : user.aid }, selbox);

    Really though I'd axe the jquery bull, it's not doing anything for you other than making the code uselessly vague and cryptic. I probably also wouldn't be waiting for onload and instead get the request started as soon as possible, like when the DOM is complete right before </body> so it can run simultaneous to other requests. Depending on what else is on the page (like say, big media files) it could even finish before the render completes, lessening any "pop-in" on the content's part.

    Also if you're only doing this onload (well, document.ready) -- and are pulling the data from a mysql database, why aren't you just generating the proper markup server-side instead of this pointless client-side code bloat?
    Java is to JavaScript as Ham is to Hamburger.

  4. #4
    Join Date
    Nov 2010
    Posts
    1,087
    Quote Originally Posted by deathshadow View Post
    You seem to be adding them to the select's OPTIONS, but not the DOM/markup -- if they don't exist on the DOM, dumping them into that array isn't gonna do jack.

    though this is another example of how the abstraction of a framework has separated you from what's really going on. Likewise, even if adding them to that array did something, this:

    selbox.options[selbox.options.length] = new Option(user.title,user.aid);

    should probably be this:

    selbox.options.push(new Option(user.title,user.aid));

    Same thing, just easier to do... not that I'm sure you can actually do "new Option" unless you defined that somewhere...
    holy CRAP

    what a frighteningly misleading answer!

    have you really never dynamically populated a <select> this way before?

    Code:
    <body>
    <select id="thesel"></select>
    <script>
    var selbox=document.getElementById("thesel");
    for (var i=1; i<6; i++){
    selbox.options[selbox.options.length] = new Option(i,i);
    }
    </script>
    
    </body>
    whatever this is purporting to be:
    Code:
    selbox.options.push(new Option(user.title,user.aid));
    will get you an "undefined is not a function" error...

    @killinspre: the way you are populating the select is fine. Your problem is elsewhere.
    Last edited by xelawho; 08-05-2014 at 05:23 PM.

  5. #5
    Join Date
    May 2014
    Posts
    1,037
    Quote Originally Posted by xelawho View Post
    have you really never dynamically populated a <select> this way before?
    Not since Nyetscape 4, and that never worked in IE that I'm aware of.

    You're right though, "push" would fail on a HTMLOptionsCollection. I keep forgetting that's not an array... though since IE support for HTMLOptionsCollection or nsIHTMLOptionsCollection (the original pre HTML 5 version) is effectively nonexistent in IE8/lower, was never really a method I'd be advocating using. (as in IE / JScript it used to be a readOnly DOMNodeList)

    Even if you can't use push, and "new Option" works, you'd be better off using appendChild instead of the goofy self-index on an object. To rework what you posted:

    Code:
    var selbox=document.getElementById("thesel");
    for (var i=1; i<6; i++) selBox.appendChild(new Option(i,i));
    Would be far, far better. My real point was I wouldn't even be TRYING to put it onto a collection. That's just asking for it to not work.

    Still leaves me wondering why you'd be doing this 'document.ready' instead of server side in the first place. Strikes me as just more "JS for nothing". M
    Last edited by deathshadow; 08-05-2014 at 06:45 PM.
    Java is to JavaScript as Ham is to Hamburger.

  6. #6
    Join Date
    Nov 2010
    Posts
    1,087
    Quote Originally Posted by deathshadow View Post
    Not since Nyetscape 4, and that never worked in IE that I'm aware of.
    yes, it works in IE (and takes - what? 5 seconds to test?). What IE has been known to choke on is your appendChild method. If you want to do it without indexing (and really
    Code:
    selbox.options[selbox.options.length] = new Option("something","something else");
    is fine here, as is
    Code:
    selbox[selbox.length] = new Option("something","something else");
    ) you would want to use the select's add method...
    Code:
    var selbox=document.getElementById("thesel");
    for (var i=1; i<6; i++) {
    selbox.add(new Option(i,i));
    };

  7. #7
    Join Date
    May 2014
    Posts
    1,037
    Ok, I didn't know about the "add" method, that's nice. Thanks. There's always something new to learn. THAT looks like what should be used. Don't brute force things when the API is providing a perfectly good method for doing it!

    Though I've never seen IE choke on appendChild... But then I don't use a lot of selects because as a USER they just piss me off... at least in most of the scenarios people put them on sites. If it's two or three options, fine... you have 12 or more, blow it out your...

    See when people use SELECT for things like dates or even the state of the union you live in -- I end up screaming at the display "FOR *** SAKE JUST LET ME TYPE IT IN!!!"

    I know... I know... Valium Jason, Valium.... For God's sake John, sit down.
    Last edited by deathshadow; 08-05-2014 at 07:59 PM.
    Java is to JavaScript as Ham is to Hamburger.

  8. #8
    Join Date
    Nov 2010
    Posts
    1,087
    Haha. Probably the worst is for year of birth where the first option is 1910 and you have to scroll all the way down.

    Or, increasingly sadly, when the first option is 2014 (do they really expect a newborn to be registering on their page?) and you also have to scroll all the way down, as if the select itself is mocking you for being an old fart...

    (although to be fair, I think all browsers now scroll to the corresponding option if you focus on the select and start typing)

  9. #9
    Join Date
    May 2014
    Posts
    1,037
    Quote Originally Posted by xelawho View Post
    (although to be fair, I think all browsers now scroll to the corresponding option if you focus on the select and start typing)
    Seems to only work with the first digit in ones I tend to use (REAL Opera, Firefox) which isn't all that useful when 90% of the options including the one you want, start with a 1.

    A while ago I made a keyboard input filter for dates, and when I showed it around was greeted by "what a waste of code!" over around 2k of scripting...

    Isn't 100 selects at four digits apiece itself 2.2k assuming you DON'T use the value attribute? :/ and that would just be 1/3rd the date.

    I like input filters. MM/DD/YYYY someone types in a 4, you plug in the 0 and the slash for them... they type in a 3 you restrict the next digit to a 0 or 1, and if they hit slash you prepend the 0?

    Just seems easier.
    Last edited by deathshadow; 08-05-2014 at 09:53 PM.
    Java is to JavaScript as Ham is to Hamburger.

  10. #10
    Join Date
    Nov 2010
    Posts
    1,087
    Quote Originally Posted by deathshadow View Post
    Seems to only work with the first digit in ones I tend to use (REAL Opera, Firefox) which isn't all that useful when 90% of the options including the one you want, start with a 1.
    really? typing 1970 into FF or opera gets me to 1970 using this:
    Code:
    <script>
    var selbox=document.getElementById("thesel");
    for (var i=0; i<2000; i++) {
    selbox.add(new Option(i,i));
    };
    </script>
    although I'm not sure if I have Real opera or the Fake one.

    I like datepickers, although I suspect we're not going to agree on that one.

  11. #11
    Join Date
    May 2014
    Posts
    1,037
    Quote Originally Posted by xelawho View Post
    although I'm not sure if I have Real opera or the Fake one.
    Opera 12.17 was the last "real" Opera. 15/newer is basically Chrome with the Opera logo slapped on it any old way... which is why for OPERA users it's pathetic crippleware, since for Opera users browser like Chrome and Safari are pathetic crippleware -- like a trip in the wayback machine with Mr. Peabody to IE 4 Mac so far as the UI and in-built functionality is concerned.

    Doesn't work here in Latest FF... strange. Wonder if one of the many extensions I use to drag it kicking and screaming up to 80% of what Opera 12 did out of the box or to make poorly written websites usable is mucking with it. I've had that happen often enough.

    Quote Originally Posted by xelawho View Post
    I like datepickers, although I suspect we're not going to agree on that one.
    I HATE them when they're done with selects -- BUT, even though I rail against the code involved, the ones that show you a full calendar? Those are pretty cool.

    Though usually if the date I want is more than three years away, I still end up screaming "For **** sake just let me type it in!"

    I'm funny that way. The handful of times a SELECT does seem appropriate, I'd usually sooner see a set of radio buttons so I can see ALL the options at once, not just the ones that fit into the tiny little box. Technically I guess you could say input[radio] and Select/option are redundant to each-other -- they're just different presentation of doing the same thing...

    WAIT... huh, I wonder if it would be easier to use radio buttons to CSS recreate a styled select (which usually hides the real select then uses markup to show it) than it would to do what most of your frameworks and libraries do. It's a crazy idea, but it might just work and let HTML do all the heavy lifting for you. Especially since clicking on a label that is wrapping or pointing at a INPUT with the "for" attribute is the same as clicking on that input. 90%+ of the cutesy stuff could be handled by the CSS.
    Last edited by deathshadow; 08-05-2014 at 10:52 PM.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles