Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update the DOM after Ajax Call (jQuery)?

How can I update the DOM with new record added element after call?

Should I return the newly inserted db record contents on call back then append using jquery?

Please advice if not enough data to answer question.

$(function(){

        $('#postentry').submit(function() {
          var tyu = $('#tittle_ent').val();
          if(tyu.length <= 2)
            {alert('Enter More Text!'); return false;}else
            {
                $.post(  
                 "posts_in.php",  
                 $("#postentry").serialize(),  
                    function(data){  
                        //alert(data); 
                    }  
                );  
                return false;
            }
        });

    });

Each record look like this:

<div id="post349" class="myclass">
This is some text.    
</div>
like image 640
Codex73 Avatar asked Jul 15 '11 22:07

Codex73


2 Answers

I'd use $.ajax() instead of $.post():

$.ajax({
    type:'post',
    url: 'posts_in.php',
    data: $("#postentry").serialize(),
    success:function(data){
        var id='post349';
        $('<div></div>').attr('id',id).addClass('myclass').html(data).appendTo('#records_wrapper');
    }
});

Quick demo of how the div will be appended and populated: http://jsfiddle.net/AlienWebguy/zuPA2/1/

like image 122
AlienWebguy Avatar answered Nov 12 '22 05:11

AlienWebguy


You can either return a complete record in the surrounding div from php or you can just get the newly inserted ID and build the record in javascript.

like image 29
jeroen Avatar answered Nov 12 '22 05:11

jeroen