Instagram API pagination - Previous Page - javascript

I am getting Instagram user's media with Jquery.
I need to get All user media, but Instagram API media limit is only 20 and API pagination returns only next link. There is no previous link.
I write code somethink like that, this is working with next but not working previous. And I stack here
function instaPhotos(page) {
var $limit = 1;
var $token = $('.instagram').data('instagramtoken');
var $nextId = $('.instagram').attr('data-instagramnext');
var $pageNumber = parseInt(localStorage.getItem('page'));
switch (page){
case 'next':
localStorage.setItem('page', ($pageNumber+1));
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit + '&max_id=' + $nextId
break;
case 'prev':
localStorage.setItem('page', ($pageNumber-1));
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit + '&min_id=' + $nextId
break;
default:
localStorage.setItem('page', 1);
var $url = 'https://api.instagram.com/v1/users/self/media/recent/?access_token=' + $token + '&count=' + $limit
}
console.log($pageNumber);
console.log($url);
$.ajax({
method: "GET",
url: $url,
dataType: "jsonp",
context: this,
success: function (r) {
if (r.pagination.next_max_id){
$('.instagram').attr('data-instagramnext', r.pagination.next_max_id);
}
// photo actions here.
}
});
}

First of all: you can increase media limit up to 33 photos. You should use count parameter on your querystring:
https://api.instagram.com/v1/tags/nofilter/media/recent?count=33&access_token=YOUR_ACCESS_TOKEN
About to navigate to previous page it seems to me that Instagram response will always be with the most recent published photos.
From Instagram API:
MIN_TAG_ID Return media before this min_tag_id.
MAX_TAG_ID Return media after this max_tag_id.
So let's think of 3 pages (from id #1 to id #100):
First page:
next_min_id #0
photo #1
photo #2
photo #3
...
photo #33
next_max_tag_id #34
Second page:
next_min_id #34 (equals to next_max_tag_id of first page)
photo #35
photo #36
photo #37
...
photo #66
next_max_tag_id #67
Third page:
next_min_id #67 (equals to next_max_tag_id of second page)
photo #68
photo #69
photo #70
...
photo #99
next_max_tag_id #100
While the querystring parameter max_tag_id limits the top of your result, min_tag_id limits the bottom of it. So if you use only min_tag_id as parameter the response will be equal the first page despite of the page min_tag_id value came from. After all the photos of first page (#1, #2, #3...) come before the min_tag_id of any other page (#34 and #67) and are the newest ones.
I think to accomplish this task the only way is using max_tag_id querystring parameter or next_url result (entire url ready to use - easier).
You should save or max_tag_id's or (even better and faster) the entire result and control the logic on your code. Working example:
var token = "<your_access_token>";
var nextURL = "https://api.instagram.com/v1/tags/riodejaneiro/media/recent?count=33&access_token=" + token;
var currentPage = 0;
var pages = new Array();
$(function() { requestInstagram(); });
function previousPage() {
currentPage = (currentPage>0) ? currentPage-1 : 0;
// show photos of currentPage
console.log("Page " + currentPage);
console.log("First photo:" + pages[currentPage][0].id);
}
function nextPage() {
if (++currentPage < pages.length ) {
// show photos of currentPage
console.log("Page " + currentPage);
console.log("First photo:" + pages[currentPage][0].id);
} else {
requestInstagram();
}
}
function requestInstagram() {
$.ajax({
method: "GET",
url: nextURL ,
dataType: "jsonp",
context: this,
success: function (r) {
if (r.meta.code == "200") {
pages[pages.length] = r.data;
// show photos here
console.log("Page " + currentPage);
console.log("First photo:" + pages[currentPage][0].id);
nextURL = r.pagination.next_url; // you should implement a way to identify the last page
console.log(nextURL);
}
}
});
}
Good luck!

I tested min_id, looks like it is broken on sandbox mode, it does however work correctly on old APIs that are live like on http://gramfeed.com
You can test sandbox mode here: http://www.gramfeed.com/accounts/sandbox

Related

session name isnt showing when loading php file

So basically i got this code from online which allows you to load body content via ajax/php.
Site i got the code from:
https://www.webdesignerdepot.com/2014/02/how-to-supercharge-your-sites-speed-with-ajax-and-jquery/
If you look at that site(specifically the ajax/php demo, not the first jquery demo) you'll see that ajax loads load.php, then it loads different html files. Ive edited it to load different php files, however the loaded content displays the html code in my php file but not the php code(session name variable).
Here's the custom.js(ajax) file:
$(function() {
$('.left-sidebar a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
var $pageRoot = $linkClicked.replace('#', '');
if (!$(this).hasClass("current")) {
$(".left-sidebar a").removeClass("current");
$(this).addClass("current");
$.ajax({
type: "POST",
url: "load.php",
data: 'page='+$pageRoot,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#main-content').html(msg);
$('#main-content section').hide().fadeIn();
}
}
});
}
else {
event.preventDefault();
}
});
var hash = window.location.hash;
hash = hash.replace(/^#/, '');
switch (hash) {
case 'steal' :
$("#" + hash + "-link").trigger("click");
break;
case 'extort' :
$("#" + hash + "-link").trigger("click");
break;
case 'kill' :
$("#" + hash + "-link").trigger("click");
break;
case 'welcome' :
$("#" + hash + "-link").trigger("click");
break;
case 'profile' :
$("#" + hash + "-link").trigger("click");
break;
}
});
here's the load.php file:
<?php
if(!$_POST['page'])
die("0");
$page = $_POST['page'];
// echo $page; // rob, steal, extort, kill, welcome, profile
if(file_exists('pages/'.$page.'.php'))
echo file_get_contents('pages/'.$page.'.php');
else
echo 'There is no such page!';
?>
Here's the welcome.php file:
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
<section id="welcome">
<h2>Welcome Content</h2>
<p class="block">Welcome back, <?=$_SESSION['name']?></p>
</section>
And this is all i see when welcome.php is loaded:
Welcome Content
Welcome back,
After looking at years old post on here a lot of people mentioned needing to have session_start(); at top of file, i tried this and it said "ignoring session start cause a session has already been started".
So i found this on another post where someone else having a similar issue(unfortunately there was no answer for me there[nor for that poster])
<?php
if (session_status() === PHP_SESSION_NONE || session_status() !== PHP_SESSION_ACTIVE )
session_start();
print_r($_SESSION);
if (!isset($_SESSION['name'])) {
die(json_encode(array(
"error",
"You must be logged in to view report data."
)));
}
?>
I put the above code at the very top of welcome.php and when i load welcome.php without ajax i see this:
Array ( [loggedin] => 1 [name] => -Phil (Just-Us) [id] => 1 [role] => Admin )
Welcome Content
Welcome back, -Phil (Just-Us)
But when i load welcome.php via ajax i only see this:
Welcome Content
Welcome back,
UPDATE: So i added the below code to my home.php file of which houses the body content div and said div houses all the dynamically loaded content. And doing this works fine, i see my session name being displayed just fine. So does replacing load.php with welcome.php in the ajax code. So something is going wrong when ajax loads the load.php file and then load.php echo's another php files contents(leaving behind needed php content).
<script>
$(document).ready(
function() {
setInterval(
function() {
$("#main-content").load('pages/welcome.php');
}
, 10000 // 1000ms = 1 second. Lowest i'd go to is 0.05s which is 50ms. (even though the lowest it can go is 4ms apparently. not advised tho)
);
$.ajaxSetup({ cache: false });
}
);
</script>
Why is it that when i use the below code it opens the php file in a new tab rather than loading it into the specified div?
// Create event listener for all link clicks
document.querySelectorAll('page-links').forEach(link => {
link.addEventListener('click', (e) => {
// Retrieve href and store in targetUrl variable
let targetUrl = e.target.href;
// Output value of targetUrl to console
// console.log('A link with target URL ' + targetUrl + 'was clicked');
$("#main-content").load(targetUr);
});
});

Javascript - How to get script to run with Ajax requested data

Battlefield Page
In the image above, there is a page that has a battlefield with 20 users on it. I have written JavaScript to capture the data and store it in a MySQL db. The problem comes into the picture when I need to hit next to go to the next page and gather that data.
It fetches the next 20 users with an Ajax call. Obviously when this happens, the script can't log the new information because the page never loads on an Ajax call which means the script doesn't execute. Is there a way to force a page load when the Ajax link is clicked?
Here's the code:
grabData();
var nav = document.getElementsByClassName('nav')[0].getElementsByTagName('td')[2].getElementsByTagName('a')[0];
nav.addEventListener("click", function(){
grabData();
});
function grabData(){
var rows = document.getElementsByClassName('table_lines battlefield')[0].rows;
var sendData = '';
for(i=1; i < rows.length -1 ; i++){
var getSid = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].getElementsByTagName('a')[0].href;
var statsID = getSid.substr(getSid.indexOf("=") + 1); //Grabs ID out of stats link
var name = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[2].textContent.replace(/\,/g,"");
var tff = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[3].textContent.replace(/\,/g,"");
var rank = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[6].textContent.replace(/\,/g,"");
var alliance = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[1].textContent.trim();
var gold = document.getElementsByClassName('table_lines battlefield')[0].getElementsByTagName('tr')[i].getElementsByTagName('td')[5].textContent.replace(/\,/g,"");
if(alliance == ''){
alliance = 'None';
}
if(gold == '??? Gold'){
gold = 0;
}else{
gold = gold.replace(/[^\/\d]/g,'');
}
sendData += statsID + "=" + name + "=" + tff + "=" + rank + "=" + alliance + "=" + gold + "#";
}
$.ajax({
// you can use post and get:
type: "POST",
// your url
url: "url",
// your arguments
data: {sendData : sendData},
// callback for a server message:
success: function( msg ){
//alert(msg);
},
// callback for a server error message or a ajax error
error: function( msg )
{
alert( "Data was not saved: " + msg );
}
});
}
So as stated, this grabs the info and sends to the php file on the backend. So when I hit next on the battlefield page, I need to be able to execute this script again.
UPDATE : Problem Solved. I was able to do this by drilling down in the DOM tree until I hit the "next" anchor tag. I simply added an event listener for whenever it was clicked and had it re execute the JavaScript.
Yes, you can force a page load thus:
window.location.reload(true);
However, what the point of AJAX is to not reload the page, so often you must write javascript code that duplicates the server-side code that builds your page initially.
However, if the page-load-code-under-discussion runs in javascript on page load, then you can turn it into a function and re-call that function in the AJAX success function.
Reference:
How can I refresh a page with jQuery?

How to pas querystring to another page using javascript or jquery?

I am trying to redirect from current i.e home page to another page with querystring using window.location.href but it redirects to current i.e. home
page again.
I dont know whats missing though code looks fine.
current URL: http://win-aslbkn4mm3v:10001/sitepages/Content%20Page/rch_home.aspx
Expecting URL: http://win-aslbkn4mm3v:10001/sitepages/Content%20Page/Doctors.aspx?qn=ddd&qs=ddd&qd=ddd
but Getting URL: //win-aslbkn4mm3v:10001/sitepages/Content%20Page/rch_home.aspx
function SearchDoctor()
{
debugger;
var Name = document.getElementById("SearchName").value;
var Speciality = document.getElementById("SearchSpeciality");
var spl = Speciality.options[Speciality.selectedIndex].text;
var Department = document.getElementById("SearchDepartment");
var dept = Department.options[Department.selectedIndex].text;
var mainUrl= '../../../Doctors.aspx?qn=' + Name + '&qs=' + Speciality + '&qd=' + Department;
window.location=mainurl;
}

is it possible to redirect the user to same page after login using client side technology

I have searched quite a lot regarding my problem and I couldn't find any relevant tutorial. Moreover, I am not even sure if it is possible using client side technology.
Problem statement: For e.g I have many pages in my web app and if a user switch from index page to page 1 and then page 2. Now the user decides to login to my web site. I want to redirect the user to page 2 once the login is successful.
Current outcome: Once the login is successful user always seems to get redirected to the index page.
Desired outcome: Once the login is successful the user should stay on page 2.
Is it possible using client side technology? In PHP we could use sessions and all. But I am confined on using client side technology to achieve that.
Here is my login function
function login(params) {
if(checkEmpty("loginEmail") && checkEmpty("password")) {
var emailField = $("#loginEmail").val(),
passwordField = $("#password").val(),
data = "login=" + emailField + "&password=" + passwordField;
for (var key in params) {
data += "&" + key + "=" + params[key];
}
// Hide errors as default
$("#loginErrorWrapper").hide();
// Try to launch the "normal" submit operation to make browser save email-field's value to cache
$('#loginSubmitHidden').click();
// Send data to server and refresh the page if everything is ok
$.when(loginPost(data)).done(function(map) {
if(!hasErrors(map)) {
var lang = map.language;
if (lang != "") {
changeLanguage(lang)
}
else {
lang = 'en';
}
redirect("/" + lang + "/");
} else {
if (map.errorCode == "155") {
$.fancybox({
href : '#termsAcceptancePopup',
title : '',
beforeLoad : function() {
$('#acceptTermsButton').attr('onclick','javascript:login({policyChecked:true});$.fancybox.close();');
},
helpers : {
overlay : { closeClick: false }
}
});
} else {
var errorString = getErrorMessage(map);
$("#loginErrorWrapper").show();
$("#loginErrorWrapper").html(errorString);
}
}
});
}
}
Ajax request
function loginPost(data) {
return $.ajax({
url: "/some-api/login",
type: "POST",
dataType: "json",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
async: true,
data:data
});
}
P.S -> I am not using PHP at all. I am working on a Java based web app.
So I have tried all the methods suggested in the comment section and all of them worked.
1) Using location.reload()
Once the user is logged in it just refresh the page.
2) Saving the last URL in a cookie
Calling the below function before calling redirect.
createCookie(value1, value2, value3);
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
3) Removing redirect("/" + lang + "/"); from my function since I am using ajax for login. However this method is not useful because once the user is logged in he/she will never know whether everything went fine or not unless he/she refresh the page manually or go to another page.
I am not certain which method is better (performance and loading time) - method 1 or method 2.

Not able to append data to Div and redirect page

I have a default page with list of items. When I click on those Items I need to dynamically append data to div in Page B and redirect the app to Page B.
I added this div in PageB
''
On Click event I am doing following action in .js file:
'$(document).on('click', '#selectConcept', function (node) {
var ncid = this.textContent.slice(6,25);
$.ajax({
dataType: "json",
url: "http://txv-trmindexer01:8080/CommonTerminologyLeopardSearch/rest/getConceptByNcid/" + ncid,
error: function () {
alert("ERROR");
},
success: function (data) {
window.location.href = 'getfacets.html';
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
} });
});'
I am able to redirect page, but nothing is appended to Div.
Can anyone help me out with this..
I'm not really sure, but I guess the code runs before the new page is loaded. So you could try to wrap the code in a function run at onload event time
window.location.href = 'getfacets.html';
window.onload = function() {
for (var result = 0; result < finalSearchResults.length; result++) {
if (finalSearchResults[result].ncid == ncid) {
$("#selectedConceptitem").empty();
var selectedconcept = "<p>" + "ncid: " + finalSearchResults[result].ncid + "," + "cid: " + finalSearchResults[result].cid + "</p>";
$(selectedconcept).appendTo("#selectedConceptitem");
}
}
}
The problem:
As soon as you set "window.location.href" property the page navigates to your page B and you loose your fetched data.
You have two solutions to the problem:
Use Single Page Application (SPA) application approach wherein you could create a new global scope for your fetched data, which can now be used by page B
Send the ncID as a querystring parameter to page B and and implement the service call and data appending logic on page B

Categories

Resources