Pontek
Pontek

Reputation: 149

jquery closure ajax call, $(this) is null

I'm new to jquery, so this might seems simple but i can't see the trick :p
I'm using jquery 1.2.6 ( and i can't upgrade it :/ ) that's why I'm using the livequery plugin.

The context is just an update of a cart in a eshop.
The problem is that I don't get the value i want for "myid" in update_it.php.
- With example 1 (see the code below) it's working ! The call is made and i got the good value in update_it.php for "myid". But it is hardcoded, i want it to be generic (see example 2).
- With example 2 it's not working :( The alert is working, the call is working but i don't get any value for "myid"

Here is my javascript :

$(document).ready( function () {
    function update_it() {
        $.ajax({ 
            type: "POST",
            url: "./update_it.php",
            dataType: "json",
            data: "myid="+$(this).val(),
            success: function(msg){
                $("div#cart-full").html(msg.fullcart);
                $("div#cart").html(msg.mincart);
            },
            error : function(xhr, desc, e) {
                alert("ko - " + xhr.status);
            }
       });
    }

    // Example 1
    $("#mycheckbox_1").livequery("click", update_it);

    // Example 2
    $("input:checkbox[id^=mycheckbox_]").each(function(){
         $(this).livequery("click", update_it);
    });

});

Thanks for any help !

Upvotes: 0

Views: 208

Answers (1)

kenny chung
kenny chung

Reputation: 96

The example for the second selection on the jquery page involves a second set of quotation marks: jQuery( "[attribute^='value']" )

try $("input:checkbox[id^='mycheckbox_']").each(function(){

EDIT:

In that case, try the "ON" keyword in the following example instead of livejquery. http://jsfiddle.net/4LaQX/2/

$(function () {
    $(document).ready(function(){
        $("[id^='hoverme_']").each(function () {
          $(this).on("click", listen);  
        });
    });

    function listen(){
        alert($(this).html());
    }
});

And in the case of Jquery 1.2.6, the click() keyword

http://jsfiddle.net/4LaQX/5/

$(this).click(doSomethingFunc);


EDIT

$(document).ready( function () {


    // Example 2
    $("input:checkbox[id^=mycheckbox_]").click(update_it);


});
function update_it() {
            $.ajax({ 
                type: "POST",
                url: "./update_it.php",
                dataType: "json",
                data: "myid="+$(this).val(),
                success: function(msg){
                    $("div#cart-full").html(msg.fullcart);
                    $("div#cart").html(msg.mincart);
                    $("input:checkbox[id^=mycheckbox_]").unbind("click");
                    $("input:checkbox[id^=mycheckbox_]").bind("click");
                },
                error : function(xhr, desc, e) {
                    alert("ko - " + xhr.status);
                }
           });
        }

Upvotes: 1

Related Questions