How to fetch all users by REST API in javascript - yammer

API doc is here https://developer.yammer.com/docs/usersjson
My javascript code below can successfully fetch the users in page 1 of yammer network.
But how to fetch all users by either one query or multiple queries in elegant way? I perceive that I need to query by looping against page 1 page 2 page 3... until the returned userArray length is 0? Then how do I validate when to stop in the loop?
yam.connect.loginButton('#yammer-login', function (resp) {
console.log(resp.authResponse);
if (resp.authResponse) {
//trigger data process
yam.platform.request({
url: "users.json",
method: "GET",
data: {
"page": 1
},
success: function (user) {
console.log("The request was successful.");
console.dir(user);
},
error: function (user) {
console.log("There was an error with the request.");
}
});
}else{
console.log("error to get access_token");
}
});

Related

Vuejs 2 trying to call api multiple times untill all the data is retreiced

I'm trying to use Vuejs 2 to call an endpoint API multiple times until all data is retrieved.
I'm using the SharePoint REST api and the results come back in an object res.d.results, however I can only query 5000 items at a time.
If rest.d.__next exists, it also has the endpoint to the next batch of data.
When I run this code I can see in the chrome debugger that the second call is made but the data is never pushed to the table and I get this message in the browser console
Event.path is deprecated and will be removed. Please use Event.composedPath() instead.
new Vue ({
el:"#app",
data: {
test: "this is my test",
pg:[]
},
created: function(){
console.log("working");
this.loopData("https://srvsharepoint1p/sites/tactical_squad/ArhivaTool/_api/web/lists/getbytitle('Dosare')/items?$top=1000", this);
},
methods: {
getListData: function(url,that){ // function that calls the api
console.log("getting data");
var headers={
"Accept": "application/json;odata=verbose"
}
return $.ajax({
url:url,
type: "GET",
headers: headers,
success: function(data){
lData = data;
}
});
},
loopData: function (web){ // function to loop through API calls until all data is retrieved.
this.getListData(web).then(res => {
console.log(res);
this.pg.push(...res.d.results)
if (res.d.__next) { // if there is a next page do another api call
this.getListData(res.d.__next); // try to call the api again
} else {
console.log('aborted')
}
})
}
}})
Any help would be greatly appreciated
I managed to figure it out
It seems I was doing recursion wrong. Hope this helps someone else it's using axios now to get data instead of ajax
new Vue ({
el:"#app",
data: {
test: "this is my test",
pg:[], // table data
counter:0
},
created: function(){
console.log("working");
this.getListData("https://srvsharepoint1p/sites/tactical_squad/ArhivaTool/_api/web/lists/getbytitle('Dosare')/items?$top=5000" ); //endpoint
},
methods: {
getListData: function(url){ //recursive function that calls itself untill all data is retreived
var vm = this
console.log("getting data");
axios.get(url).then(function(res){
if (res.data["odata.nextLink"] ) { // check if another page needs to be requested
vm.pg.push(...res.data.value); // push values into table object
vm.getListData(res.data["odata.nextLink"]); //call function again
}
else {
console.log('aborted');
alert("Tabelul este incarcat, se poata folosi butonul de exprot")
}
})
.catch(function(error){
alert(error);
})
}})

How to call continues Ajax requests in background without disturbing front-end page

I want to develop a report page with continues ajax requests which is retrieves a bunch of record sets for each call to complete the entire report,
i.e ,
i want to display a 1000 of student records and for retrieving whole 1000 records makes more loading time which is need to be avoided. so i just created a loop of ajax requests which fetch 100 records for each request. In this case the browser holds until the total of 1000 records displays ...i want to avoid this i want to run the ajax requests in background and it not should disturb or hold the browser to see the first 100 records..
while( loop until the whole records retrived ){
$.ajax({
url: "/erp/reports/json/student_report/",
type: "POST",
dataType: "json",
data: {class_id : id},
success: function (json) { // retrieve 100 records }
});
}
Or tell me that do i approached wrong way can i achieve this using react is possible?
thanks in advance
This will make sure you call the next ajax request right after the first one finishes.
function fetchRecords(id){
$.ajax({
url: "/erp/reports/json/student_report/",
type: "POST",
dataType: "json",
data: {class_id : id},
success: function (json) {
// retrieve 100 records
// DO WHAT EVER YOU WANNA DO HERE
if(! the whole records retrived )
fetchRecords(id)
}
});
}
You should use a recursive function and javascript timeout.
That is, you make a function for ajax, then call the function by timeout recursively.
Please take a look my sample code.
This is a function to get all records more than 1000 by 100 records per page.
It should be refined as you wants
function clickedOrder() {
orderPageIndex = 0;
orderCnt = 0;
importOrder();
}
function importOrder() {
orderPageIndex++;
$.ajax({
type: 'POST',
url: './order.php',
async: false,
data: {pageIndex: orderPageIndex, orderCount: orderCnt},
success: function (result) {
console.log(result);
if (result.indexOf("OK") == 0 || result.indexOf("Zero") == 0) {
alert("imported successfully");
} else if (result.indexOf("ERROR") == 0) {
alert("Import Failed" + result);
} else if (result.indexOf("Order")==0) {
var strCnt = result.substring(result.indexOf(":") + 1);
orderCnt += strCnt*1;
startOrderTimer();
} else {
alert("Import Failed" + result);
}
},
error:function(error){
alert(error);
}
});
}
function startOrderTimer () {
setTimeout(stopOrderTimer,100);
}
function stopOrderTimer () {
importOrder();
}

Catching an AJAX error from a post request (422)

I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs

WordPress ajax call with add_filter

I have a WordPress function that works exactly how I want. The function below changes the email recipient in Contact Form 7 to abc#aol.com.
Now I need to use AJAX to update the email recipient to a dynamic value.
function wpcf7_dynamic_email_field($args) {
if(!empty($args['recipient'])) {
$args['recipient'] = str_replace('%admin%', 'abc#aol.com', $args['recipient']);
return $args;
}
return false;
}
add_filter('wpcf7_mail_components', 'wpcf7_dynamic_email_field');
Here's my AJAX call. I do not know how to tell the call to initiate the wpcf7_dynamic_email_field() function. Can that be done?
$.ajax({
url: ajaxurl, // or example_ajax_obj.ajaxurl if using on frontend
data: {
'action': 'update_team_page_contact_form',
'emailAddress' : emailAddress
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});

Make 2 AJAX calls on button Click

I am working on ASP.NET MVC project. In my home page, I have a search box with a search button.
When User types a Keyword and Click Search, I need to perform 2 independent search Operations (I am using Elasticseach, so two calls to Elasticsearch).
Make a call to SearchItems action method, which will go and get Items from Elasticsearch and returns ItemsPartialView.
Make a call to SearchCategory action method which goes and gets categories from Elasticsearch and returns CategoryPartialView.
In my home page, I want to make 2 ajax calls, to these action methods using AJAX, to display the result.
This Image explains what I want to achieve
Question: Is it possible to make 2 calls to 2 action methods on one event using AJAX?
It's possible. The only real issue is whether you want the ajax requests to be sent in a certain order (and the usual issues of efficiency of code to avoid repeats, the format of the data returned etc). One way of doing this (where the ajax second call is made after the first completes successfully) is sketched out:
<input type="text" id="search-query" value="" />
<button id="test-button">Test Ajax</button>
<div id="ajax-one-result"></div>
<div id="ajax-two-result"></div>
<script>
$(function(){
$(document).on("click", "#test-button", function(){
var qry = $("#search-query").val();
func1(qry);
function func1(queryString) {
var urlOne = "/Path/To/AjaxOne";
return $.ajax({
type: "GET",
url: urlOne,
timeout: 30000,
data: { query: queryString },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-one-result").html(transport);
func2(transport);
console.log("AjaxOne success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxOne");
},
complete: function () {
}
});
}
function func2 (ajaxOneResult) {
var urlTwo = "/Path/To/AjaxTwo";
$.ajax({
type: "GET",
url: urlTwo,
timeout: 30000,
data: { query: ajaxOneResult },
dataType: "json",
beforeSend: function () {
},
success: function (transport) {
$("#ajax-two-result").html(transport);
console.log("AjaxTwo success");
},
error: function (xhr, text, error) {
console.log("ERROR AjaxTwo");
},
complete: function () {
}
});
}
});
});
</script>
with Controller Actions:
public async Task<JsonResult> AjaxOne(string query)
{
// For testing only
System.Threading.Thread.Sleep(5000);
var result = "AjaxOne Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> AjaxTwo(string query)
{
// For testing only
System.Threading.Thread.Sleep(2000);
var result = "AjaxTwo Result: " + query;
return Json(result, JsonRequestBehavior.AllowGet);
}

Resources