简体   繁体   中英

using json as datatype in ajax

I am trying to chang my AJAX script that have a text as datatype, into JSON.

the datatype:"text" was working well, so I tried to change it to this script:

In the PHP code:

header("Content-type: application/json");

$emp_name = $_POST['d1'];
$pos = $_POST['d2'];
$sal = $_POST['d3'];

$insert = "INSERT into emp(name, pos, sal) VALUES (:emp_name, :pos, :sal)";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":emp_name", $emp_name);
$insertStmt->bindValue(":pos", $pos);
$insertStmt->bindValue(":sal", $sal);
$insertStmt->execute();

    //echo "success";
   while($row = $insertStmt->fetch())
   {
        $data[]=$row;
    }
    echo json_encode($data);

And here is what I changed in my AJAX script:

$("#btnClicked").click(function()
{
    var emp = $("#name").val();
    var pos = $("#pos").val();
    var sal = $("#sal").val();

    $.ajax
    ({
        url: 'insert.php',
        type: 'POST',
        data: {d1: emp, d2: pos, d3: sal},
        dataType: "JSON",

        function(data)
        {
            console.log(data);
        }

    });
});

I need to see the data first in the console.

Data are added to the server and will show in my html table when refresh, but they don't appear in the console.

Their is no error shown in the console.

So how to see them, and how to append my table with json returned data.

I'm not sure about jQuery but I think the function should be more like this with a success handler

$("#btnClicked").click(function(){
    var emp = $("#name").val();
    var pos = $("#pos").val();
    var sal = $("#sal").val();

    $.ajax({
        url: 'insert.php',
        type: 'POST',
        data: {d1: emp, d2: pos, d3: sal},
        dataType: "JSON",
        success:function(data){
            console.log(data);
        },
        error:function(err){alert(err)}    
    });
});

Didn't notice the php code until pointed out by Barmar - instead of trying to return data from an insert statement perhaps you could send back your own array of data to the js function.

header("Content-type: application/json");

$emp_name = $_POST['d1'];
$pos = $_POST['d2'];
$sal = $_POST['d3'];

$insert = "INSERT into emp(name, pos, sal) VALUES (:emp_name, :pos, :sal)";
$insertStmt = $conn->prepare($insert);
$insertStmt->bindValue(":emp_name", $emp_name);
$insertStmt->bindValue(":pos", $pos);
$insertStmt->bindValue(":sal", $sal);
$insertStmt->execute();

echo json_encode( array('name'=>$emp_name, 'position'=>$pos, 'salary'=>$sal ) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM