0

I am trying to make a search box in my web application, and I used ajax post to make a request to my server. My question is:

Is it possible to send looped array values from PHP to my JavaScript? I want to get all of the results from my server.

CLIENT SIDE: Ajax POST request

<script type="text/javascript">
$(document).ready( function() {
   $.ajax({
       type: "POST",
       url: "searchPlaces.php",
       data: { searchInput: form.searchTxtId.value },
       success: function (result)
       {
            // Get the search result
       }
   });
});
</script>

SERVER SIDE (after retrieving the post from ajax, and making queries):

while ($result = mysql_fetch_assoc ($query))
{
   $resultName = $result['name'];
   $resultAddress = $result['address'];
}
2
  • possible duplicate of array from php to JavaScript Commented Aug 30, 2012 at 23:21
  • 1
    You can't mix-and-match HTML and JavaScript comments that way; if you're putting a place-holder comment in your JavaScript, it should probably be a JavaScript comment. Commented Aug 30, 2012 at 23:22

2 Answers 2

0
$results = array();
while ($result = mysql_fetch_assoc ($query)) {
   $results[] = $result;
}
echo json_encode(array('results' => $results));

In your success callback you can then iterate over result.results which contains an object with the column names from your query as attributes.

success: function(result) {
    $.each(results, function(i, row) {
        console.log(row.name, row.address);
    })
}

It is also advisable to use dataType: 'json' in your $.ajax({...}); arguments to avoid unnecessary guessing of the response type.

In case you have more columns in the SQL resultset than you want to forward to the client, you could add a custom array in the loop:

$results[] = array('name' => $row['name'], 'address' => $row['address']);
Sign up to request clarification or add additional context in comments.

Comments

0

yes you can you can return a json string :

$.ajax({
       type: "POST",
       dataType: 'json', // return type is json ;
       url: "searchPlaces.php",
       data: { searchInput: form.searchTxtId.value },
       success: function (result)
       {
            $.each($result,function(index, value){
                 // use params
            } 
       }
   });

and on your php side you use json_encode()

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.