2

this is my ajax code to retrieve all data from a php file:

<script type="text/javascript">
 $(document).ready(function() {
    $("#display").click(function() {                
      $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "read.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){                    
            $("#responsecontainer").html(response); 
            //alert(response);
        }
    });
});
});
</script>
<h3 align="center">Manage Student Details</h3>
<table border="1" align="center">
   <tr>
       <td> <input type="button" id="display" value="Display All Data" /> </td>
   </tr>
</table>
<div id="responsecontainer" align="center"></div>

And this is part of my php file witch retrieves data from database and stores it into variables :

    <?php
  while($row = mysqli_fetch_assoc($result)){
    $user_id = $row["user_id"]
    $user_name = $row["user_name"]
    $user_text = $row["user_text"]
    }
    ?>

If I echo the above variables then they will be shown in my html page whitch contains ajax codes but I want to get each variable with ajax and do some operations on them and then show them in my html page
There is Simple html dom in php to get one page's html elements is there anything like php simple html dom for ajax? if not then how is it possible to do the things I said?
I'll be appreciate that if someone can help me with this:)

2 Answers 2

1

Server side

$array = array();
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){

                        array_push(//what you need);

                }
echo json_encode($array);

And on the client side

success: function(response){                    
            data = $.parseJSON(JSON.stringify(returnedData)); 

        }

Note that JSON.stringify is not needed however I like it data is now an object and you can access its properties with data.propertyname

Sign up to request clarification or add additional context in comments.

Comments

0

You have to return a JSON object with the variables. Make an array outside the while loop, and then on each while loop do array_push to the main array. After the loop echo the array through json_encode and then decode it on the ajax end.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.