With reference to AutoComplete in Bot Framework , I had implemented GET method of search URL.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="https://cdn.botframework.com/botframework-
webchat/latest/botchat.css" rel="stylesheet" />
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
<link rel="stylesheet"
href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.botframework.com/botframework-
webchat/latest/botchat.js"></script>
<style>
.wc-chatview-panel {
width: 350px;
height: 500px;
position: relative;
}
</style>
</head>
<body>
<div id="mybot"></div>
</body>
</html>
<script src="https://cdn.botframework.com/botframework-
webchat/latest/CognitiveServices.js"></script>
<script type="text/javascript">
var searchServiceName = "abc";
var searchServiceApiKey = "xyzabc";
var indexName = "index1";
var apiVersion = "2017-11-11";
var corsanywhere = "https://cors-anywhere.herokuapp.com/";
var suggestUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/suggest?api-version=" + apiVersion + "&search=how";
var autocompleteUri = "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs/autocomplete?api-version=" + apiVersion;
var searchUri = corsanywhere + "https://" + searchServiceName + ".search.windows.net/indexes/" + indexName + "/docs?api-version=" + apiVersion;
BotChat.App({
directLine: {
secret: "DIRECTLINEKEY"
},
user: {
id: 'You'
},
bot: {
id: '{BOTID}'
},
resize: 'detect'
}, document.getElementById("mybot"));
</script>
<script type="text/javascript">
$(function () {
$("input.wc-shellinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "GET",
url: searchUri,
dataType: "json",
headers: {
"api-key": searchServiceApiKey,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "SAMPLEURL",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE"
},
data: JSON.stringify({
top: 5,
fuzzy: false,
// suggesterName: "", //Suggester Name according to azure search index.
search: request.term
}),
success: function (data) {
if (data.value && data.value.length > 0) {
//RESPONSE FORMATTED as per requirements to hold questions based on input value(Below code is only for my reference i added)
var result = "";
var inputValue = request.term;
for (i = 0; i < data.value.length; i++) {
var allquestions = data.value[i].questions;
if (allquestions.length > 0) {
for (j = 0; j < allquestions.length; j++)
if (allquestions[j].toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
result = result + "," + allquestions[j];
}
}
}
if (result != null) {
alert(result);
response(data.value.map(x => x["#search.text"])); ---Caught Error at this STEP
}
else { alert("no data"); }
}
else {
alert("No response for specific search term");
}
}
});
},
minLength: 3,
position: {
my: "left top",
at: "left bottom",
collision: "fit flip"
},
select: function (Event, ui) {
$(document).ready(function () {
var input = document.getElementsByClassName("wc-shellinput")[0];
var lastValue = input.value;
input.value = ui.item.value;
var event = new CustomEvent('input', {
bubbles: true
});
// hack React15
event.simulated = true;
// hack React16
var tracker = input._valueTracker;
if (tracker) {
tracker.setValue(lastValue);
}
input.dispatchEvent(event);
})
$('wc-textbox').val("");
Event.preventDefault();
$(".wc-send:first").click();
}
});
});
</script>
My Sample API Output:
{ "#odata.context": "URL", "value": [{ "questions": [ "where are you", "where have you been", ] }, { "questions": [ "How are you?" ] } ] }
I am getting API response successfully (data.value) but got exception at
response(data.value.map(x => x["#search.text"]));
Error Message:Uncaught TypeError: Cannot read property 'label' of undefined
I had tried replacing #search.text with "value" and "#data.context" but still am getting error. I want to display all questions data based on user input
I am finally able to fix my issue with below solution.
Note: JQuery Autocomplete "response" method takes array as data type.
Solution:
1) when we are passing entire API array results to "response" method, results must have "label" keyword with proper data.
sample code while passing entire API results:
response(data.value.map(x => x["#search.text"]));
2) when we don't have "label" keyword in API response, we have to format response as per requirements and create a new array of data that we want to display as auto suggest and pass to "response" method.
Below is code for same:
var autoSuggestDataToDisplay= [];
var inputValue = request.term;
for (i = 0; i < data.value.length; i++) {
var allquestions = data.value[i].questions;
if (allquestions.length > 0) {
for (j = 0; j < allquestions.length; j++)
if (allquestions[j].toLowerCase().indexOf(inputValue.toLowerCase()) != -1) {
result = result + "," + allquestions[j];
if (autoSuggestDataToDisplay.indexOf(allquestions[j].toLowerCase()) === -1) {
autoSuggestDataToDisplay.push(allquestions[j].toLowerCase());
}
}
}
}
if (result != null) { response(autoSuggestDataToDisplay); }
else { alert("no data"); }
As i dont have "label" in API response, I followed #2 approach and solved it.
Related
I am trying to save data using ajax. The ajax is inside my javascript file and passed to my controller and route. However the issue is it cannot save the data into my database.
Here is my jquery.hotspot.js file that include ajax:
(function ($) {
var defaults = {
// Object to hold the hotspot data points
data: [],
// Element tag upon which hotspot is (to be) build
tag: 'img',
// Specify mode in which the plugin is to be used
// `admin`: Allows to create hotspot from UI
// `display`: Display hotspots from `data` object
mode: 'display',
// HTML5 LocalStorage variable where hotspot data points are (will be) stored
LS_Variable: '__HotspotPlugin_LocalStorage',
// CSS class for hotspot data points
hotspotClass: 'HotspotPlugin_Hotspot',
// CSS class which is added when hotspot is to hidden
hiddenClass: 'HotspotPlugin_Hotspot_Hidden',
// Event on which the hotspot data point will show up
// allowed values: `click`, `hover`, `none`
interactivity: 'hover',
// Action button CSS classes used in `admin` mode
save_Button_Class: 'HotspotPlugin_Save',
remove_Button_Class: 'HotspotPlugin_Remove',
send_Button_Class: 'HotspotPlugin_Send',
// CSS class for hotspot data points that are yet to be saved
unsavedHotspotClass: 'HotspotPlugin_Hotspot_Unsaved',
// CSS class for overlay used in `admin` mode
hotspotOverlayClass: 'HotspotPlugin_Overlay',
// Enable `ajax` to read data directly from server
ajax: false,
ajaxOptions: { url: '' },
listenOnResize: true,
// Hotspot schema
schema: [
{
'property': 'Title',
'default': ''
},
{
'property': 'Message',
'default': ''
}
]
};
// Constructor
function Hotspot(element, options) {
var widget = this;
// Overwriting defaults with options
this.config = $.extend(true, {}, defaults, options);
this.element = element;
// `tagElement`: element for which hotspots are being done
this.tagElement = element.find(this.config.tag);
// Register event listeners
$.each(this.config, function (index, fn) {
if (typeof fn === 'function') {
widget.element.on(index + '.hotspot', function (event, err, data) {
fn(err, data);
});
}
});
if (this.config.mode != 'admin' && this.config.listenOnResize) {
$(window).on('resize', function () {
$(element).find('.' + widget.config.hotspotClass).remove();
widget.init();
});
}
if (this.config.tag !== 'img') {
widget.init();
return;
}
if (this.tagElement.prop('complete')) {
widget.init();
} else {
this.tagElement.one('load', function (event) {
widget.init();
});
}
}
Hotspot.prototype.init = function () {
this.parseData();
// Fetch data for `display` mode with `ajax` enabled
if (this.config.mode != 'admin' && this.config.ajax) {
this.fetchData();
}
// Nothing else to do here for `display` mode
if (this.config.mode != 'admin') {
return;
}
this.setupWorkspace();
};
Hotspot.prototype.createId = function () {
var id = "";
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 7; i++) {
id += letters.charAt(Math.floor(Math.random() * letters.length));
}
return id;
};
Hotspot.prototype.setupWorkspace = function () {
var widget = this;
// `data` array: to contain hotspot objects
var data = [];
var tHeight = $(widget.tagElement[0]).height(),
tWidth = $(widget.tagElement[0]).width(),
tOffset = widget.tagElement.offset(),
pHeight = $(widget.element[0]).height(),
pWidth = $(widget.element[0]).width(),
pOffset = widget.element.offset();
// Create overlay for the tagElement
$('<span/>', {
html: '<p>Click this Panel to Store Messages</p>'
}).css({
'height': (tHeight / pHeight) * 100 + '%',
'width': (tWidth / pWidth) * 100 + '%',
'left': (tOffset.left - pOffset.left) + 'px',
'top': (tOffset.top - pOffset.top) + 'px'
}).addClass(widget.config.hotspotOverlayClass).appendTo(widget.element);
// Handle click on overlay mask
this.element.delegate('span', 'click', function (event) {
event.preventDefault();
event.stopPropagation();
// Get coordinates
var offset = $(this).offset(),
relativeX = (event.pageX - offset.left),
relativeY = (event.pageY - offset.top);
var height = $(widget.tagElement[0]).height(),
width = $(widget.tagElement[0]).width();
var hotspot = { x: relativeX / width * 100, y: relativeY / height * 100 };
var schema = widget.config.schema;
for (var i = 0; i < schema.length; i++) {
var val = schema[i];
var fill = prompt('Please enter ' + val.property, val.default);
if (fill === null) {
return;
}
hotspot[val.property] = fill;
}
data.push(hotspot);
// Temporarily display the spot
widget.displaySpot(hotspot, true);
});
// Register admin controls
var button_id = this.createId();
$('<button/>', {
text: "Save data"
}).prop('id', ('save' + button_id)).addClass(this.config.save_Button_Class).appendTo(this.element);
$('<button/>', {
text: "Remove data"
}).prop('id', ('remove' + button_id)).addClass(this.config.remove_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('save' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.saveData(data);
data = [];
});
$(this.element).delegate('button#' + ('remove' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.removeData();
});
if (this.config.ajax) {
$('<button/>', {
text: "Send to server"
}).prop('id', ('send' + button_id)).addClass(this.config.send_Button_Class).appendTo(this.element);
$(this.element).delegate('button#' + ('send' + button_id), 'click', function (event) {
event.preventDefault();
event.stopPropagation();
widget.sendData();
});
}
};
Hotspot.prototype.fetchData = function () {
var widget = this;
// Fetch data from a server
var options = {
data: {
HotspotPlugin_mode: "Retrieve"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function (data) {
// Storing in localStorage
localStorage.setItem(widget.config.LS_Variable, data);
widget.parseData();
})
.fail($.noop);
};
Hotspot.prototype.parseData = function () {
var widget = this;
var data = this.config.data,
data_from_storage = localStorage.getItem(this.config.LS_Variable);
if (data_from_storage && (this.config.mode === 'admin' || !this.config.data.length)) {
data = JSON.parse(data_from_storage);
}
$.each(data, function (index, hotspot) {
widget.displaySpot(hotspot);
});
};
Hotspot.prototype.displaySpot = function (hotspot, unsaved) {
var widget = this;
var spot_html = $('<div/>');
$.each(hotspot, function (index, val) {
if (typeof val === "string") {
$('<div/>', {
html: val
}).addClass('Hotspot_' + index).appendTo(spot_html);
}
});
var height = $(this.tagElement[0]).height(),
width = $(this.tagElement[0]).width(),
offset = this.tagElement.offset(),
parent_offset = this.element.offset();
var spot = $('<div/>', {
html: spot_html
}).css({
'top': (hotspot.y * height / 100) + (offset.top - parent_offset.top) + 'px',
'left': (hotspot.x * width / 100) + (offset.left - parent_offset.left) + 'px'
}).addClass(this.config.hotspotClass).appendTo(this.element);
if (unsaved) {
spot.addClass(this.config.unsavedHotspotClass);
}
if (this.config.interactivity === 'hover') {
return;
}
// Overwrite CSS rule for `none` & `click` interactivity
spot_html.css('display', 'block');
// Initially keep hidden
if (this.config.interactivity !== 'none') {
spot_html.addClass(this.config.hiddenClass);
}
if (this.config.interactivity === 'click') {
spot.on('click', function (event) {
spot_html.toggleClass(widget.config.hiddenClass);
});
} else {
spot_html.removeClass(this.config.hiddenClass);
}
};
Hotspot.prototype.saveData = function (data) {
if (!data.length) {
return;
}
// Get previous data
var raw_data = localStorage.getItem(this.config.LS_Variable);
var hotspots = [];
if (raw_data) {
hotspots = JSON.parse(raw_data);
}
// Append to previous data
$.each(data, function (index, node) {
hotspots.push(node);
});
this.data=data;
$.ajax({
type:"POST",
url:"/store",
dataType:'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
Title:$('#Title').val(),
Message: $('#Message').val(),
x:$('#relativeX').val(),
y: $('#relativeY').val(),
},
success: function(data){
console.log(data,d);
},
error: function(data)
{
console.log(data);
},
});
localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));
this.element.trigger('afterSave.hotspot', [null, hotspots]);
};
Hotspot.prototype.removeData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null) {
return;
}
if (!confirm("Are you sure you wanna do everything?")) {
return;
}
localStorage.removeItem(this.config.LS_Variable);
this.element.trigger('afterRemove.hotspot', [null, 'Removed']);
};
Hotspot.prototype.sendData = function () {
if (localStorage.getItem(this.config.LS_Variable) === null || !this.config.ajax) {
return;
}
var widget = this;
var options = {
data: {
HotspotPlugin_data: localStorage.getItem(this.config.LS_Variable),
HotspotPlugin_mode: "Store"
}
};
$.ajax($.extend({}, this.config.ajaxOptions, options))
.done(function () {
widget.element.trigger('afterSend.hotspot', [null, 'Sent']);
})
.fail(function (err) {
widget.element.trigger('afterSend.hotspot', [err]);
});
};
$.fn.hotspot = function (options) {
new Hotspot(this, options);
return this;
};
}(jQuery));
Here is my route:
Route::get('hotspots','ImageController#getPin');
Route::post('store','ImageController#storePin')->name('store.storePin');
Here is my ImageController.php:
public function getPin()
{
$pin= Pin::select('Title','Message','x','y');
return hotspot::of($pin)->make(true);
}
public function storePin(Request $request)
{
$validation = Validator::make($request->all(), [
'Title' => 'required',
'Message' => 'required',
'x'=>'required',
'y'=>'required',
]);
if ($request->get('save','button_id') == "insert")
{
$pin = new Pin();
$pin->Title=$request->Title;
$pin->Message= $request->Message;
$pin->x = $request->relativeX;
$pin->y =$request->relativeY;
$pin->save();
//return Request::json($request);
}
}
Here is my hotspot.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Picomment Hotspot</title>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/bootsrap.min.css') }}">
<script type="text/javascript" src="{{ asset ('js/jquery.min.js') }}"></script>
<link rel="stylesheet" type="text/css" href="{{ asset ('css/jquery.hotspot.css') }}">
<link rel="stylesheet" type="text/css" href="{{ asset ('css/style.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
<div class="col-md-6" style="margin-top: 40px;">
<div id="theElement-a">
<img src="{{ asset('storage/'.$files) }}" alt="" title="">
</div>
</div>
</div>
<script type="text/javascript" src="{{ asset ('js/jquery.hotspot.js') }}"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#theElement-a").hotspot({
mode: "admin",
// uncomment
/*ajax: true,
ajaxOptions: {
'url': 'links.to.server'
},*/
interactivity: "click",
LS_Variable: "HotspotPlugin-a",
afterSave: function(err, data) {
if (err) {
console.log('Error occurred', err);
return;
}
alert('Saved');
// `data` in json format can be stored
// & passed in `display` mode for the image
localStorage.clear();
console.log(data);
},
afterRemove: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
window.location.reload();
},
afterSend: function(err, message) {
if (err) {
console.log('Error occurred', err);
return;
}
alert(message);
}
});
});
</script>
</body>
</html>
I've been trying to use Indeed.com's API to search for jobs based on location. However, I keep on getting the error saying that
https://ip-api.com/json/?callback=jQuery2140044062367054279905_1470512340351&_=1470512340352 Failed to load resource: net::ERR_CONNECTION_REFUSED
This is the code that I have:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Indeed Job search result</title>
<script src="//code.jquery.com/jquery-2.1.4.js" type="text/javascript"></script>
<style type="text/css">
.pagination li{
background-color: #000;
padding: 5px;
float:left;
margin-right: 2px;
border-radius: 5px;
color: #FFF;
cursor: pointer;
}
</style>
</head>
<body>
<script>
jQuery(function() {
var resultLinks = $('body').find('#pagination');
var location, country, city, region, limit = 10;
$.get("//ip-api.com/json/", function (response) {
console.log(response);
city = (isNull(response.city))?(response.city+","):"";
region = (isNull(response.region))?(response.region):"";
location = city + region;
country = response.country;
console.log(country);
}, "jsonp");
$( "#searchResult" ).click(function() {
jobSearch($('#location').val(),$('#jobname').val(),country,0,limit);
});
resultLinks.on('click', 'li', function (e) {
var start = ($(this).text() - 1) * limit, end = start + limit;
jobSearch($('#location').val(),$('#jobname').val(),country,start,end);
});
function isNull(value){
if(typeof(value) === "object" || typeof(value) === "undefined" || value === "null" || value === "")
return false;
else
return true;
};
function extractDomain(url) {
var domain;
//find & remove protocol (http, ftp, etc.) and get domain
if (url.indexOf("://") > -1) {
domain = url.split('/')[2];
}
else {
domain = url.split('/')[0];
}
//find & remove port number
domain = domain.split(':')[0];
return domain;
};
function jobSearch(location,data,country,start,end){
var serachData =data;
$.ajax({
cache: false,
data: $.extend({
publisher: '7778623931867371',
v: '2',
format: 'json',
q: data,
l: location,
radius: 50,
limit:limit,
sort: 'date',
highlight: 1,
filter: 1,
latlong: 1,
co: country.toLowerCase(),
userip: '',
useragent: ''
}, { start: start, end: end }),
dataType: 'jsonp',
type: 'GET',
timeout: 5000,
url: '//api.indeed.com/ads/apisearch'
})
.done(function( data ) {
var result="",pagination = "",i=2,style,url, paginationLimit = Math.ceil((data.totalResults)/limit);
$.each( data.results, function( i, item ) {
style = ((i%2) == 0)?"articaljoblistinggray":"articaljoblistingwhite"
result = result + '<a target="_blank" href="'+item.url+'"><li class="articaljoblisting '+style+'" style="margin-bottom:3px;">'+item.jobtitle+'<br /><span style="color:black;">'+item.source+' - '+item.formattedLocation+'</span></li></a>';
i++;
url = item.url;
});
for (i = 1; i <= paginationLimit; i++) {
pagination = pagination + '<li>'+i+'</li>';
}
$('#jobs-data').html('<ul style="list-style: none;margin: 0;padding:0;">'+result+'</ul><a style="float: right;" target="_blank" href="http://'+extractDomain(url)+'/jobs?q='+serachData+'&l='+location+'">Find more jobs</a>');
$('#pagination').html('<ul class="pagination" style="list-style: none;margin: 0;padding:0;">'+pagination+'</ul>');
});
};
});
</script>
</body>
</html>
Any help is appreciated!
This URL cannot be accessed from the browser. https://api.indeed.com/ads/apisearch But this can be https://www.indeed.com/. Please check if you have correct URL for the API call.
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
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.
Im using javascript SDK to send some invitations to friends, and i neeed to get the friends IDs. this is part of my code:
function RequestFriendship() {
FB.getLoginStatus(function (response) {
if (response.session && response.perms != null && response.perms.indexOf('user_about_me') != -1) {
Request();
}
else {
FB.ui({
method: 'auth.login',
perms: 'user_about_me,publish_stream',
display: 'iframe'
}, function (response3) {
if (response3 != null && response3.perms != null && response3.perms.indexOf('user_about_me') != -1) {
Request();
}
else {
alert('No invitations sent.');
}
});
}
});
and my Request method is:
function Request() {
FB.ui({ method: 'apprequests', message: 'Mensaje Publicidad', data: '', title: 'Titulo publicidad' },
function (response) {
if (response && response.request_ids) {
var ids = response.request_ids;
FB.api("/me/apprequests/?request_ids=" + ids[0], function (response2) {
alert(JSON.stringify(response2, replacer));
});
}
});
}
But every time run it i get an empty data in the FB.api("/me/apprequests/?request_ids=" + ids[0]. I dont know what im doing wrong, i think i worked fine for me some time ago but now it isnt. Is this a permission problem? I think user_about_me is enough to ask for apprequest but not sure anymore. Any help? Thanx
WEll i found the answer myself. Just use this:
if (response && response.request_ids) {
var ids = response.request_ids;
var _batch = [];
for (var i = 0; i < ids.length; i++) {
_batch.push({ "method": "get", "relative_url": ids[i] });
}
if (_batch.length > 0) {
FB.api('/', 'POST', { batch: _batch }, function (res) {
// var obj = eval('(' + res + ')');
for (var j = 0; j < res.length; j++) {
body = res[j].body;
var myObject = eval('(' + body + ')');
friendID = myObject.to.id;
// here you have every friendID
}
});
}
}
:)
You don't actually need to create a batch request. You can use the ids parameter on the root and give it the request_ids value returned from the dialog directly:
FB.api("/?ids=" + response.request_ids, callback);