Nested Loops in ajax call / angular - javascript

I'm trying to Loop trough a variable, search for the ID's and then make an ajax call to get the Detailcontent of the different ID's in the Success function I try to loop trough the received content and get the emails out.
It is working but i get the first email twice in my $scope.subContactmail. I think there is a problem with the loop but i don't get it. Was trying to figure it out the whole night and unfortunately no idea came trough. The idea should be that if the first loop is finished it will start with the second loop. But at the moment the first loop goes trough the second as well.
Problaby your pros out there can help me with this problem.
Looking forward for your help!
Here is the specific part of my angular app file:
//find all contract relations id's from customer
$scope.contactrelation = function (input) {
$http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactsRelation.php', input).
success(function(data, status, headers, config) {
$scope.subContactDetails = [];
$scope.subContactmail = [];
$scope.subContactId = data;
console.log($scope.subContactId);
//GET ALL the subcontact ID's from the selected item
var i=0;
var subContactIdlenght = $scope.subContactId.length;
while (i < subContactIdlenght) {
console.log($scope.subContactId[i].contact_sub_id);
var number = $scope.subContactId[i].contact_sub_id;
i = i + 1;
//Send the ID to the API and get the user Details
$http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactswithID.php', number).
success(function(data, status, headers, config) {
$scope.subContactDetails.push(data); // store it in subContactDetails
console.log($scope.subContactDetails);
//HERE COULD BE THE PROBLEM!!
// I want this loop to start when the first loop is finished but i have to run this in this success function.
// At the moment i get the first email twice!
//Loop trough ContactDetails and get the emails.
if (i == subContactIdlenght){
var subContactDetailslength = $scope.subContactDetails.length;
for(var p=0; p < subContactDetailslength; p++) {
console.log($scope.subContactDetails[p].mail);
var number = $scope.subContactDetails[p].mail;
$scope.subContactmail.push(number);
};
};
}).
error(function(data, status, headers, config) {
$scope.errormessage = data;
console.log(data);
});
};//ENDWHILE
console.log(data);
}).
error(function(data, status, headers, config) {
$scope.errormessage = data;
console.log(data);
});

you have 2 solutions
Use the promise API (recommended):
something like that
var wheatherPromise = $http.get(...);
var timePromise = $http.get(...);
var combinedPromise = $q.all({
wheather: wheatherPromise,
time: timePromise
})
combinedPromise.then(function(responses) {
console.log('the wheather is ', responses.wheather.data);
console.log('the time is ', responses.time.data);
});
OR
simply do the following:
make ur $http request in a seperated function or (AJS service is
recommended).
call that function in a for loop based on ur list
declare a scope variable holds an empty array inside the function
push response objects in the array
avoid defining $http.get inside a for loop which cause unexpected behavior

I think what you need is promises/deferred API here.

Related

How to know when sorting stops in Javascript

I'm using AngularJS to sort an array. Im pushing the objects as I iterate to the response data from the Ajax call, and this becomes an issue because as the data is rendered in the UI, you can see it sorting in the elements and causes a bad user experience. I want to be able to know when the sorting stops and that's when I render the data.
$scope.posts = [];
var ajaxCall = function()
.success(function (data) {
var data = data;
angular.forEach(data, function(data){
prepData(data.id, data.name);
})
})
.error(function(){
/* Do Something */
})
})
var prepData = function(id, name){
var post = {id : id, name, name}
$scope.posts.push(post); //renders at this point
$scope.posts.sort(function(a,b){
return parseFloat(a.index) - parseFloat(b.index);
}) // I want to know when sorting stops
}

Angular making pseudo-synchronous HTTP requests

I want to construct a mechanism that would access a database via POST requests. So far, I do received the desired data, but am have issues with the timing. Here are three pieces of code that I'm using (simplified to keep the focus of the question).
First, a factory handling the HTTP request vis-à-vis a servlet:
var My_Web = angular.module('My_Web');
My_Web.factory('DB_Services', function($http , $q) {
var l_Result ;
var DB_Services = function(p_Query) {
var deferred = $q.defer();
var url = "http://localhost:8080/demo/servlets/servlet/Test_ui?";
var params = "data=" + p_Query ;
var Sending = url + params ;
$http.post(Sending).
success(function(data, status, headers, config) {
deferred.resolve(data);
}).
error(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
}
return DB_Services;
});
Second, a general purpose function handling the promise (or so I meant) exposed to all the controllers that would need to extract data from the remote DB:
$rootScope.Get_Data_from_DB = function(p_Query) {
DB_Services(p_Query).then(function(d) {
console.log("In Get_Data_from_DB; Received data is: " + JSON.stringify(d));
$scope.data = d;
});
};
Third, one example within one of the controllers:
$scope.Search_Lookups = function () {
console.log ("search for lookup data...") ;
var l_Lookup_Type = document.getElementById("THISONE").value ;
var l_Send_Request_Data = '{"Requestor_ID":"4321" , "Request_Details" : { "Data_type" : "' + l_Lookup_Type + '" } }' ;
console.log("Sending Request: " + l_Send_Request_Data) ;
l_Data = $rootScope.Get_Data_from_DB(p_Query) ;
console.log ("Received response: " + l_Data) ;
Deploy_data(l_Data) ;
}
The function Deploy_data(l_Data) is responsible of dismembering the received data and put the relevant pieces on screen.
What happens is that I get on the console the string Received response: undefined and immediately after the result of the retrieval as In Get_Data_from_DB; Received data is: (here I get the data).
The Received response: undefined is printed from the invoking function (third piece of code), whereas the output with the actual data is received and printed from within the second piece of code above. This means that the invocation to Deploy_data would not receive the extracted data.
Once again, the same mechanism (i.e. the factory $rootScope.Get_Data_from_DB) would be vastly used by many controllers.
I thought of using $scope.$watch but I'm not sure because the same user might be triggering several queries at the same time (e.g. request a report that might take few seconds to arrive and, in the meantime, ask for something else).
I think I found a solution (at least it appears to be ok for the time being). The global function Get_Data_from_DB accepts a second parameter which is a callback of the invoking controller.
The invoking controller creates a private instance of the Get_Data_from_DB function and triggers a request providing the callback function.
I'll need to test this with parallel queries, but that is still a long way to go...

How to split name to first and last name and use in scope

I am working with Node, Angular & Mongo. And was able to successfully save and retrieve a user from the db. I have in my user model the following -> name: String. This is basically where the user inputs his first and last name.
Now i want to retrieve the name from the database and split the first and lastname up to retrieve the first letter of the first name and last name to create the initials of the user.
My question is how to do this basically:
Part of my app.js code for retrieving the user is the following (in this function I would write the split javascript code):
//Retrieving the users
$scope.getUsers = function() {
$http.get('/api/users').success(function(data) {
$scope.userInfo = data;
//console.log("Retrieved users from the server", data);
//$scope.linkTaskToUser(data);
//console.log(data);
})
.error(function(data, status, headers, config) {
console.log("Error in retrieving users from server");
});
var FirstLastName = $scope.userInfo.data.name;
console.log('---->>>>>' , FirstLastName);
}
$scope.getUsers();
I tried something like this :
var FirstLastName = $scope.userInfo.data.name;
console.log('---->>>>>' , FirstLastName);
But of course this is not right (throws up an error)....
First all,put your below code inside success callback:
var FirstLastName = $scope.userInfo.data.name;
console.log('---->>>>>' , FirstLastName);
Now try to console just data.name. If this one is giving you data then try to console.log($scope.userInfo.name);
Hope this might help you !!
Cheers !!!
get() is asynchron - you have to manage data in the success-function:
//Retrieving the users
$scope.getUsers = function() {
$http.get('/api/users').success(function(data) {
$scope.userInfo = data;
var FirstLastName = $scope.userInfo.data.name;
console.log('---->>>>>' , FirstLastName);
//console.log("Retrieved users from the server", data);
//$scope.linkTaskToUser(data);
//console.log(data);
})
.error(function(data, status, headers, config) {
console.log("Error in retrieving users from server");
});
}
$scope.getUsers();

How get array in Angular template?

In PHP side there are some element of array:
$this->data['messages']['ms'][] = 'Line1';
$this->data['messages']['ms'][] = 'Line2';
and method that to return json format:
echo json_encode($this->data['messages']); die();
Angular side:
$scope.response = {};
....
request.success(function (data) {
$scope.response.message = data.messages; // Edit here
});
<div ng-repeat="error in response">{{error}}</div>
When I try to get array items, I get nothing
I have converted my difficult object to array:
$scope.messages = [];
...
// In loop
$scope.messages.push(item);
Output in console:
Array[2]0: "Qeydiyyat mümkün deyil. Bu e-mail ilə istifadəçi artıq saytda qeydiyyatdan keçib"1: "Bu IP ünvanından artıq qeydiyyatdan keçilib"
In HTML template I try to display elements:
<div ng-repat="error in messages">{{error}}</div>
you must check your request. Are you useing $http?
Have you provided http in controller/service?
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
you may also check with console.log(data) if theres any data provided.
Maybe there's different construction than you thought (for example wrapped data)
P.S. it should be messages (with s in the end)
Try this in your angular side.
$scope.response = {};
....
request.success(function (data) {
$scope.message = data.data;
console.log($scope.message);
});
<div ng-repeat="error in message">{{error}}</div>
You call your variable in a wrong way. Try console log the $scope.message if there are data's provided.

Access PHP Array within jQuery (Ajax, JSON)

I have the following PHP code which encodes a PHP array:
Code
$js_array = json_encode($tmp);
Output
{
"frfgt55":["ABC","frfgt55","Aberdeen"],
"vfrgt6":["ABC","vfrgt6","Birmingham"],
"vbgtfdh67":["XYZ","vbgtfdh67","Leeds"],
"vfe5gb":["XYZ","vfe5gb","Bristol"],...
}
What I am struggling with is to then access this within a jQuery script. I know I should be making use of $.getJSON but I am struggling with its implementation as my Ajax knowledge is limited. I cannot see how this would access the variable that as been encoded.
Ajax code
$.getJSON('../_client/index.php', function(data) {
/* data will hold the php array as a javascript object */
});
Any advice, feedback and comments welcomed.
If I well understood your needs you can access data with:
$.getJSON('../_client/index.php', function(data) {
/* data will hold the php array as a javascript object */
console.info(data.frfgt55); //accessing the first item of the array
});
EDIT
In order to handle success and error code I suggest you to use the promise interface and so replace the current $.getJSON() code with:
$.getJSON('../_client/index.php')
.success(function(response) { console.info(response); alert("success"); })
.fail(function(jqXHR, status, error){ console.info(error); alert("error"); });
If I am correct then check this code it will help you
$.getJSON('../_client/index.php', function(data) {
for(var key in data) { // In comment check first loop data for each record.
// key = 'frfgt55'; // For 1st loop
var yourArrayRecord = data[key]; // For 1st loop <- ["ABC","frfgt55","Aberdeen"]
var perticularValue1 = yourArrayRecord[0]; // For 1st loop <- "ABC"
var perticularValue2 = yourArrayRecord[1]; // For 1st loop <- "frfgt55"
var perticularValue3 = yourArrayRecord[2]; // For 1st loop <- "Aberdeen"
}
});

Categories