112233
112233

Reputation: 2466

how to display array passed via ajax in html

This is my ajax:

$("#submit").on("click",function()
    {

          $("#add_car_form").submit(function(){           
            var data = {
              "action": "test"
            };
            data = $(this).serialize() + "&" + $.param(data);
            $.ajax({
              type: "POST",
              dataType: "text",
              url: "add_car_submit.php", //Relative or absolute path to response.php file
              data: data,
              success: function(data) {

                $(".the-return").html("<br />JSON: " + data );//this outputs 

{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}

              }
            });
            document.getElementById("add_car_form").reset();
            return false;
          });

        });

I simply echo from php script like this: echo $return["json"]; and it will output like this:

{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}

How do append to a div in html table form like this?

Car Name: name
Car Maker: maker
......

Upvotes: 0

Views: 4787

Answers (2)

Raghavendra
Raghavendra

Reputation: 3580

try this in your success function

data = jQuery.parseJSON( data );  //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
  out += '<tr><td>'+key+': '+ value +'</td></tr>';
});

out += '</table>';

//append out to your div
 $(".the-return").html(out);

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

You should not create a form submit handler inside a click handler as it could create multiple listeners for single click event.

I think you could just encode the data use json_encode in the server side then, accept the response as json in the client using dataType: 'json' then

$("#submit").on("click", function () {

    var $form = $("#add_car_form")
    var data = {
        "action": "test"
    };
    data = $form.serialize() + "&" + $.param(data);
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "add_car_submit.php", //Relative or absolute path to response.php file
        data: data,
        success: function (data) {

            $(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here

        }
    });
    document.getElementById("add_car_form").reset();
    return false;

});

Upvotes: 1

Related Questions