views:

203

answers:

5

I have a piece of code that is working fine in IE, but it doesn’t run in Firefox. I think the problem is that I have not been able to implement $('document').ready(function). The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]. I will be very thankful if someone can see my code & help me in correctly implementing it. Here is my code:

<html><head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2
     /jquery.min.js"></script>
     <script type="text/javascript" language="javascript">
     $(document).ready(function() { 
     $.getJSON("http://127.0.0.1/conn_mysql.php", function (jsonData) {
     $.each(jsonData, function (i, j) {
     document.form1.fruits.options[i] = new Option(j.options);
     });});
     });
     </script></head>
     <body><form name="form1">
     My favourite fruit is :
     <select name="fruits" id="fruits" /></form></body>
</html>
+4  A: 

Short version (suggested by meeger): don't use single quotes around document.

document is a variable that comes with JavaScript (at least in the browser context). Instead, try the following for the relevant line.

$(document).ready(function() {

You'll also want to take the onLoad attribute off of the body tag, else it will run twice.

Dan G
To summarize, don't use single quotes around `document`.
meagar
@some Use of double quotes wasn't in question; you could also have said "don't use brackets or dollar signs or periods or commas around `document`"
meagar
+1  A: 

Just run $(document).ready(function() {doStuff}). This will automatically run when the document is ready.

It's best practice, at least in my opinion, that you don't put any events in the html itself. This way you separate the structure of an html document from it's behavior. Instead attach events in the $(document).ready function.

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
     <script type="text/javascript">
       $(document).ready(function() { 
           $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
             var selectElem = $('#fruits');

             for(var i = 0; i < jsonData.length; i++) { 
               selectElem.append($('<option>').html(jsonData[i].options));
             }

           });
       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>

EDIT: I tested with the following and mocked the json object since I can't make that call myself.

<html>
  <head>
     <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
     <script type="text/javascript">
       $(document).ready(function() {
           var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');
           var selectElem = $('#fruits');

           for(var i = 0; i < jsonData.length; i++) { 
             selectElem.append($('<option>').html(jsonData[i].options));
           }

       });
     </script>
  </head>
  <body>
    <form name="form1">
      My favourite fruit is :
      <select name="fruits" id="fruits" />
    </form>
  </body>
</html>
shoebox639
onload won't? :-)
pst
Touche, I'll clarify.
shoebox639
XCeptable
I refer you to http://api.jquery.com/ready/. The .ready function will get called once the page has fully loaded. You can define the function multiple times if you'd like, they will get run lexically as it appeared on the page. I was merely saying that you should avoid using the onLoad event in the html itself as it doesn't provide for much flexibility in design.
shoebox639
OK, thanks that have had a clear example. I have edited the code now but its behaving same i.e. executing in IE but not in firefox. Whats trouble now.
XCeptable
Post edited, maybe this will run in FF.
shoebox639
not working even in ie .....
XCeptable
Can you post your console output or give more indication as to /how/ its now working?
shoebox639
I just tested that exact and it worked in both chrome and firefox. The only difference is that instead of getting the json, I mocked it with just `var jsonData = JSON.parse('[{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}]');` as you said this is how your data came out. That said, I think the problem is with your json service not returning the right thing.
shoebox639
XCeptable
XCeptable
`$ not defined` means jQuery isn't getting imported. I had the problem at first because the code you posted split the jQuery import in two, which put a space in the path, so it couldn't find it.
shoebox639
I am taking care of space as if I add an artificial space, than ie also stops working.
XCeptable
Does the second set of code work? copy the whole thing as is into a file and run it. Because I can definitely confirm that that works. So I can probably guarantee it's your ajax service that is failing.
shoebox639
XCeptable
OK, with ur 2nd set of code, its now other way round. i.e. its working in FF but not IE.
XCeptable
I'm on a linux box right now, so I can't test IE. I'll test it at home a little later and will keep checking this thread.
shoebox639
XCeptable
+2  A: 

Here it is in all its glory. The shorthand, awesome version:

UPDATED

<script type="text/javascript" language="javascript">
    $(function() { 
        $.getJSON("http://localhost/conn_mysql.php", function (jsonData) {
            var cacheFruits = $('#fruits'),
                cacheOption = $(document.createElement('option'));

            $.each(jsonData, function (i, j) {
                cacheFruits.append(
                    cacheOption.clone().attr('value', j.options).html(j.options)
                );
            });
        });
    });
</script>

Of course, I don't know what your JSON structure is, so you may need to play around with the append section of the code.

There should be no reason why the above would not work.

Stephen
I prefer to use `$.ready(function)` as it is slightly less magically named. [jQuery.ready](http://api.jquery.com/ready/). Just out of curiosity, why not `$('<option/>')` for the creation?
pst
I respect your position, but I wouldn't call this one magic. Well, actually I would, but for different reasons. ;) The reason for the `document.createElement()` is becuase it's faster than the string-parsed `$('<option/>')` version.
Stephen
@Stephen no, it is not working. U say I need to drop <body onload> mean it should only be a normal body tag <BODY>. The structure of my json is like [{"options":"smart_exp"},{"options":"user_intf"},{"options":"blahblah"}].
XCeptable
I edited the code, its still running in ie but not in firefox. Can u see now whats problem. thanX
XCeptable
I updated the code. If it doesn't work, then you've got other problems. Possibly a duplicate ID or other invalid HTML issues.
Stephen
XCeptable
A: 

You do not need quotes around document. Once the page has completely loaded, it will start executing whatever you have defined in ready()

$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    $(this).each(jsonData, function (i, j) {
      document.form1.fruits.options[i] = new Option(j.options);
    });
  });
});
Andrew Sledge
is not working even in ie ...
XCeptable
A: 

Try this, your json data should be in this format:

[{'text':'sometext','value':'somevalue'},{'text':'sometext','value':'somevalue'}];


$(document).ready(function() { 
  $(this).getJSON("http://localhost/conn_mysql.php", function (jsonData) {
    var options = [];
    $.each(jsonData, function (i, j) {
      options.push('<option value="' + j.value + '">'  + j.text + '</option>');
    });
    $('#fruits').html( options.join(''));
  });
});

Please note that there may be an encoding/escaping issues here. Make sure that you escape the text properly from the server side. htmlentities, htmlspecialchars can help you with that.

This should work in most browsers

jerjer
its not working even in ie ...
XCeptable
I have tested it, it even don't run in ie with now corrected code.
XCeptable