Search code examples
javascriptjquerydomecmascript-5

How refresh particular div without reload whole page?


<div id="success_hold">
<?php
    if($row['mandate_end']!=date('Y-m-d') && $row['job_position']=='unhold')
    {
        echo '<span class="badge badge-success">Open</span>';
    }
    else
    {
        echo '<span class="badge badge-warning">Hold</span>';
    }
?>
</div>

<script>
    $(document).ready(function(){
        var flag =  1;
        $(".hold").click(function(){
            job_id = this.id;
            if(flag == 1)
            {
                $.ajax({
                    type:"POST",
                    data:{"job_id":job_id},
                    url:"<?php echo base_url(); ?>pausehold",
                    success:function(data){
                        $("#success_hold").load("#success_hold");
                    }
                });
                flag = 0;
            }
            else
            {
                $.ajax({
                    type:"POST",
                    data:{"job_id":job_id},
                    url:"<?php echo base_url(); ?>resumehold",
                    success:function(data){
                        $("#success_hold").load("#success_hold");
                    }
                });
                flag = 1;
            } 
        }); 
    });
</script>

I have div where id="success_hold". Now, what happens when I click on class="hold" I am updating my data. Now, I want to refresh my <div id="success_hold"> without reload whole page where I am using .load() function But the problem is that when I use .load() the function shows the whole page in success_hold. So, How can I fix this issue? I want to refresh only success_hold.

Thank You


Solution

  • The problem is because load() is used to make another AJAX request and place the a portion of the HTML retrieved from that request in the target element.

    As you're already making an AJAX request to get the data, which is presumably HTML, you simply need to append() data to the container.

    Also note that the only difference between the two sides of your condition is the URL the request is sent to, so you can easily DRY this code up:

    $(document).ready(function() {
      var flag = true;
    
      $(".hold").click(function() {
        var url = '<?php echo base_url(); ?>' + (flag ? 'pausehold' : 'resumehold');
        flag = !flag;
    
        $.ajax({
          type: "POST",
          data: { job_id: this.id },
          url: url,
          success: function(data) {
            $("#success_hold").append(data);
          }
        });
      });
    });
    

    If data contains the entire page, then you should change that PHP file to return only the relevant HTML as it will help to speed up the request. If, for whatever reason, you can't do that then you can extract the required element from the response like this:

    $("#success_hold").append($(data).find('#success_hold'));