Rails beginner
Rails beginner

Reputation: 14504

Jquery ajax call not made

I am having problem with jquery that the ajax call is not made. Also the click should not get at the top of dom to trigger the hide af the .warning div.

I can see with firebug that the POST request is not made.

Here is my jquery:

$(document).click(function(e) {
    if($('.warning').hasClass("active"))
        $('.warning').hide();
});

$('.ero').click(function(e) {
    e.stopPropagation();
    e.preventDefault();
            $.ajax({
        type: 'POST',
        url: '/stem_op/3',
        data: {id: idv},
        success:function(msg){
        $('.warning').fadeIn(500).css({
        display: 'block',
        position: 'absolute',
        left: position.left + 50,
        top: position.top - 25
    }).append(msg).addClass("active")}
        });      
});

Upvotes: 0

Views: 296

Answers (2)

vernonk
vernonk

Reputation: 1221

Yeah, based on your code if it's included in the head the ero classed element doesn't exist yet. Without the .ready() your code is executing immediately. Since you're using .click() as opposed to a delegate, there's nothing to bind to when it's executed.

Like Dyer above says, wrap it in a ready:

$(document).ready(function() {
   //code goes here
});

If you are possibly going to have an .ero element added dynamically with JS based on user interaction, you'll want to make use of delegate.

Also, .click() is essentially a shortcut to bind() so try and start using that at least so you can namespace your events as well. That makes binding, unbinding, and rebinding event handlers extremely easy without impacting other code that may be using the same events on that element.

//instead of
$(".ero").click(function(e) { });

//something like this
$(".ero").bind("click.mynamespace", function(e) {
    //code here
});

Upvotes: 1

DallinDyer
DallinDyer

Reputation: 1408

$('.ero') probably didn't exist yet. Try wrapping in ready, or using live

$('.ero').live('click', function() { ... }

Upvotes: 0

Related Questions