Frank
Frank

Reputation: 949

jQuery: Can't retrieve an attribute of a dynamically created DOM element

Here's the situation: I'm writing a simple AJAX application that performs CRUD functions. When the user double clicks on a particular element, the element changes into a text box so that they can edit inline. When the text box loses focus (code for which is below), the value of the textbox gets POSTed to a PHP script that updates the database.

All is groovy except for one thing. When I create a new record, which gets popped onto the top of the list with AJAX, I can't edit that record without refreshing the page. I mean, the edit looks like it's been committed, but when you refresh, it reverts back to the original. After refreshing, there are no issues.

To boil it down: When I try to run the following code on newly created rows in my table (both in the database and on the page), the edit appears to be made on the page, but never makes it to the database.

//Make changes on FOCUSOUT
    $('#editable').live('focusout', function(){
        var parentListItem = $(this).parents('li');
        var theText = $(this).val();
        var parentListItemID = parentListItem.parents('ul').attr('id');

        $(this).remove();
        parentListItem.html(theText);
        parentListItem.removeClass('beingEdited');

        $.post("databasefuncs.php?func=edit", { postedMessage: parentListItemID, fullTextContent: theText },
            function(result){
                if(result == 1) {
                    parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
                } else {
                    alert(result);
                }

            });

    });

Upvotes: 0

Views: 363

Answers (2)

Ady Ngom
Ady Ngom

Reputation: 1302

Your problem is that the post executes but the function you target (func=edit) never fires, the params you are sending after the question mark are never read by your php, you are sending a post request and wanting it to behave like a get by attaching parameters to the URL, change your request to:

$.ajax({
 type: "POST",
 url: "databasefuncs.php",
 data: {func: "edit", postedMessage: parentListItemID, fullTextContent: theText},
 success: function(data, textStatus, jqXHR) {
    if(textStatus === "success") {
      parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
    }
    else {
       alert(textStatus);
    }
 } 
});

Now in your PHP you have $_POST["func"] = "edit";

Hope this is clear and it helps. Cheers.

Upvotes: 0

Aditya Manohar
Aditya Manohar

Reputation: 2274

I suppose you are not binding the event to the new DOM Element loaded via AJAX.

Upvotes: 1

Related Questions