0

I have page getorgname.php which return array so how do i get the array in my jquery page using $.ajax method?

$ds = my_ldap_connect(CHI_LDAP_LOCATION, CHI_LDAP_PORT, CHI_LDAP_USE_TLS);
$groups = get_all_groups($ds, CHI_LDAP_BASE_DN, CHI_LDAP_BIND_DIRECTORY, CHI_LDAP_BIND_PASSWORD);
$sr = @ldap_search($ds, "ou=people,".CHI_LDAP_BASE_DN, "(uid=*)");
$nt = ldap_get_entries( $ds, $sr );
//echo "<pre>";
//print_r($nt);
//echo "</pre>";
foreach( $nt as $each )
{
    if( is_array( $each ) )
    {

        $json[] = trim('"'.$each['o'][0].'"');

    }
}

return $json;

2 Answers 2

2

Set the proper json headers to serve json and print the array in json format:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json'); 

//create your array here

echo json_encode(array);

Then receive the array on the client side using jQuery:

$.ajax({
   url: 'getorgname.php',
   dataType: 'json',
   success: function(data){
       //the 'data' object contains your array
       //do stuff with it here
   }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Without setting the data-type in jQ's $.ajax call, and by simply using the echo construct rather then return, you should be fine. If you start messing with the headers, chances are you'll run into trouble sooner or later:
You can only set the headers if no output has been generated yet, so be weary: either buffer, or keep the header calls at the very top. Just know what you're doing.

In your case just ending in echo json_encode($json); will do the trick:

foreach( $nt as $each )
{
    if( is_array( $each ) )
    {
        $json[] = trim($each['o'][0]);
    }
}
echo json_encode($json);

That's all you need to do, you don't have to format the JSON manually.
Your jQ should look something like this:

$.ajax({
    url: 'yourscript.php',
    data: yourRequestObject,
    success: function(response)
    {
        console.log(response);//this'll be either an array or an object (assoc array's are objects in JS)
    }
});

2 Comments

Don't forget dataType: "json" to avoid issues if jQuery fails to detect that it's json and not plain text.
@KevinB: Well, 9 out of 10 jQuery's "educated guess" is correct (I haven't seen it go wrong once). That said, I haven't used jQuery in over a year now... :)

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.