I am doing on a instagram api, and I get information from server including user profiles and two more kinds. I want to put the information in a table on html. Each row is related to a username(since I searched for username), and there are profiles and two more things on each row. I am a little confused about how to do that.
here is my code:
var searchUsers = function(query,count){
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
data: {
q: query,
count: count,
access_token: access_token,
},
url: "https://api.instagram.com/v1/users/search",
success: function(data) {
// placing the images on the page
console.log(data);
if (data.data.length>0){
var resultShow = $("#users_result");
for (var i in data.data){
resultShow.append("<img src='" + data.data[i].profile_picture + "'></img>");
// var username = "https://www.instagram.com/"+ data.data[i].username;
// console.log(username);
resultShow.append("<a target='_blank' href = 'https://www.instagram.com/"+data.data[i].username+"'>user profile</a>");
// var id = data.data[i].id;
// console.log(id);
$.ajax({
url: 'https://api.instagram.com/v1/users/' + data.data[i].id + '/media/recent/',
type: "GET",
dataType: "jsonp",
data: {access_token: access_token},
success: function(data2){
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
},
error: function(data2){
console.log(data2);
}
});
}
} else {
resultShow.html("Noting found!");
}
},
error: function(data){
console.log(data);
}
});
};
You can change almost any value in a page using the innerHTML property.
Ex:document.getElementById("demo").innerHTML = "Paragraph changed!";
http://jsfiddle.net/blazeeboy/fNPvf/
To change the values inside a table, just assign an ID to it and change with your Javascript function.
In your case, I would suggest inserting any Javascript parameter between line 31 and 32.
success: function(data2){
var title = document.getElementById('title');
var username = "https://www.instagram.com/"+ data.data[i].username;
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
It will write the username into the table with id "title", if you need more than one table value, you'll need to make a array and use the for loop to insert an specific value into a specific table, tr, etc... id
success: function(data2){
//tableids are the ids of each table row or column in the order you wanna write them
var tableids = ['0', '1', '2'];//starting at 0
var username = "https://www.instagram.com/"+ data.data[i].username;
var title = document.getElementById(tableids[i]);
title.innerHTML = username;
console.log(data2);
for(x in data2.data){
// console.log(data2.data[x].link);
resultShow.append("<a target='_blank' href = '"+data2.data[x].link+"'><img src='" + data2.data[x].images.thumbnail.url + "'></img></a>");
}
}
Hope it was clear enough
Related
I have implemented autocomplete feature using JQuery, but now I wanted to store last 20 searched per inputfield in browser. So, if user when focuses the suggestion will be fetched from the browser. If user types then from Rest API using ajax I am fetching the data.
$("input[type='text']").autocomplete({
source: function(request, response) {
var id = $(this.element).prop("id");
var id2=this.element[0].id;
var id3=$(this.element.get(0)).attr('id');
console.log(id);
console.log(id2);
console.log(id3);
var params = {'page':1,'size':"10"};
params[id]=request.term;
var jsonParams = JSON.stringify(params);
$.ajax({
type: "POST",
url:"http://localhost:5645/search",
data: jsonParams,
headers: {"X-CSRF-TOKEN": $("input[name='_csrf']").val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
//const result = new Set()
var result=[];
console.log(id);
console.log(msg.details)
console.log(msg.details.length)
for(var i = 0; i < msg.details.length; i++) {
var obj = msg.details[i];
if(obj!=null && columnMapping[id]!=undefined && obj[columnMapping[id]]!=undefined){
console.log(obj[columnMapping[id]]);
//result.add(obj[columnMapping[id]]);
result.push(obj[columnMapping[id]]);
}
console.log(result);
}
//response(Array.from(result));
response(result);
}
/* error: function() {
response([]);
} */
})
},
select: function(event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label) : "Nothing selected, input was " + this.value);
return false;
}
}).autocomplete("instance")._renderItem = function(ul, item) {
console.log('test');
var item = $("<div>" + item.label + "</div>")
return $("<li>").append(item).appendTo(ul);
};
Above is the jquery code which I am using for autocomplete. So, if no input is there I need to fetch from browser recent search. So, when user types unique search keys should be inserted. How I can store and retrive using javascript.
I am trying to fetch data from the API and display them in format Name + clickable website link.
I was able to display data but the link is represented as text rather than hyperlink.
There is my Ajax script:
$(function() {
$.ajax({
url: "url",
type: "get",
dataType: "json",
success: function(data) {
console.log(data.name);
for (i = 0; data.length; i++) {
name = data[i].name;
web_pages = data[i].web_pages;
var link = document.createElement('a');
link.setAttribute('href', web_pages);
link.innerHTML = web_pages;
var paragraph = $("<p />", {
text: name + " " + link
});
$("#display-resources").append(paragraph);
}
}
});
});
It's because you're inserting the link as text (string). Try this instead
var paragraph = $("<p />", { text: name + " " }).append(link)
Given an url like this:
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg
How do i get it to be like
https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,44_AL_.jpg
The issue I am having is with retrieving IMDB poster images, using this:
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: form.serialize(), // assuming the form has a hidden input with api_key name, containing your API key
crossDomain: true,
dataType: "jsonp",
success: function(data) {
window.console.log(data);
}
});
});
I get a json response like:
"thumbnail": "https://images-na.ssl-images-amazon.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw##._V1_UX32_CR0,0,32,44_AL_.jpg"
I get no poster and the api i am using don't help, yet that thumbnail image is including various formats, one of which is 44_al which is what i would like to leave as a string in order to output it like:
function imdbLoad() {
var form = $("#usp-title").val();
var encodedTerm = encodeURIComponent(form);
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
q: encodedTerm
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
$.each(data.data.results, function(i, items) {
$("#imdb").append('<h2>'+i+'</h2>');
$.each(items, function(k, item) {
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ item.thumbnail +"'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
});
});
}
});
}
Unless anyone has any other way to grab the poster url
You can either use regex to replace string part that is not required
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var regex = /,.*(?=,)/g;
console.log(url.replace(regex, ''))
or split using comma(,) and join first and last part.
var url = "https://images-na.ssl-images-amazon.com/images/M/MV5BMTM3MTc3OTc0NF5BMl5BanBnXkFtZTcwOTQ0OTM1MQ##._V1._CR34,0,295,440_UX32_CR0,0,32,44_AL_.jpg"
var parts = url.split(',');
console.log(parts[0] + ',' + parts.pop())
This is a bit of a longer code as I have included few bits such as limiting the number of results but basically what I noticed is that after the ## the whole string is about image size. So instead of using a regex (that would be the answer for this specific question), I could simply add the dimension to the url as a string like:
<img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'>
Full code
$('form[name="search-imdb"]').on("submit", function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
url: "http://imdb.wemakesites.net/api/search",
data: {
api_key: "...",
q: form.find('input[name="q"]').val()
},
crossDomain: true,
dataType: "jsonp",
success: function(data) {
$("#imdb").empty();
var thumbnailMod, limiteRes = 1;
if (data.data.results.titles !== undefined) {
$("#imdb").append('<h2>Titles</h2>');
$.each(data.data.results.titles, function(i, item) {
thumbnailMod = item.thumbnail.split('#.');
if (thumbnailMod.length > 1) {
if (limiteRes > 3) {
return;
}
limiteRes++;
$("#imdb").append("<div class='col-xs-12 col-md-4'><div class='thumbnail'><img class='img-responsive' src='"+ thumbnailMod[0] + "#._V1_UX500_CR0,0,500,550_AL_.jpg'><div class='caption'><h3>"+ item.title +"</h3><p>"+ item.title +"</p></div></div>");
}
});
} else {
console.log('No titles found for this search.');
}
}
});
});
I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0"es=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});
I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'¶1='+ para1 +
'¶2=' + para2+
'¶3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}