0

I am using a jQuery ajax post function to enter a new row in the database and then output some HTML on .done()

It works well with out putting it into a function. But for some reason when I add this to a function it stopped working. Can anyone please help me figure this out?

Below is my code

Function page:

function add_items(){



    var id = ($(this).attr("id"));

    //Insert a new row using an ajax post method, post the the id to reference
    //under which category the menu item should go under
    var adtnl_item = $.post("ItemCreate.php", {id : id })


    .fail(function(){
        console.log( "New Row Can't be added" );
    })

    //Append the new menu item input fields to the div class
    //.menu_item_wrapper that has an id of the mainØ category ID
    .done(function(data) {
         return $('.menu_item_wrapper[id="' + id + '"]').append(data);

    });

}

Index page:

    $(".add_item").on("click", function(){


        add_items();



    });
Hristo Enev
  • 2,421
  • 18
  • 29
elrado88
  • 75
  • 3
  • 8
  • Please see http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – Jasen Sep 16 '14 at 17:46
  • Is something happening? Any errors in the console? Also check the ajax request - in Chrome -> developer tools -> Network – Hristo Enev Sep 16 '14 at 17:53

1 Answers1

0

when you call add_items() from inside the on click function, this no longer represents the element from inside the add_items function. Try passing your element in to the function

function page 

function add_items(el){
    var id = ($(el).attr("id"));

    //Insert a new row using an ajax post method, post the the id to reference
    //under which category the menu item should go under
    var adtnl_item = $.post("ItemCreate.php", {id : id })
    .fail(function(){
        console.log( "New Row Can't be added" );
    })

    //Append the new menu item input fields to the div class
    //.menu_item_wrapper that has an id of the mainØ category ID
    .done(function(data) {
         return $('.menu_item_wrapper[id="' + id + '"]').append(data);
    });
}

index page 

$(".add_item").on("click", function(){
    add_items(this);
});
Zombiesplat
  • 943
  • 8
  • 19
  • 1
    or can keep `this` in handler function and pass handler as reference `$(".add_item").on("click",add_items);` – charlietfl Sep 16 '14 at 18:13