views:

131

answers:

3

Hi,

I am a little bit stumped with the following problem and I am afraid that the solution is too obvious but I don't see it anymore. Problem, how come that this jQuery code works:

$(document).ready(function() {     
    var q = $(".box").val();     
    $.get("db.php", {searchterm: "test", type: "search", time: "2pm" },
        function(twitter){  
             var tweets = JSON.parse(twitter);
        }
    );

but if i make it part of a click event then it won't work:

$(document).ready(function() {     
    $(".btn").click(function() {      
    var q = $(".box").val();     
    $.get("db.php", { searchterm: "test", type: "search", time: "2pm" },
        function(twitter){
            var tweets = JSON.parse(twitter);
         }
    );   
});

Of course, my html page does have a button with class name 'btn'

Firebug flashes an error message within jQuery but reset the console right away so I can't read or copy the error from the log. Any suggestions?

+3  A: 

Perhaps you just need to return false; from the click handler?

$(document).ready(function() {
    $(".btn").click(function() {
        var q = $(".box").val();
        $.get("db.php", { searchterm: "test", type: "search", time: "2pm" }, function(twitter){ var tweets = JSON.parse(twitter); });
        return false;
    });
});

This will prevent the default action for the link - i.e. navigating to the URL.

Greg
or use `preventDefault();`
Russ Cam
Greg provided the solution without noticing the bug :)
cballou
Thanks a lot! I need to study this return false concept :)
DrDee
@cballou I did notice a missin }); but thought I'd missed it when I copied from the question heh
Greg
A: 

You were missing a closing });

$(document).ready(function() {     
    $(".btn").click(function() {      
        var q = $(".box").val();     
        $.get("db.php", {searchterm: "test", type: "search", time: "2pm"}, function(twitter){
            var tweets = JSON.parse(twitter);
        });
        return false;
    });   
});

The return false is also a good choice (credit @Greg).

cballou
A: 

@cballou's answered your question, but BTW, even if Firebug goes blank after flashing up an error, you can retrieve the error by opening Firefox's default Error Console (Ctrl+Shift+J or Tools > Error Console).

Premasagar
Good to know, thanks.
Tom
the missing }): was a typo, the return false fixed the problem
DrDee
Ah yes. The `return false;` prevents the event being passed to the default handler for that event - e.g. on an anchor link, the default action would be to redirect the page to the linked url.
Premasagar