0

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
......
1
  • @NishitMaheta: He is receiving JSON in JS, no reason to use PHP json_decode. Commented Jul 13, 2015 at 6:05

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your time...I'll keep it as alternative answer
1

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;

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.