简体   繁体   中英

How to Insert ajax data into table in modal

This is the ajax code that takes the data in json and creates a table with the data. But I'm getting this error:

parsererror

 $('#loadddx').click(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr('href'), // Example: ajax.php?id= dataType: 'json', success: function(resp) { var trHTML = ''; $.each(resp, function(i, userData) { for (i = 0; i < resp.userData.length; i++) { trHTML += '<tr><td>' + resp.userData[i].pais + '</td><td>' + resp.userData[i].data + '</td><td>' + resp.userData[i].origem + '</td><td>' + resp.userData[i].ip + '</td><td>' + resp.userData[i].isp + '</td><td>' + resp.userData[i].browser + '</td><td>' + resp.userData[i].os + resp.userData[i].newid + '</td></tr>'; } }); $('#result').append(trHTML); console.log(resp); $("#showDataa").modal("show"); }, error: function(xhr, status) { console.log(status); } }); }); 

Here is the .php file that returns the data

 $res = []; while ($stmt - > fetch()) { $res[] = array("success" => true, "pais" => $pais, "data" => $data, "origem" => $origem, "ip" => $ip, "isp" => $isp, "browser" => $browser, "os" => $os, "newid" => $newid); echo json_encode($res); } 

Can anyone help me?

Try updating your PHP as follows:

$stmt->fetch();
echo json_encode(array("success" => true, "pais" => $pais, "data" => $data, "origem" => $origem, "ip" => $ip, "isp" => $isp, "browser" => $browser, "os" => $os, "newid" => $newid));

Not sure what the while loop was for? If the values within the loop are globals being updated by $stmt->fetch() each iteration and you need multiple iterations try the following:

$res = [];
while($stmt->fetch()) $res[] = array("success" => true, "pais" => $pais, "data" => $data, "origem" => $origem, "ip" => $ip, "isp" => $isp, "browser" => $browser, "os" => $os, "newid" => $newid);
echo json_encode($res);

UPDATE

Update your JS as follows, assuming you used the first PHP example I gave you. Not sure the way you are appending your table rows is the best, but this should resolve your issue. If it doesn't please provide the console.log output for resp:

 $('#loadddx').click(function(e) { e.preventDefault(); $.ajax({ url: $(this).attr('href'), // Example: ajax.php?id= dataType: 'json', success: function(resp) { console.log(resp); $('#result').append( '<tr><td>' + resp.pais + '</td><td>' + resp.data + '</td><td>' + resp.origem + '</td><td>' + resp.ip + '</td><td>' + resp.isp + '</td><td>' + resp.browser + '</td><td>' + resp.os + resp.newid + '</td></tr>'; } $("#showDataa").modal("show"); }, error: function(xhr, status) { console.log(status); } }); }); 

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