Reputation: 11
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;
Upvotes: 0
Views: 150
Reputation: 76395
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)
}
});
Upvotes: 1
Reputation: 35194
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
}
});
Upvotes: 2