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
Related
I have this below function to filter search
function GetFilters()
{
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
var categoryid = loc.pathname.split('/').pop();
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get all keys.
var keys = Object.keys(data);
var fdata = "";
// iterate over them and create the fdata
keys.forEach(function(key,i){
if (i>0) fdata += '&'; // if its not the first key add &
fdata += key+"="+data[key].join(',');
});
$.ajax({
type: "get",
url: "<?php echo $appURL; ?>/productByCategory",
data: {
"fdata": fdata,
"categoryID": categoryid
},
success: function (response) {
$('.productCategory').html(response);
}
});
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
}
window.onload = GetFilters;
and now I want to run the function every page loaded, but it seems there is no effect and display is empty.
PHP
if(isset( $_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))
{
}
If I remove this: if(isset( $_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))
{
}
I can see the data display.
I need to do this because prevent user directly open productByCategory.php
How to do that?
I am new to AngularJS1 and Js. Here i am uploading a file which will be saved on my drive as well as in mongodb. What I am trying to do is to get the uploaded file name which can easily be seen here in attached picture. Kindly help me out with this.
$scope.uploadedFileList.push(p);
$('#addproFile').ajaxfileupload({
action: 'http://' + window.location.hostname + ':' + window.location.port + '/api/upload',
valid_extensions : ['md','csv','css', 'txt'],
params: {
dummy_name: p
},
onComplete: function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
/* $scope.nameString = uploadedFileList.join(',');
$scope.$apply();*/
},
onCancel: function() {
console.log('no file selected');
}
});
This is my controller
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true == settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
} else {
uploading_file = false;
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery )
this is my ajax file upload function
Here's my problem:
I load a first time my tree to display him.
I can change the value of the Session's files name "state" to enable or disable a node in my tree.
But after I change ne value in my database and return the JSON, I read again the tree to refresh my tree with the changes but it's failed and write in console :
" TypeError: Tree_view.getElementsByClassName(...)[0].children[(item.id_perso - 1)].children[1] is undefined".
That I don't understand is I pass my first time by these functions and it work well, but when I reload it failed apparently because the it undefined.
Thank's for any help.
$(document).ready(function() {
$('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node);
var treeview = $('#Tree_view').data('kendoTreeView');
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
if (item.level() == 0) {
setTimeout(function() { waitDisable(item, treeview); }, 1000);
}
}
function waitDisable(item, treeview) {
if (item.fields.type == "parcours")
{
var node = Tree_view.getElementsByClassName('k-group')[0].children[item.id_perso - 1].children[1].children;
for (i = 0; i < item.children._data.length; i ++)
{
if (item.children._data[i].state != null) {
node[i].children[0].children[1].className = "k-in k-state-disabled";
node[i].children[0].children[0].className = ".k-icon-remove";
}
else node[i].children[0].children[0].className = "k-icon k-plus";
addRow(node, item, i, treeview);
}
}
}
var cmp = 0;
var One_Time = false;
function addRow(node_Here, item, i, treeview) {
var actual_row = node_Here[i].children[0];
if (actual_row.childNodes.length < 3) {
var newSpan = document.createElement('button');
if (item.children._data[i]._childrenOptions.data.state != null) {
newSpan.appendChild(document.createTextNode("Re-Up"));
newSpan.className = "change_state btn btn-success btn-xs";
}
else {
newSpan.appendChild(document.createTextNode("Down"));
newSpan.className = "change_state btn btn-danger btn-xs";
}
actual_row.appendChild(newSpan);
}
cmp += 1;
if (cmp == item.children._data.length)
One_Time = true;
if (One_Time) {
addClickListner(item, i, treeview);
One_Time = false;
cmp = 0;
}
}
function addClickListner(item, i, treeview) {
$(".change_state").click(function (event) {
var name_Promo_Rm = event.target.parentNode.children[1].textContent;
var User_Select = event.view.Parcours.transport.read.data.user_id;
$.ajax({
url: '#Url.Action("ChangeStatutBase", "Users")',
type: 'GET',
dataType: 'json',
data: { Name_Promo: name_Promo_Rm, User_id: User_Select },
});
refreshTree(treeview);
})
}
// Refresh tree
function refreshTree(treeview) {
// Save open items
saveExpandedItems(treeview);
// Reload data source
treeview.dataSource.read();
// Load open items
console.log("OKKKKKKK");
setTimeout(loadExpandedItems(), 600);
}
I've resolved my problem, in the "setTimeout" in the bottom I've placed "()" in the first parameter and it doesn't put the pause and data don't have the time to be loaded.
I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.
I have an input text box which fires each time when the user enters data and fills the input text.I'm using bootstrap typehead. Problem is when i enter a letter a it does fire ajax jquery call and fetch the data but the input text box is not populated.Now when another letter aw is entered the data fetched against letter a is filled in the text area.
I have hosted the code here http://hakunalabs.appspot.com/chartPage
Ok so here is part of my html code
<script type="text/javascript">
$(document).ready(function () {
$('#txt').keyup(function () {
delay(function () {
CallData();
}, 1000);
});
});
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
</script>
<input type="text" id="txt" runat="server" class="span4 typeahead local remote" placeholder="Search..." />
And here is my javascript code
var DataProvider;
function CallData() {
DataProvider = [];
var vdata = $('#txt').val();
if (vdata != "") {
var urlt = "http://examples/search?keyword=" + vdata + "&callback=my_callback";
$.ajax({
type: "GET",
url: urlt,
jsonpCallback: "my_callback",
dataType: "jsonp",
async: false,
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
}
function my_callback(data) {
var NameArray = new Array();
var descArray = new Array();
for (var i = 0; i < data.count; i++) {
NameArray.push(data.response[i].days_till_close + " Days Left | " + data.response[i].name + " | " + data.response[i].description);
}
for (var i = 0; i < data.count; i++) {
descArray.push(data.response[i].description);
}
DataProvider = [];
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: NameArray[i], description: descArray[i] };
DataProvider.push(dataObject);
}
var vdata = $('#txt').val();
var urlp = "http://example.com/v1/members/search?keyword=" + vdata + "&my_callbackMember";
$.ajax({
type: "GET",
url: urlp,
jsonpCallback: "my_callbackMember",
dataType: "jsonp",
error: function (xhr, errorType, exception) {
var errorMessage = exception || xhr.statusText;
alert("Excep:: " + exception + "Status:: " + xhr.statusText);
}
});
}
function my_callbackMember(data) {
var memberArray = new Array();
for (var i = 0; i < data.count; i++) {
memberArray.push(data.response[i].name);
}
for (var i = 0; i < data.count; i++) {
var dataObject = { id: i + 1, name: memberArray[i] };
DataProvider.push(dataObject);
}
localStorage.setItem("name", JSON.stringify(DataProvider));
var sources = [
{ name: "local", type: "localStorage", key: "name", display: "country" }
];
$('input.typeahead.local.remote').typeahead({
sources: [{ name: "", type: "localStorage", key: "name", display: "name"}],
itemSelected: function (obj) { alert(obj); }
});
}
Your issue is that typeahead can only present to you the results that are already in localstorage at the moment when you do a key press. Because your results are fetched via AJAX, they only show up in localstorage a second or so AFTER you've pressed the key. Therefore, you will always see the results of the last successful ajax requests in your typeahead results.
Read the bootstrap documentation for type aheads http://twitter.github.com/bootstrap/javascript.html#typeahead and read the section about "source". You can define a "process" callback via the arguments passed to your source function for asynchronous data sources.