I need to run function "testfun 2 times", for each function I will have a few of names lets say testfun(5, global_user) // output [1,2,4,4,5] and for testfun(7, global_user) // output [9,10,11]
How I can put this 2 arrays in one array after I will run 2 functions?
testfun(5, global_user);
testfun(7, global_user);
function testfun(groupId, myUser) {
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url: itemsUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: loadTeamNames,
error: errorHandler
}
);
}
var arr = [];
function loadTeamNames(data){
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var name = $(this)[0].Name;
});
}
Thanks
With JS
var mergedArray = outputOne.concat(outputTwo);
With JQuery
var mergedArray = $.merge( $.merge( [], outputOne), outputTwo);
Since testFun() uses asynchronous methods you can't do anything immediately after running it twice without waiting for both instnces to complete. This is accomplished using promises
You could use $when() and return a promise from testFun(). Will need to move loadTeamNames into testFun to do it
$.when() won't complete until both of the promises are resolved
function testfun(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "Title";
var itemsUrl = "https://info.com(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor;
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function () {
var name = $(this)[0].Name;
});
// resolve deferred and pass data to be used in `$.when()`
defer.resolve(results);
}
return defer.promise;
}
To use
$.when(testfun(5, global_user),testfun(7, global_user)).done(function (results1, results2) {
//do what you need to with arrays results1 & results2
});
Add defer.reject() in the errorHandler
Assuming that jsonObject.d.results is an array already, you can just do:
arr.concat(results)
This will concatenate your array so far with the new result. Have that code inside of loadTeamNames and each run of testfun will concatenate the result to your current array. not really sure what you're using all those variables inside of loadTeamNames for however.
function getTeamNames(groupId, myUser) {
var defer = $.Deferred();
var selectStr = "$select=Title,LoginName";
var orderbyStr = "$orderby=Title";
var itemsUrl = "https://sites.sp.kp.org/pub/qosstgcat/_api/web/SiteGroups/getbyid(" + groupId + ")/users" + "?" + selectStr + "&" + orderbyStr;
var executor = new SP.RequestExecutor(carootUrl);
executor.executeAsync(
{
url : itemsUrl,
method : "GET",
headers : {"Accept" : "application/json; odata=verbose"},
success : loadTeamNames,
error : errorHandler
}
);
function loadTeamNames(data) {
var jsonObject = JSON.parse(data.body);
var results = jsonObject.d.results;
var hide_groups = false;
$(results).each(function(){
var login_name = $(this)[0].LoginName;
});
defer.resolve(results);
}
return defer.promise;
}
result
$.when(getTeamNames(4, global_user),getTeamNames(185, global_user)).done(function () {
console.log(results);
});
Related
I have a script, below, and when the page loads I get an error message: Cannot read property 'length' of undefined, so I researched the error and found that the AJAX request wasn't executed. If I execute the same code in the browser console, the script works fine. What's wrong with my code?
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
});
}
function getCitiesList2() {
var bla = getCitiesList();
console.log(bla['responseJSON']);
var i = 0;
var data = [];
while (i < bla['responseJSON'].length) {
data[i] = {};
data[i]['id'] = bla['responseJSON'][i]['id'];
data[i]['text'] = bla['responseJSON'][i]['title'];
i++;
}
console.log(data);
}
$('#city').select2({
data: getCitiesList2(),
width: "100%"
});
</script>
Since JavaScript is asynchronous language, it just keeps running and doesn't wait for AJAX to return result.
In your code, the first line of getCitiesList2 function assigns the return value of an AJAX call. The AJAX returns later, and var bla doesn't yet have the response. To solve this, you can pass a callback to your AJAX function getCitiesList and execute it on AJAX success.
function getCitiesList(callback) {
var country_id = '189';
$.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(result) {
callback(result);
}
});
}
function getCitiesList2() {
getCitiesList(function(result) {
var i = 0;
var data = [];
while (i < result['responseJSON'].length) {
data[i] = {};
data[i]['id'] = result['responseJSON'][i]['id'];
data[i]['text'] = result['responseJSON'][i]['title'];
i++;
}
});
}
The problem is that console.log(bla['responseJSON']); in getCitiesList2 is executed before the ajax response is received. And after var bla = getCitiesList(); assignment, bla basically holds a deferred object. All you need to do is to assign a callback function that is going to be executed once the ajax call returns.
<script>
function getCitiesList() {
var country_id = '189';
return $.ajax({
type: 'get',//тип запроса: get,post либо head
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
}).done(function(data){
$('#city').select2({
data: processCitiesResponse(data),
width: "100%"
});
});
}
function processCitiesResponse(data)
{
console.log(data);
var i = 0;
var options = [];
while (i < data.responseJSON.length) {
options[i] = {};
options[i].id = data.responseJSON[i].id;
options[i].text = data.responseJSON[i].title;
i++;
}
console.log(options );
}
</script>
first and second answer doesn't help, the same problem.
This work:
<script>
var AUTH_TOKEN = $('meta[name=csrf-token]').attr('content');
function Blabla(){
var country_id = '189';
$.ajax({
type: 'get',
url: '/countries/' + country_id + '/cities' + "&authenticity_token=" + AUTH_TOKEN,
success: function(bla){
var i = 0;
var data = [];
while (i < bla.length) {
data[i] = {};
data[i]['id'] = bla[i]['id'];
data[i]['text'] = bla[i]['title'];
i++;
}
$('#city').select2({
data: data,
width: "100%"
});
}
});
}
Blabla();
</script>
how do i display all content in my data array without repeating my self like i have done below .
// Program guide Rest
$(document).ready(function() {
$.ajax({
cache: false,
url: "http://engrid2media.com/nextt/api/epg/schedule/id/",
type: 'GET',
crossDomain: true,
dataType: 'json',
success: function() {
alert("EPG Success");
},
error: function() {
alert('EPG Failed!');
},
}).then(function(data) {
var result = data [0];
console.log(result);
$('.ch-name').append(result.ch_name);
$('.ch-logo').append(result.ch_logo);
$('.ch-desc').append(result.ch_desc);
$('.ch-genre').append(result.ch_genre);
$('.ch-type').append(result.type);
$('.ch-resolution').append(result.resolution);
var result1 = data [1];
console.log(result1);
$('.ch-name1').append(result1.ch_name);
$('.ch-logo1').append(result1.ch_logo);
$('.ch-desc1').append(result1.ch_desc);
$('.ch-genre1').append(result1.ch_genre);
$('.ch-type1').append(result1.type);
$('.ch-resolution1').append(result1.resolution);
var result2 = data [2];
console.log(result2);
$('.ch-name2').append(result2.ch_name);
$('.ch-logo2').append(result2.ch_logo);
$('.ch-desc2').append(result2.ch_desc);
$('.ch-genre2').append(result2.ch_genre);
$('.ch-type2').append(result2.type);
$('.ch-resolution2').append(result2.resolution);
var result3 = data [3];
console.log(result3);
$('.ch-name3').append(result3.ch_name);
$('.ch-logo3').append(result3.ch_logo);
$('.ch-desc3').append(result3.ch_desc);
$('.ch-genre3').append(result3.ch_genre);
$('.ch-type3').append(result3.type);
$('.ch-resolution3').append(result3.resolution);
var result4 = data [4];
console.log(result4);
$('.ch-name4').append(result4.ch_name);
$('.ch-logo4').append(result4.ch_logo);
$('.ch-desc4').append(result4.ch_desc);
$('.ch-genre4').append(result4.ch_genre);
$('.ch-type4').append(result4.type);
$('.ch-resolution4').append(result4.resolution);
var result5 = data [5];
console.log(result5);
$('.ch-name5').append(result5.ch_name);
$('.ch-logo5').append(result5.ch_logo);
$('.ch-desc5').append(result5.ch_desc);
$('.ch-genre5').append(result5.ch_genre);
$('.ch-type5').append(result5.type);
$('.ch-resolution5').append(result5.resolution);
});
});
This works fine , but it will be difficult to display over 20 items from the database with this method since i would have to do it one after the other.
A simple for loop would do it.
.then(function(data) {
for (var i = 0; i < 6; ++i)
{
var prefix = (i == 0 ? "" : i.toString());
$('.ch-name' + prefix).append(data[i].ch_name);
$('.ch-logo' + prefix).append(data[i].ch_logo);
$('.ch-desc' + prefix).append(data[i].ch_desc);
$('.ch-genre' + prefix).append(data[i].ch_genre);
$('.ch-type' + prefix).append(data[i].type);
$('.ch-resolution' + prefix).append(data[i].resolution);
}
});
Why not just write helper function?
Something like that.
function(data) {
var result,
suffix = '';
for (var i in data) {
result = data[i];
if (i > 0) {
suffix = i;
}
$('.ch-name' + suffix).append(result.ch_name);
$('.ch-logo' + suffix).append(result.ch_logo);
$('.ch-desc' + suffix).append(result.ch_desc);
$('.ch-genre' + suffix).append(result.ch_genre);
$('.ch-type' + suffix).append(result.type);
$('.ch-resolution' + suffix).append(result.resolution);
}
}
Try utilizing $.each()
$.each(data, function(key, val) {
var idx = key === 0 ? "" : key;
$(".ch-name" + idx).append(val.ch_name);
$(".ch-logo" + idx).append(val.ch_logo);
$(".ch-desc" + idx).append(val.ch_desc);
$(".ch-genre" + idx).append(val.ch_genre);
$(".ch-type"+ idx).append(val.type);
$(".ch-resolution" + idx).append(val.resolution);
});
Is it possible to use like fuse.js with an XML document instead of JSON? As it is now I only have an XML document with data and hope that I shouldn't make a new version as well for JSON.
Hope someone can help me out which direction I can/should go.
Kind regards,
Niels
Found the solution myself. Instead of the example with JSON placed on http://kiro.me/projects/fuse.html, here is the version with an XML call instead :)
$(function() {
function start(books) {
var $inputSearch = $('#hero-search'),
$results = $('#results ul'),
$authorCheckbox = $('#value'),
$titleCheckbox = $('#typeId'),
$caseCheckbox = $('#case'),
searchAuthors = true,
searchTitles = false,
isCaseSensitive = false,
fuse;
function search() {
$results.empty();
$.each(r, function(i, val) {
$resultShops.append('<li class="result-item"><span><img src="' + this.statusId + '" /></span> ' + this.value + '</li>');
});
}
function createFuse() {
var keys = [];
if (searchAuthors) {
keys.push('value');
}
if (searchTitles) {
keys.push('typeId');
}
fuse = new Fuse(books, {
keys: keys,
caseSensitive: isCaseSensitive
});
}
$inputSearch.on('keyup', search);
createFuse();
}
$.ajax({
type: 'GET',
dataType: 'xml',
url: 'xml-document/document.xml',
success: function(response) {
var suggestions = [];
$(response).find("searchResults").children().each(function(i, elm) {
var name = $(elm).find('name').text();
var url = $(elm).find('url').text();
var description = $(elm).find('description').text();
var statusId = $(elm).find('status').text();
var typeId = $(elm).find('type').text();
var result = {};
result.value = name;
result.url = url;
result.description = description;
result.statusId = statusId;
result.typeId = typeId;
suggestions.push(result);
});
start(suggestions);
},
error: function(response) {
console.log('failure',response);
}
});
});
I don't have very much to my code but I seem to be getting Illegal invocation with my order variable - works fine and shows in console.log if I comment it out
$('body').on("click", "#brands_by_category_submit_btn", function (e) {
e.preventDefault();
var self = $(this);
var order = $(".order").toArray();
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
if(data.length)
{
var data_array = {
id : id,
brand_name : brand_name,
cat_id : data,
order : order,
state : 1
};
var url = $("#brands_by_category_submit_btn").data("url");
//console.log(data_array);
ajaxCall(url, data_array);
alert("Categories Updated");
}
});
AjaxCall:
function ajaxCall(url, data_array, div_id, callback_fn) {
return $.ajax({
type:'POST',
url:url,
beforeSend: function(){
$("#" + div_id).html("<img src='http://www.#.co.nz/files/large/ajax-loader.gif' alt='Loading..' title='Loading..'/>");
},
data:data_array,
complete:function (data) {
$("#" + div_id).html(data.responseText);
if(callback_fn != null)
{
eval(callback_fn + '()');
}
}
});
}
Your problem is that you're converting an array of HTML elements into POST data which simply isn't possible. You should instead loop through your elements and grab their .text() property:
var self = $(this);
var order = []; //or "new Array()". Whatever you prefer for readability
$(".order").each(function() {
order.push($(this).text());
});
var id = $("#manID").data("id");
var brand_name = $("#brand_name").data("id");
var data = grabData(true);
I am trying to return a JSON object from a function using the JSON jQuery plugin (http://code.google.com/p/jquery-json/) but after returning the object from the function, it becomes undefined.
$(document).ready(function() {
var $calendar = $('#calendar');
$calendar.weekCalendar({
...
data : function(start, end, callback) {
var datas = getEventData();
alert(datas); // Undefined???
}
});
If I inspect the object before returning it, it is defined.
function getEventData() {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
//alert(dataString);return false;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
alert($.toJSON(jsonArray)); // Defined!
return ($.toJSON(jsonArray));
} else {
}
}
});
}
Any idea what I'm missing here?
function getEventData() {
function local() {
console.log(42);
return 42;
}
local();
}
Your missing the fact that the outer function returns undefined. And that's why your answer is undefined.
Your also doing asynchronous programming wrong. You want to use callbacks. There are probably 100s of duplicate questions about this exact problem.
Your getEventData() function returns nothing.
You are returning the JSON object from a callback function that's called asynchronously. Your call to $.ajax doesn't return anything, it just begins a background XMLHttpRequest and then immediately returns. When the request completes, it will call the success function if the HTTP request was successful. The success function returns to code internal in $.ajax, not to your function which originally called $.ajax.
I resolved this by using callbacks since AJAX is, after all. Once the data is retrieved it is assigned to a global variable in the callback and the calendar is refreshed using the global variable (datas).
$(document).ready(function() {
// Declare variables
var $calendar = $('#calendar');
datas = "";
set = 0;
// Retrieves event data
var events = {
getEvents : function(callback) {
var dataString = "minDate="+ minDate/1000 + "&maxDate=" + maxDate/1000;
$.ajax({
type: "POST",
url: "busker_ops.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data != null) {
var jsonArray = new Array();
var jsonObj = {};
for(var i = data.length - 1; i >= 0; --i) {
var o = data[i];
var set_id = o.set_id;
var start = o.startOrig;
var end = o.endOrig;
var title = o.title;
var deets = o.deets;
jsonObj =
{
"id":parseInt(set_id),
"start":$("#calendar").weekCalendar("formatDate", new Date(start), "c"),
"end":$("#calendar").weekCalendar("formatDate", new Date(end), "c"),
"title":title,
"body":deets
};
jsonArray[i] = jsonObj;
}
//alert($.toJSON(jsonArray));
callback.call(this,jsonArray);
} else {
}
}
});
}
}
$calendar.weekCalendar({
data : function(start, end, callback) {
if(set == 1) {
callback(datas);
//alert(datas.events);
}
}
});
// Go get the event data
events.getEvents(function(evented) {
displayMessage("Retrieving the Lineup.");
datas = {
options : {},
events : evented
};
set = 1;
$calendar.weekCalendar("refresh");
});
});