Trying to post to a PHP file that returns a JSON response and then use it to display results but only one record is displayed with undefined values.
Here is the JSON response from core/backend/comm.php:
{
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"username": "xyz",
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"username": "abc",
},
<!--JSON RESPONSE ENDS-->
Here is the code that I have tried but not working:
$('[id^="cat"]').click(function() {
// do something
var prot= this.getAttribute("prot");
jQuery.ajax({
url: "core/backend/comm.php",
data:{ prot: prot },
// $("#query_form").serialize(),
type: "POST",
success:function(data){
// $("#repo").html(data);
data = [data];
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].name + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].username + '</p>';
htmlText += '</div>';
}
$('#repo').append(htmlText);
},
error:function (){}
});
});
Corrected Code:
$('[id^="cat_"]').click(function() {
// do something
var prot= this.getAttribute("prot");
jQuery.ajax({
url: "core/backend/comm.php",
// dataType: "text",
data:{ prot: prot },
// $("#query_form").serialize(),
type: "POST",
success:function(data){
// $("#repo").html(data);
console.log(data);
var data = JSON.parse(data);
var htmlText = '';
for ( var key in data ) {
htmlText += '<div class="div-conatiner">';
htmlText += '<p class="p-name"> Name: ' + data[key].name + '</p>';
htmlText += '<p class="p-loc"> Location: ' + data[key].location + '</p>';
htmlText += '<p class="p-desc"> Description: ' + data[key].description + '</p>';
htmlText += '<p class="p-created"> Created by: ' + data[key].created_by + '</p>';
htmlText += '<p class="p-uname"> Username: ' + data[key].username + '</p>';
htmlText += '</div>';
}
$('#repo').append(htmlText);
},
error:function (){}
});
});
Here is the corrected JSON response:
[ {
"name": "Rehan",
"location": "Pune",
"description": "hello hi",
"created_by": 13692,
"username": "xyz"
},
{
"name": "Sameer",
"location": "Bangalore",
"description": "how are you",
"created_by": 13543,
"username": "abc"
}]