I am using AJAX to get the data and make them into an array like below:
function drawDate(username, date, device, token){
$.ajax({
type: 'GET',
url: dsu + "dataPoints/" + getDatapointId(username, date, device),
headers: {
"Authorization": "Bearer " + token
},
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
return [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
return location_events
}
},
error: function(data){
console.log('Data did not have any locations.')
}
});
}
Then when I tried to call that function, it returned "undefined". I actually want to put that array into FullCalendar like below:
$(document).ready(function() {
var today = moment();
var token = url("#access_token");
$.getJSON(dsu + "oauth/check_token?token=" + token)
.done(function(data) {
var username = data["user_name"];
var device = 'android';
var date = url("#date")? moment(url("#date")).toDate() : new Date();
var redraw = function(){
var test = drawDate(username, moment(date).format('YYYY-MM-DD'), device, token);
console.log(test); //***** Here! I tried to make the return of the function into a variable but it returned "undefined"
};
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: test, //******* I want to the array to be rendered here.
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
})
.fail(function() {
console.log("Fail!");
});
I read most of the similar questions and it seems that I should use callback function but I don't really understand how to use them.
Thank you very much! Any help is welcome!
The problem is that you do AJAX request which is asynchronous and you cannot return this data from drawDate() function. You need to do what you need with data retrieved from server in your 'success' callback. Like following:
success : function(data, device) {
var location_events = []; //***** Here is the array variable.
if(device == "android" || device == "ios") {
rows = data["body"]["episodes"].map(function (epi) {
var state = epi["inferred-state"].toLocaleUpperCase();
var start = new Date(epi["start"]);
var end = new Date(epi["end"]);
var long_lat = epi["location-samples"];
if (state == "STILL") {
var longitude_sum = 0;
var latitude_sum = 0;
long_lat.forEach(function(obj) {
longitude_sum += obj['longitude'];
latitude_sum += obj['latitude'];
});
location_events = [state, start, end, latitude_sum / long_lat.length, longitude_sum / long_lat.length];
}
});
//**** I pushed the data into the array.
rows.forEach(function(obj){
if (typeof obj !== 'undefined') {
location_events.push({
title: 'location',
start: moment(obj[1]).format().substring(0, 19),
end: moment(obj[2]).format().substring(0, 19),
url: "https://maps.googleapis.com/maps/api/staticmap?center="+ obj[3] + "," + obj[4] + "&zoom=15&size=2000x1000&maptype=roadmap&markers=color:red%7Clabel:S%7C" + obj[3] + "," + obj[4] + "&markers=size:mid"
})
}
});
console.log(location_events);
}
$('#calendar').fullCalendar({
header: '',
defaultDate: '2015-08-03',
defaultView: 'agendaDay',
allDaySlot: false,
slotEventOverlap: false,
events: location_events,
eventAfterRender: function(event, element, view) {
$(element).attr("id", "event_id_" + event.id);
}
});
}
Related
My problem is when event is successfully added, it shows on the screen but id is not included and thus if we want to edit an event that we just add without refreshing the page, error will appear which says id doesn't match.
Add function looks like this.
function registSchedule() {
// 開始終了日付の調整
var startYmd = moment(formatNengappi($('#inputYmdFrom').val() + "00時00分00", 1));
var endYmd = moment(formatNengappi($('#inputYmdTo').val() + "00時00分00", 1));
var allDayCheck = $('#allDayCheck').prop("checked");
if (!allDayCheck) {
startYmd = moment(formatNengappi($('#inputYmdHmFrom').val() + "00", 1));
endYmd = moment(formatNengappi($('#inputYmdHmTo').val() + "00", 1));
}
if (endYmd.diff(startYmd, 'days') > 0) {
endYmd = endYmd.add(+1, "days");
}
//非同期でサーバーにリクエストを送信
var EventData = {
id: $("#scheduleId").val(),
title: $('#inputTitle').val(),
start: startYmd.format("YYYY-MM-DDTHH:mm:ss"),
end: endYmd.format("YYYY-MM-DDTHH:mm:ss"),
allDay: allDayCheck,
};
sendAjaxRequest("add_event", EventData);
}
sendAjaxRequest looks like this.
function sendAjaxRequest(method, EventData) {
var cal = $("#calendar").fullCalendar("getView");
EventData.searchStart = cal.start;
EventData.searchEnd = cal.end;
// 処理名を設定
var methodName = "登録";
if (method == "update") {
methodName = "更新"
} else if (method == "remove") {
methodName = "削除"
}
$.ajax({
url: "/fullcalendar/" + method,
type: "GET",
data: {'title': EventData.title, 'start': EventData.start, 'end': EventData.end,'id': EventData.id,'allDay':EventData.allDay},
success: function(data) {
// カレンダー再描画
$('#calendar').fullCalendar( 'removeEvents', EventData.id );
$('#calendar').fullCalendar('renderEvent', EventData);
$('#inputScheduleForm').modal('hide');
alert("予定を" + methodName + "しました。");
console.log(EventData)
},
error: function(data) {
alert("予定の" + methodName + "に失敗しました。");
}
});
$('#calendar').fullCalendar('unselect');
}
views.py looks like this.
def add_event(request):
title = request.GET.get("title", None)
start = request.GET.get("start", None)
end = request.GET.get("end", None)
event = Events(title=str(title), start=start, end=end)
event.save()
data = {}
return JsonResponse(data)
result from console.log(EventData) after I clicked add button:
{id: "", title: "abcccc", start: "2020-08-21T00:00:00", end: "2020-08-21T00:00:00", allDay: true, …}
What should I add in the success: function(data) {} part to make sure after I add the event, I don't have to refresh the button to create a new id?
Any idea anyone?
I'm using FullCalendar and trying to update an event with a modal. When I try to update the event, I'm getting the cannot read property 'clone' of undefined.
I'm using the clientEvents method, as stated in their documentation
event must be the original Event Object for an event, not merely a reconstructed object. The original Event Object can obtained by callbacks such as eventClick, or by the clientEvents method.
to get my original event, however, when I submit I still get this error.
Here's my code:
initializeFullCalendar: function () {
var loc = $('#locationCodes').val();
$('.autocomplete').keypress(function (key) {
if (key.charCode == 32 && $('.autocomplete').val().length >= 1) { return true };
// if (key.charCode == 92 || key.charCode == 47 || key.charCode < 65) return false;
});
$(document).tooltip({
track: true,
hide: { effect: "explode", duration: 300 }
});
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
selectable: true,
selectHelper: true,
dayclick: function(date){
},
select: function (date, start, end) {
if ($('#job').attr('class') === 'XXX') {
EMP.calendarPopup(date, start, end);
}
},
eventSources: [
{
url: '/Home/getAllEvents/',
data: { Locations: loc },
type: 'POST'
}
],
eventClick: function (event, element, date) {
EMP.editCalendarPopup(date, event);
},
height: 350,
defaultView: 'basicWeek',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventRender: function (data, element) {
var start = moment(data.start._i).format('LT');
var end = moment(data.end._i).format('LT');
}
});
},
editCalendarPopup: function (date, event) {
$('.calendar-popup').addClass('active edit');
var event_date = event.start._i.split("T")[0];
var start = event.start._i.split("T")[1]
var end = event.end._i.split("T")[1];
start = EMP.convert12hr(start);
end = EMP.convert12hr(end);
var startTime = start.split(' ')[0];
var startMod = start.split(' ')[1];
var endTime = end.split(' ')[0];
var endMod = end.split(' ')[1];
$('#date').val(event_date);
$('#calendar-event').val(event.title);
$('#calendar-custodian').val(event.cust);
$('#calendar-start').val(startTime);
$('#startampm').val(startMod)
$('#calendar-end').val(endTime);
$('#endampm').val(endMod);
$('#hiddenEvent').val(event.title);
$('#hiddenCustodian').val(event.cust);
$('#hiddenStart').val(event.start._i);
$('#hiddenEnd').val(event.end._i);
$('#hiddenId').val(event._id);
},
editCalendarAjax: function() {
var event = $("#calendar").fullCalendar('clientEvents');
var hiddenId = $('#hiddenId').val();
event = $.grep(event, function(e){return e._id === hiddenId});
event = event[0];
var event_date = $('#date').val();
var title = $('#calendar-event').val();
var cust = $('#calendar-custodian').val();
var start = $('#calendar-start option:selected').val();
var end = $('#calendar-end option:selected').val();
var startampm = $("#startampm option:selected").val();
var endampm = $("#endampm option:selected").val();
start = start + " " + startampm;
end = end + " " + endampm;
start = EMP.convert24hr(start);
end = EMP.convert24hr(end);
var locCode = $('.location').attr('id');
var date_start = event_date + "T" + start;
var date_end = event_date + "T" + end;
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
var origEvent = $('#hiddenEvent').val();
var origCust = $('#hiddenCustodian').val();
var origStart = $('#hiddenStart').val();
var origEnd = $('#hiddenEnd').val();
item = {};
item["title"] = title;
item["cust"] = cust;
item["start"] = date_start;
item["end"] = date_end;
item["locCode"] = locCode;
item["origEvent"] = origEvent;
item["origCust"] = origCust;
item["origStart"] = origStart;
item["origEnd"] = origEnd;
$.ajax({
type: "POST",
url: "/Home/updateCalendar",
data: item,
success: function () {
console.log('success!');
},
error: function (xhr, ajaxOptions, thrownError) {
window.alert("Please click here to refresh your session");
console.log('error')
}
});
$('#calendar').fullCalendar('unselect');
EMP.togglePopups();
},
The issue was I was using an old version of FullCalendar. After updating I stopped getting the error.
One more thing I had to change was this:
if (title) {
event = {
title: title,
start: date_start,
cust: cust,
end: date_end
};
$('#calendar').fullCalendar('updateEvent', event);
}
to this:
if (title) {
event.title = title;
event.start = date_start;
event.cust = cust;
event.end = date_end;
$('#calendar').fullCalendar('updateEvent', event); // stick? = true
}
because I was overwriting my event. Everything works now.
I'm using the code from netsniff.js to generate a har file and I want to improve it to generate a har file from multiple links given in an array (named links in my below code).
There is another question here Using Multiple page.open in Single Script that might help me, but I have no idea how to implement the given solution in my code..
Below is my code (it logs FAIL to load the address in the output file if the links array contain more than one item):
"use strict";
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function () {
function pad(n) { return n < 10 ? '0' + n : n; }
function ms(n) { return n < 10 ? '00'+ n : n < 100 ? '0' + n : n }
return this.getFullYear() + '-' +
pad(this.getMonth() + 1) + '-' +
pad(this.getDate()) + 'T' +
pad(this.getHours()) + ':' +
pad(this.getMinutes()) + ':' +
pad(this.getSeconds()) + '.' +
ms(this.getMilliseconds()) + 'Z';
}
}
var entries = [];
function createHAR(address, title, startTime, resources)
{
resources.forEach(function (resource) {
var request = resource.request,
startReply = resource.startReply,
endReply = resource.endReply;
if (!request || !startReply || !endReply) {
return;
}
// Exclude Data URI from HAR file because
// they aren't included in specification
if (request.url.match(/(^data:image\/.*)/i)) {
return;
}
entries.push({
startedDateTime: request.time.toISOString(),
time: endReply.time - request.time,
request: {
method: request.method,
url: request.url,
httpVersion: "HTTP/1.1",
cookies: [],
headers: request.headers,
queryString: [],
headersSize: -1,
bodySize: -1
},
response: {
status: endReply.status,
statusText: endReply.statusText,
httpVersion: "HTTP/1.1",
cookies: [],
headers: endReply.headers,
redirectURL: "",
headersSize: -1,
bodySize: startReply.bodySize,
content: {
size: startReply.bodySize,
mimeType: endReply.contentType
}
},
cache: {},
timings: {
blocked: 0,
dns: -1,
connect: -1,
send: 0,
wait: startReply.time - request.time,
receive: endReply.time - startReply.time,
ssl: -1
},
pageref: address
});
});
return {
log: {
version: '1.2',
creator: {
name: "PhantomJS",
version: phantom.version.major + '.' + phantom.version.minor +
'.' + phantom.version.patch
},
pages: [{
startedDateTime: startTime.toISOString(),
id: address,
title: title,
pageTimings: {
onLoad: page.endTime - page.startTime
}
}],
entries: entries
}
};
}
var page = require('webpage').create()
var fs = require('fs');
var count = 0;
function processSites(links)
{
page.address = links.pop();
var path = 'file' + count + '.har';
page.resources = [];
console.log("page resources:", page.resources)
count = count + 1;
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.open(page.address, function (status) {
var har;
setTimeout(function () {
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
entries = [];
har = createHAR(page.address, page.title, page.startTime, page.resources);
// console.log(JSON.stringify(har, undefined, 4));
fs.write(path, JSON.stringify(har), 'w');
if(links.length > 0)
{
processSites(links);
}
else
{
phantom.exit();
}
}
}, 10000);
});
}
var links = ["http://stackoverflow.com", "http://marvel.com"];
processSites(links);
Update:
The above code generate two har files file1.har and file2.har, but the second har file also contains the har code generated from both links, and it should only have the har code for the first link...
Fixed this by setting var har = " "
You can't iterate opening pages in PhantomJS in a simple loop because page.open method is asynchronous. It doesn't wait for first site to be processed, opening the second right away.
I've rewritten your script to use recursion: next site will be opened only after the current is processed. (Note: if any of the sites in queue will fail to load the whole process will halt, but you can easily rewrite the script to avoid that).
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function () {
// ...
}
}
var entries = [];
function createHAR(address, title, startTime, resources)
{
// ...
}
var page = require('webpage').create()
function processSites(links)
{
page.address = links.pop();
console.log("PAGE ADDRESS: ", page.address);
page.resources = [];
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.open(page.address, function (status) {
var har;
setTimeout(function () {
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
har = createHAR(page.address, page.title, page.startTime, page.resources);
console.log(JSON.stringify(har, undefined, 4));
if(links.length > 0)
{
processSites(links);
}
else
{
phantom.exit();
}
}
}, 10000);
});
}
var links = ["http://edition.cnn.com", "http://stackoverflow.com"];
processSites(links);
I'm having a problem with the way I save information in ajax with alert, I made it using confirm in JQuery but the button text can't be changed I so decided to make my own dialog box so I can modify the buttons, but the problem is the data saves before I click the save button.
function saveEdit(e) {
var result = '';
var item = $('input[name=username]').val();
$.ajax({
url: root + 'ccards/getAllDetails',
data: {
item: item
},
type: 'POST',
async: false,
dataType: 'json',
success: function(data) {
var dateObj = new Date();
var month = dateObj.getUTCMonth() + 1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var hour = dateObj.getUTCHours()
var minute = dateObj.getUTCMinutes();
var second = dateObj.getUTCSeconds();
var datetoday = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
var selected_date = Date.parse(data.modified);
var today = Date.parse(datetoday);
var d = new Date(data.modified);
var h = d.getHours();
var m = d.getMinutes();
var username = data.username.toUpperCase();
var coreuser = data.core_user.username.toUpperCase();
var hr = '';
var time = '';
if (h <= '12') {
hr = h;
time = hr + ":" + m + " AM";
} else {
hr = h - 12;
time = hr + ":" + m + " PM";
}
if (Math.abs(today - selected_date) <= 60 * 60 * 24 * 1000) {
$('#confirmSave').show().dialog({
height: 200,
width: 500,
zIndex: 10,
modal: true,
resizable: false
});
$('#time').html(time);
$('#coreuser').html(coreuser);
if ($('#confirmSave button[name=submit]').data('clicked')) {
result = true;
} else if ($('#confirmSave button[name=cancel]').data('clicked')) {
result = false;
}
}
}
});
return result;
}
$('.clientForm').submit(function(event) {
var form = this;
console.log(form);
if ($("input[name='action']", form).val() == 'save' || $("input[name='action']", form).val() == 'savenew' || $("input[name='action']", form).val() == 'login') {
if ((!validate_email(form)) || (!validate(form))) {
mode = 'edit';
setMode(mode);
return false;
}
}
var save = saveEdit();
if (save == true) {
var dt = $(this).serializeArray();
var action = root + $("input[name='module']", form).val() + $("input[name='method']", form).val();
$('.fields', this).slideUp('fast');
$('.response', this).html("<div class='load'>Processing, please wait...</div>");
$.ajax({
type: 'POST',
url: action,
data: dt,
dataType: 'json',
success: function(data) {
if (data) procJSON.init(data, form);
},
complete: function(data) {
},
error: function(data) {
onError(data);
}
});
}
return false;
});
I recently used the noty plugin, alongside jQuery's deferred to solve a similar problem.
First, a function to show the confirm dialog and return a promise-like object, which resolves to true if the Ok button is pressed, or false if the Cancel button is pressed.
function showConfirm(msg) {
var dfd = $.Deferred();
noty({
text: msg,
type: 'confirm',
dismissQueue: false,
layout: 'center',
theme: 'defaultTheme',
modal: true,
buttons:
[{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: $noty => {
$noty.close();
dfd.resolve(true);
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: $noty => {
$noty.close();
dfd.resolve(false);
}
}]
});
return dfd.promise();
}
Then you can do something like...
$('.clientForm').submit(function(event) {
showConfirm("Do you wish to save?").then(function(confirmed) {
if (!confirmed) {
return;
}
// make ajax request here
}
}
I am using this plugin:http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Display-Instagram-Photos-On-Your-Web-Page-Instagram-Lite.html
When I set up my username and client-ID, it pulls photos from the wrong feed, for which I don't even have access (it pulls from helaspamexico, but instead it should be pulling from helaspa -> I am logged in to this and have generated client-ID for this)... Has anyone experienced something similar?
/*!
Name: Instagram Lite
Dependencies: jQuery
Author: Michael Lynch
Author URL: http://michaelynch.com
Date Created: January 14, 2014
Licensed under the MIT license
*/
;(function($) {
$.fn.instagramLite = function(options) {
// return if no element was bound
// so chained events can continue
if(!this.length) {
return this;
}
// define plugin
plugin = this;
// define default parameters
plugin.defaults = {
username: null,
clientID: null,
limit: null,
list: true,
videos: false,
urls: false,
captions: false,
date: false,
likes: false,
comments_count: false,
max_id: null,
load_more: null,
error: function() {},
success: function() {}
}
// vars
var s = $.extend({}, plugin.defaults, options),
el = $(this);
var getMaxId = function(items) {
// return id of last item
return items[items.length-1].id;
};
var formatCaption = function(caption) {
var words = caption.split(' '),
newCaption = '';
for(var i = 0; i < words.length; i++) {
var word;
if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else if(words[i][0] == '#') {
var a = ''+words[i]+'';
word = a;
} else {
word = words[i]
}
newCaption += word + ' ';
}
return newCaption;
};
var loadContent = function() {
// if client ID and username were provided
if(s.clientID && s.username) {
// for each element
el.each(function() {
var el = $(this);
// search the user
// to get user ID
$.ajax({
type: 'GET',
url: 'https://api.instagram.com/v1/users/search?q='+s.username+'&client_id='+s.clientID+'&callback=?',
dataType: 'jsonp',
success: function(data) {
if(data.data.length) {
// define user namespace
var thisUser = data.data[0];
// construct API endpoint
var url = 'https://api.instagram.com/v1/users/'+thisUser.id+'/media/recent/?client_id='+s.clientID+'&count='+s.limit+'&callback=?';
// concat max id if max id is set
url += (s.max_id) ? '&max_id='+s.max_id : '';
$.ajax({
type: 'GET',
url: url,
dataType: 'jsonp',
success: function(data) {
// if success status
if(data.meta.code === 200 && data.data.length) {
// for each piece of media returned
for(var i = 0; i < data.data.length; i++) {
// define media namespace
var thisMedia = data.data[i],
item;
// if media type is image or videos is set to false
if(thisMedia.type === 'image' || !s.videos) {
// construct image
item = '<img class="il-photo__img" src="'+thisMedia.images.standard_resolution.url+'" alt="Instagram Image" data-filter="'+thisMedia.filter+'" />';
// if url setting is true
if(s.urls) {
item = ''+item+'';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '<div class="il-photo__meta">';
}
// if caption setting is true
if(s.captions && thisMedia.caption) {
item += '<div class="il-photo__caption" data-caption-id="'+thisMedia.caption.id+'">'+formatCaption(thisMedia.caption.text)+'</div>';
}
// if date setting is true
if(s.date) {
var date = new Date(thisMedia.created_time * 1000),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
date = month +'/'+ day +'/'+ year;
item += '<div class="il-photo__date">'+date+'</div>';
}
// if likes setting is true
if(s.likes) {
item += '<div class="il-photo__likes">'+thisMedia.likes.count+'</div>';
}
// if caption setting is true
if(s.comments_count && thisMedia.comments) {
item += '<div class="il-photo__comments">'+thisMedia.comments.count+'</div>';
}
if(s.captions || s.date || s.likes || s.comments_count) {
item += '</div>';
}
}
if(thisMedia.type === 'video' && s.videos) {
if(thisMedia.videos) {
var src;
if(thisMedia.videos.standard_resolution) {
src = thisMedia.videos.standard_resolution.url;
} else if(thisMedia.videos.low_resolution) {
src = thisMedia.videos.low_resolution.url;
} else if(thisMedia.videos.low_bandwidth) {
src = thisMedia.videos.low_bandwidth.url;
}
item = '<video poster="'+thisMedia.images.standard_resolution.url+'" controls>';
item += '<source src="'+src+'" type="video/mp4;"></source>';
item += '</video>';
}
}
// if list setting is true
if(s.list && item) {
// redefine item with wrapping list item
item = '<li class="il-item" data-instagram-id="'+thisMedia.id+'">'+item+'</li>';
}
// append image / video
if(item !== '') {
el.append(item);
}
}
// set new max id
s.max_id = getMaxId(data.data);
// execute success callback
s.success.call(this);
} else {
// execute error callback
s.error.call(this, data.meta.code, data.meta.error_message);
}
},
error: function() {
// recent media ajax request failed
// execute error callback
s.error.call(this);
}
});
} else {
// error finding username
// execute error callback
s.error.call(this);
}
},
error: function() {
// search username ajax request failed
// execute error callback
s.error.call(this);
}
});
});
} else {
// username or client ID were not provided
// execute error callback
s.error.call(this);
};
}
// bind load more click event
if(s.load_more){
$(s.load_more).on('click', function(e) {
e.preventDefault();
loadContent();
});
}
// init
loadContent();
}
})(jQuery);
<ul class="instagram"></ul>
Load more
<br clear="all">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// Wait untill everything loads
$(window).load(function(){
$('.instagram').instagramLite({
username: 'helaspa',
clientID: 'ecdadd6520c04f5b8ae8bfdc888dd59c',
urls: true,
limit: 10,
load_more: '.instagram-more',
captions: false,
likes: false,
comments_count: false,
success: function() {
console.log('The request was successful!');
},
error: function(errorCode, errorMessage) {
console.log('There was an error');
if(errorCode && errorMessage) {
alert(errorCode +': '+ errorMessage);
}
}
});
});
</script>
If you are looking for a bad but quick solution, just put a '$' on the end of your username. The result of the API call will have your result first (by dumb luck) so the library will work.
The library you are using is not parsing the result of the query API correctly. The query API returns results for usernames similar to your query and doesn't filter results that are the wrong username.
Really, you should submit a patch to the library to use an API other than search: https://instagram.com/developer/endpoints/users/
Here is the bad the function:
https://github.com/michael-lynch/instagram-lite/blob/master/src/instagramLite.js#L95