简体   繁体   中英

Return multiple results with AJAX from sql query in php

Hello I am realizing simple AJAX request and would like to be able to store the results from the SQL SELECT query into 3 different ajax variables.

Where 2 of them will store one variable and the other one have to store foreach results.

Let's say my AJAX request is the following:

$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
              $("#time-result").html(data.result01);
              $("#time-sum-result").html(data.result02);

Where I will have 2 results result01 and result02

In the current state of my script inside the mysql select request what is returning like data is the following:

        $stmt = $con->prepare( $sql );                      
        $stmt->setFetchMode(PDO::FETCH_ASSOC);
        $stmt->execute();       
foreach($stmt as $row) {
            echo "<tr>
                     <td>".$row['clientname']."</td>   
                     <td>".$row['taskname']."</td>
                     <td>".$row['department']."</td>
                     <td>".$row['note']."</td>
                     <td>".$row['caseid']."</td>
                     <td>".$row['time']."</td>                                                                        
                    </tr>";                     
            }

I would like to put the result of the forreach as it is inside the echo, where it will contains various iterations and then for result02 for example would like to put only one row of the same query for example like: $row['date']

In this case

data.result01 - will have all the code of the <tr></tr> data.result02 - will have only one variable which is date.

Question is how to dump the foreach into result01 and in the same time to put in result02 only one row from the same query. $stmt

Export all your data first then use it with jquery ? Something like :

PHP :

foreach($stmt as $row) {
   $arr_out[] = $row;
}
echo json_encode($arr_out);
exit();

JQUERY :

var result1 = "";

$.post('includes/check_number.php', {'date':date, 'userid':userid}, function(data) {
  $.each(data, function(key, item) {
     result1 += "<tr><td>"+item.clientname+"</td>[...]<td>"+item.time+"</td></tr>";
     result2 = item.date;
  });
  $("#time-result").html(result1);
}

I didn't test this code, hope it will help you.

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