skip to Main Content

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


  1. 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:

    const responses = [1, 2, 3, 4, 5, 6, 7];
    $('.data').children().each((index, child) => {
        $(child).text(responses[index])
    });
    

    E.g: https://jsbin.com/cikacohalu/edit?html,js,output

    For more complicated html structure, use direct selector to set their content:

    $('.data .task_date').text(response[0]);
    $('.data .title').text(response[1]);
    $('.data .description').text(response[2]);
    $('.data .location').text(response[3]);
    $('.data .startdate').text(response[4]);
    $('.data .tasktime').text(response[5]);
    $('.data .price').text(response[6]);
    

    I would recommend the @Nick’s answer, that you have exact key name for each field from PHP backend to client.

    Login or Signup to reply.
  2. You can use like this,

      $(function(){
            $(".task-listing").click(function() {
                $.ajax({
                    type: 'POST',
                    url: 'php/task-info-get.php',
                    dataType: 'json',
                    data: 'pid=' + $(this).attr("id"),
                    success: function (response) {
                        var jsonres=JSON.parse(result);
                        htmlconts='';
                        for (i in jsonres) {
                            htmlconts+='<div class="data">
                                <div class="task_date">'+jsonres[i][0]+'</div>
                                <div class="title">'+jsonres[i][1]+'</div>
                                <div class="description">'+jsonres[i][2]+'</div>
                                <div class="location">'+jsonres[i][3]+'</div>
                                <div class="startdate">'+jsonres[i][4]+'</div>
                                <div class="tasktime">'+jsonres[i][5]+'</div>
                                <div class="price">'+jsonres[i][6]+'</div>
                            </div>';
                        }
                        $("body").append(htmlconts);
                    }
                });
            });
        }); 
    

    I have appended the final contents in body tag. you may use the parent of class='data'.

    Login or Signup to reply.
  3. 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:

    while($stmt->fetch()) {
        $output[]=array(
            'task_date' => $task_date,
            'title' => $title,
            'description' => $description,
            'location' => $location,
            'price' => $price,
            'startdate' => $startdate,
            'tasktime' => $tasktime
        );
    }
    

    Then in your JS you can simply use the keys of the response to fill the divs:

    success: function (response) {
        Object.keys(response[0]).map(k => $('.' + k).text(response[0][k]));
    }
    

    Here’s a snippet demonstrating the code (using a normal rather than arrow function):

    let response = [{
      task_date: "2020-02-26 17:56:15",
      title: "cccccccccccccc",
      description: "cccccccccccccc",
      location: "Remote",
      price: 44,
      startdate: "2020-02-14",
      tasktime: "00:03:33"
    }]
    
    Object.keys(response[0]).map(function(k) {
      $('.' + k).text(response[0][k]);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>
    Login or Signup to reply.
  4. 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);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search