2

Lately, I'm having trouble with jQuery click events. In this example, I'm wanting to use ajax post when an user clicks on a list item. No errors pop up on Firebug and the jquery script is in the code. When I run the code, nothing happens. The code is below.

<script type="text/javascript" >
$('#pop').click(function() {
var pop = 'pop';
$.post('ajax_file.php', {
    style: pop
    }, function(data) {
        $('#tube').html(data);  
        });});
</script>

<ul>
    <li id="pop">Pop</li>
</ul>
1
  • 1
    <script> is just enough. And wrap your code into a ready $(function(){ Commented Aug 20, 2012 at 22:45

3 Answers 3

2

Try this:

$(document).ready(function(){
   $('#pop').click(function() {
       var pop = 'pop';
       $.post('ajax_style_homepage.php', {
         style: pop
       }, function(data) {
           $('#tube').html(data);  
       });
    });
})
Sign up to request clarification or add additional context in comments.

Comments

2

Wrap it in the document ready function and see what happens. Also you don't need to empty. You can call the html method and it will overwrite the content.

$(function(){
   $('#pop').click(function() {
        var pop = 'pop';
        $.post('ajax_style_homepage.php', { style: pop}, function(data) {
            $('#tube').html(data);  
        });
    });
});

Comments

1

Just another way to do the same thing as the 2 other answers without binding your click method at page load. Simply set your onclick attribute on your list item to a function containing your ajax call. This is easier to follow in my opinion.

<script type="text/javascript" >
function makeAJAXPost(){
    var pop = 'pop';
    $.post('ajax_file.php', {
        style: pop
        }, function(data) {
            $('#tube').html(data);  
    });     
}
</script>

<ul>
    <li onclick="makeAJAXPost()" id="pop">Pop</li>
</ul>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.