简体   繁体   中英

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>

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/

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.

In your JS file you could write this

 $.ajax({
    type: 'POST',
    url: posts_in.php,
    data: {
       action: 'updateDomAfterAjaxCall',
       post_id: postentry
   },

   success: function(data, textStatus, XMLHttpRequest) {

       var linkid = '#' + postentry;
       jQuery(linkid).html('');
       jQuery(linkid).append(data);

   },
   error: function(MLHttpRequest, textStatus, errorThrown) {
       alert(errorThrown);
   }
 });
 

In your backend code, you could do this. In this case, I used PHP.

 function updateDomAfterAjaxCall() {

    $post_ID = $_POST['post_id'];
    // Carefully tranverse the dom to 
    // Update records of the DOM that is 
    // affected by the new entry
    // so that it behave almost like
    // headless browser
    // Target footer-postentry
    // header-postentry, sidebar-postentry, content-postentry

    $result = '';
    $record_from_db = ""

    $results.='<div class="myclass" >'.$record_from_db.'</div>';
    die($result);
  }
$.post(  
     "posts_in.php",  
     $("#postentry").serialize(),  
        function(data){  
            $('#myDivOnThePage').append(data);
        }  
 );  

If data contains new record, so yes, parse it and append where and like you want.

By creating a new jsfiddle.net with an example, I can help you a little bit more...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM