I currently have a working AJAX request that sends a request to my PHP file and echos the result to the HTML. I am able to create an alert that shows the array of data. How do I parse the data and insert each one specifically into the div classes? I know you might be thinking “just use a table or a list” My actual code is much more structured, the data must be inserted into the specific divs.
Script
$(function(){
$(".task-listing").click(function() {
$.ajax({
type: 'POST',
url: 'php/task-info-get.php',
dataType: 'json',
data: 'pid=' + $(this).attr("id"),
success: function (response) {
alert(response);
}
})
});
});
HTML div I want Data in
<div class="data">
<div class="task_date"></div>
<div class="title"></div>
<div class="description"></div>
<div class="location"></div>
<div class="startdate"></div>
<div class="tasktime"></div>
<div class="price"></div>
</div>
PHP
<?php
include 'sqlconnection.php';
$conn = OpenCon();
$stmt = $conn->prepare('SELECT task_date,title,description,location,price,startdate,tasktime FROM tasks WHERE pid='.$_POST['pid']);
$stmt->execute();
$stmt->bind_result($task_date,$title,$description,$location,$price,$startdate,$tasktime);
while($stmt->fetch()) {
$output[]=array($task_date,$title,$description,$location,$price,$startdate,$tasktime);
}
$json=json_encode($output);
echo $json;
$stmt->close();
CloseCon($conn);
?>
4
Answers
If the response is always an array with full enough content (length = 7) & in order as childs in div.data tag, you can just do this with Jquery:
E.g: https://jsbin.com/cikacohalu/edit?html,js,output
For more complicated html structure, use direct selector to set their content:
I would recommend the @Nick’s answer, that you have exact key name for each field from PHP backend to client.
You can use like this,
I have appended the final contents in
body
tag. you may use the parent ofclass='data'
.I would modify your PHP to return an associative array, with the keys being the class of the relevant
div
you want the data to go into:Then in your JS you can simply use the keys of the response to fill the divs:
Here’s a snippet demonstrating the code (using a normal rather than arrow function):
Can you please share your response if possible?
Is it a single object?
if single object then it’s not good to assume and iterate through a loop to get specific key-value based on an index of an array. eg. task_date is at 2 positions in an array.
parse your ajax response first eg. var jsonres=JSON.parse(result);
append your value by jquery selecter $(“.task_date”).html(data);