skip to Main Content

How to append Ajax response to div in HTML

This is my ajax Code

$(document).ready(function(){
    $('.credit,.debit').change(function(){
        var value=$(this).val();
        $.ajax({
            type:"POST",
            url:"<?php echo base_url();>index.php/Transactions/getamountbyid",
            data:{id:value},
            success:function(result){
                console.log(result);
                $(".bal").html(result);
            }
        });
    });
});

This is my controller Code

public function getamountbyid(){
    $id=$this->input->post('id');
    $this->Transaction_model->getamountbyid($id);
    print_r($data1);
}

And THIS is my Ajax Response

Array ( [0] => stdClass Object ( [Accounts_id] => 1 [Accounts_number] => 123123123 [Account_Name] => Qualight [account_nickname] => Qualight [Address] => hyderabad [Mobile] => 9123912345 [account_type] => 1 [PAN_NO] => 1231231231 [GST_NO] => 123 [credit] => 20000.00 [debit] => [balance] => 20000.00 [Time_stamp] => 2020-02-13 18:51:49 ) )

I want to display account debit and credit balance after selecting the account from drop down it should be display below drop down can you please help me how to append required response data to required field or div

3

Answers


  1. if you only want to append then you need to use append() function. else Please provide the HTML as well so that I can understand your requirement and concept

    Login or Signup to reply.
  2. First off, change print_r($data1); to return json_encode($data1); if return doesn’t work then try echo.
    Next, change $(".bal").html(result); to $(".bal").html( result[0].credit+"<br>"+result[0].debit);

    Login or Signup to reply.
  3. You need to create a div with identifier where you want to show the credit/debit and populate this div with in ajax response.

    Firstly, use json_encode()

    public function getamountbyid(){
             $id=$this->input->post('id');
    $this->Transaction_model->getamountbyid($id);
    **print_r(json_encode($data1));**
        }
    

    Then, use

    $("#target-div").append(JSON.stringify(data));
    
    success: function (data) {
                for(var key in data) {
                var value = data[key];
                    html+='<div>'+key+':'+value+'</div>'
                }
                $("#target-div").append(html);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search