Lara Ch
Lara Ch

Reputation: 165

AJAX datatype JSON and HTML

I am following a tutorial about ajax and I have made this script, where I get data as JSON and append them into a table:

$.ajax({
    url: 'insert.php', 
    type: 'POST', 
    data: {data1: name, data2: phone, data3: address},
    dataType: "json", 
    success:function(res){
        //if(data=="success")
        //{
            //alert("Data added");
            //console.log(arr.id);
            $("#trId").before("<tr><td>"+res.emp_name+"</td><td>"+res.ph+"</td><td>"+res.add+"</td></tr>");
        //}
    },
    error:function(res){
        alert("data not added");
    }

And here is the PHP code:

$insert = "INSERT into employee(emp_name, phone, address) VALUES (:emp_name, :ph, :add)";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":emp_name", $emp_name);
$insertStmt->bindValue(":ph", $pos);
$insertStmt->bindValue(":add", $address);
$insertStmt->execute();

//echo "success";
$lastid = $conn->lastInsertId();
$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo json_encode($res);

Our instructor asked us to transform this script, from JSON as datatype into HTML, and make the initial changes for it. But I can't figure out what should the PHP code returns now, and how to append the returned values into the table.

Secondly, why some people use HTML as datatype while JSON is better ?

Upvotes: 1

Views: 3733

Answers (1)

u_mulder
u_mulder

Reputation: 54841

Set dataType to html:

dataType: "html"

And render html on server:

$res = array('name'=>$emp_name, 'ph'=>$pos, 'add'=>$address, 'id'=>$lastid);
echo "<tr><td>" . $res['name'] . "</td><td>" . $res['ph'] . "</td><td>" . $res['add'] . "</td></tr>"";

So in a success callback you will receive html:

success: function(res) {
    $("#trId").before( res );
}

Why use html instead of json - is an opinion-based or a case-based question.

Upvotes: 2

Related Questions