Jump to content
PriyaSingh

How to pull selected attribute data from ajax called data?

Recommended Posts

i have been able to fetch data with an ajax call from active directory .The php file used to fetch data from active directory is below :

<?php
$username = 'maxxxxxxx';
$password = 'xxxxxxxxx';
$server = 'ldap://xxxxxxx';
$domain = '@asia.xxxxxx.com';
$port = 389;

$ldap_connection = ldap_connect($server, $port);

if (! $ldap_connection)
{
echo '<p>LDAP SERVER CONNECTION FAILED</p>';
exit;
}

// Help talking to AD
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);

$ldap_bind = @ldap_bind($ldap_connection, $username.$domain, $password);

if (! $ldap_bind)
{
echo '<p>LDAP BINDING FAILED</p>';
exit;
}
else
{
     echo 'login successful';
}

$base_dn = "OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxx,DC=com";

$dispname="Mark Hwett";


$filter ="(&(objectClass=user)(displayName=$dispname))";

$attr = array("sn","givenname","employeeid","distinguishedname","displayname","samaccountName","department","manager","mail","title","thumbnailphoto");

$result = ldap_search($ldap_connection,$base_dn,$filter,$attr);

$rescount = ldap_count_entries($ldap_connection,$result);

$data = ldap_get_entries($ldap_connection,$result);


if ($data["count"] > 0)
{
for ($i=0; $i<$data["count"]; $i++)
{
echo "<p> sn: " . $data[$i]["sn"][0]."<br/>";
echo "givenname: ". $data[$i]["givenname"][0] ."<br/>" ;
echo "employeeID: " . $data[$i]["employeeid"][0]."<br/>";
echo "distinguishedName: " . $data[$i]["distinguishedname"][0]."<br/>";
echo "displayName: " . $data[$i]["displayname"][0]."<br/>";
echo "sAMAccountName: " . $data[$i]["samaccountname"][0]."<br/>";
echo "department: ". $data[$i]["department"][0]."<br/>";
echo "manager: " .$data[$i]["manager"][0]."<br/>";
echo "mail: ". $data[$i]["mail"][0]."<br/>";
echo "title: " .$data[$i]["title"][0]."<br/>";
//echo "photo: " .$data[$i]["thumbnailphoto"][0]."<br/>";


// echo "<br/><br/>";
}
}
else
{
echo "<p>No results found!</p>";
}


?> 

The browser console shows that the above php returns this :

<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk@abc.com<br/>
title: xyz<br/> 

I want to take only some attributes from above data like mail,displayname etc and display in my HTML :

<h2 class="profile__name" id="emailOfUser">Email : </h2> 

Now the problem is the jquery that I have used here :

$('.leaderboard li').on('click', function () {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {id:$(this).find('.parent-div').data('name')},
success: function(data){
console.log(data);

$('#popup').fadeIn();

$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data



//whatever you want to fetch ......
// etc ..
},
error: function(){
alert('failed, possible script does not exist');
}
});
}); 

problem is this :

$('#emailOfUser').html(data); 

this line displays all data whereas I want to select only email,displayname from the above console data

kindly help me how to select only desired attribute data from the above browser console data i. the data returned by the ajax call.

Share this post


Link to post
Share on other sites

That big HMTL string your PHP outputs

echo "<p> sn: " . $data[$i]["sn"][0]."<br/>";
echo "givenname: ". $data[$i]["givenname"][0] ."<br/>" ;
echo "employeeID: " . $data[$i]["employeeid"][0]."<br/>";
echo "distinguishedName: " . $data[$i]["distinguishedname"][0]."<br/>";
echo "displayName: " . $data[$i]["displayname"][0]."<br/>";
echo "sAMAccountName: " . $data[$i]["samaccountname"][0]."<br/>";
echo "department: ". $data[$i]["department"][0]."<br/>";
echo "manager: " .$data[$i]["manager"][0]."<br/>";
echo "mail: ". $data[$i]["mail"][0]."<br/>";
echo "title: " .$data[$i]["title"][0]."<br/>";
is useless.

 

Use JSON instead.

 

1. PHP will report that you're outputting HTML by default. You are not. Override that with

header('Content-Type: application/json');
at/near the top of your code and before you try to output anything.

 

2. Replace all your error messages with JSON. I suggest something like

//echo '<p>LDAP SERVER CONNECTION FAILED</p>';
echo json_encode(["success" => false, "error" => "LDAP SERVER CONNECTION FAILED"]);
exit;
That is, a "success" that is true/false (false for errors) and an "error" with the error message.

 

3. Get rid of silly little status messages.

//echo 'login successful';
4. Replace your normal output with JSON. You can probably use $data mostly as-is, and you don't need to check how many results there are either.

$data = ldap_get_entries($ldap_connection,$result);
unset($data["count"]); // don't need this, it screws things up
echo json_encode(["success" => true, "results" => $data]);
"success" just means that the lookup happened succcessfully and "results" will tell your Javascript about the results.

 

Now fix your Javascript to work with the new output.

 

5. Put dataType:"json" in the settings that you pass to $.ajax.

 

6. Remove the $(...).html(data) you have now because that's not what you want and won't work anyways.

 

7. The success callback's "data" will be an object. Do with it whatever you want. You can use data.success to tell if there was an error or not; if there was then you can use data.error for the message, and if not then data.results will be an array you can loop over normally

for (var i = 0; i < data.results.length; i++) {
If you have problems, post your new code with an explanation about what it is doing.

Share this post


Link to post
Share on other sites

What I do is put all my output as arrays and send them down to a json function and any errors are thrown to an error function then to output.

 

Like so ->

<?php

require_once 'lib/includes/utilities.inc.php';

use website_project\trivia_game\OutputQA;

/* Makes it so we don't have to decode the json coming from JQuery */
header('Content-type: application/json');

$gamePlay = new OutputQA();

$id = filter_input(INPUT_POST, 'id');

if (isset($id)) {
    $data = $gamePlay->readQA($id);
    if ($data) {
        $output = $data[0];
        output($output);
    } else {
        $output = 'eof';
        errorOutput($output, 410);
    }
}

$q_num = filter_input(INPUT_POST, 'q_num');
$answer = filter_input(INPUT_POST, 'answer');


if (isset($q_num) && isset($answer)) {

    $result = $gamePlay->checkDailyTen($q_num, $answer);

    if ($result) {
        output($result);
    } else {
        $output = ['eof' => TRUE, 'message' => 'There are no more questions'];
        errorOutput($output, 410);
    }
}

/*
 * Set error code then send message to Ajax / JavaScript
 */

function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * If everything validates OK then send success message to Ajax / JavaScript
 */

function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

It just something that keeps me thinking straight....it might help  :confused:

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.