I am trying to display data fetched as JSON from MySQL DB using PHP into an HTML element say a table. Below is my code for this:
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#display").change(function()
{
var type = document.getElementById('display').value;
$.ajax(
{
//create an ajax request to load_page.php
type: "POST",
url: "DBOperations.php",
data : "type=" +type,
dataType: "text", //expect text to be returned
success: function(response)
{
var tr = $('<tr>');
tr.append('<td>' + response.client_id + '<td>');
tr.append('<td>' + response.client_name + '<td>');
tr.append('<td>' + response.client_title + '<td>');
tr.append('<td>' + response.client_type + '<td>');
$('#myTable').append(tr);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('error: ' + textStatus + ': ' + errorThrown);
alert(response);
}
});
});
});
</script>
</head>
<body>
<form>
<select id="display" name="clienttype" onchange="showClient(this.value)">
<option value="">Select a Client:</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</form>
<br>
<table id="myTable">
<tr>
<th>ClientID</th>
<th>ClientName</th>
<th>ClientTitle</th>
<th>ClientType</th>
</tr>
</table>
</form>
</body>
</html>
Here is what i am getting from php as JSON:
[{"client_id":"1","0":"1","client_name":"asdf","1":"asdf","client_title":"asdf","2":"asdf","client_type":"a","3":"a"}]
Besides if i set the datatype in AJAX to json, it displays the error as in this question: how to remove parsererror: SyntaxError: Unexpected token < in JSON at position 0
So i keep it as either html or text which at least displays the response wtihout the error. but i need to format the response and feed it to another element.
Thanks in advance.