Click here to Skip to main content
14,929,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am calling an ajax call in which I am fetching the list of name in the Active Directory. What i get is a list of names which I can store it in the array.

The ajax call will return that array and it should become the javascript array so that I can pass that as a source for the autocomplete as a parameter.

I have heard somewhere that it is done using json_encode to convert php array to javascript one.

Please advice.


A novel solution:

Use the AJAX to return a javaScript function that maps data into an array. The function is constructed inside the AJAX script. You need to do this as a function in that it's rather annoying to try to put a script on an existing client page and then execute it - but not difficult if you sneak around, logically, and modify a function already existing on the page.

So, declare a dummy javaScript function on your page and then update its via the AJAX.

Now then, how do you get this function to execute?

In the AJAX return, after modifying the functions content, have an already written call to the function. This function will was in place to execute upon the return of your AJAX call. It will thus execute the modified script which can be the loading of your data into an array.

Don't forget to consider the scope of the data in your function - or at least, the scope of where you map the return values from the function.

Try the following example:
$phpArray = array(0,1,2,3);
echo json_encode($phpArray);

<script src=""></script>
$(document).ready( function() {
    $('#clickme').click(function() {
            type: 'POST',
            url: 'ajax.php',
            data: 'id=somedummydata',
            dataType: 'json',
            cache: false,
            success: function(result) {

               var jsArray = [];

               for (i = 0; i < result.length; i++) { 
                  // add the returned values to the JS array


<div id="result">Ajax input</div>
<div id="clickme">Click Me!</div>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900