I'm trying to pull photos from specific tag. Found an awesome tutorial and I've managed to pull photos from Instagram with pagination.
The problem I'm facing now is duplicate photos being displayed if it reaches to the end of the photos.
HTML Source
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.7.2.min.js' type='text/javascript' charset='utf-8'></script>
<script src='javascripts/application.js' type='text/javascript' charset='utf-8'></script>
<link rel='stylesheet' href='stylesheets/application.css' type='text/css' media='screen'>
<title>Photo Stream </title>
<meta name="description" content="Search for instagram images online.">
<meta name="author" content="Omar Sahyoun">
</head>
<body>
<!--<form id='search'>
<button class="button" type="submit" id="search-button" dir="ltr" tabindex="2">
<span class="button-content">Search</span>
</button>
<div class='search-wrap'>
<input class='search-tag' type='text' tabindex='1' value='cats' />
</div>
</form>-->
<h2 id="search">Photo Stream </h2>
<div id='photos-wrap'>
</div>
<div class='paginate'>
<a class='button' style='display:none;' data-max-tag-id='' href='#'>View More...</a>
</div>
</body>
</html>
Javascript File
// Add trim function support for IE7/IE8
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
// Instantiate an empty object.
var Instagram = {};
// Small object for holding important configuration data.
Instagram.Config = {
clientID: 'xxxx',
apiHost: 'https://api.instagram.com'
};
// Quick and dirty templating solution.
Instagram.Template = {};
Instagram.Template.Views = {
"photo": "<div class='photo'>" +
"<a href='{url}' target='_blank'><img class='main' src='{photo}' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' /></a>" +
"<span class='heart'><strong>{count}</strong></span><span class='comment'><strong>{count2}</strong></span>" +
"<span class='avatar'><iframe src='//www.facebook.com/plugins/like.php?href={url}&send=false&layout=button_count&width=40&show_faces=true&action=like&colorscheme=light&font&height=21&' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:80px; height:21px;' allowTransparency='true'></iframe></span>" +
"</div>"
};
Instagram.Template.generate = function(template, data){
var re, resource;
template = Instagram.Template.Views[template];
for(var attribute in data){
re = new RegExp("{" + attribute + "}","g");
template = template.replace(re, data[attribute]);
}
return template;
};
// ************************
// ** Main Application Code
// ************************
(function(){
function init(){
bindEventHandlers();
}
function toTemplate(photo){
photo = {
count: photo.likes.count,
count2: photo.comments.count,
avatar: photo.user.profile_picture,
photo: photo.images.low_resolution.url,
url: photo.link
};
return Instagram.Template.generate('photo', photo);
}
function toScreen(photos){
var photos_html = '';
$('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
.fadeIn();
$.each(photos.data, function(index, photo){
photos_html += toTemplate(photo);
});
$('div#photos-wrap').append(photos_html);
}
function generateResource(tag){
var config = Instagram.Config, url;
if(typeof tag === 'undefined'){
throw new Error("Resource requires a tag. Try searching for cats!");
} else {
// Make sure tag is a string, trim any trailing/leading whitespace and take only the first
// word, if there are multiple.
tag = String(tag).trim().split(" ")[0];
}
url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&count=10&client_id=" + config.clientID;
return function(max_id){
var next_page;
if(typeof max_id === 'string' && max_id.trim() !== '') {
next_page = url + "&max_id=" + max_id;
}
return next_page || url;
};
}
function paginate(max_id){
$.getJSON(generateUrl(tag), toScreen);
}
function search(tag){
resource = generateResource(tag);
$('.paginate a').hide();
$('#photos-wrap *').remove();
fetchPhotos();
}
function fetchPhotos(max_id){
$.getJSON(resource(max_id), toScreen);
}
function bindEventHandlers(){
$('body').on('click', '.paginate a.button', function(){
var tagID = $(this).attr('data-max-tag-id');
fetchPhotos(tagID);
return false;
});
// Bind an event handler to the `click` event on the form's button
$('form#search button').click(function(){
// Extract the value of the search input text field.
var tag = $('input.search-tag').val();
// Invoke `search`, passing `tag`.
search(tag);
// Stop event propagation.
return false;
});
}
function showPhoto(p){
$(p).fadeIn();
}
Instagram.App = {
search: search,
showPhoto: showPhoto,
init: init
};
})();
$(function(){
Instagram.App.init();
// Start with a search on cats; we all love cats.
Instagram.App.search('hwplus');
});
Please help me to find a way to disable the 'View More' button if photos have reached the end.
And is there a way to add cache in JSON object and fetch variables from Javascript?
Thanks and appreciate.
Once you reach the end of the photos, the next_max_tag_id won't exist. You'll need to check if next_max_tag_id exists and if not, disable the button. You'll implement your new code on this line, maybe make a variable for photos.pagination.next_max_id and when the user clicks the button, check if the variable is defined.
Untested code:
var next_max = photos.pagination.next_max_id;
if (next_max == 'undefined') {
var next_max = 'end';
$('.paginate a').addClass('disabled');
}
//define .disabled in your CSS
$('.paginate a').attr('data-max-tag-id', next_max).fadeIn();
Related
So, I have a HTML form and I need to send it's value as a parameter to a php function, but I also need a different value, that's not even inside the HTML.
For example:
<form action="methods.php" method="register">
<input type="text" placeholder="EventID">
<input type="submit" value="Register">
</form>
This form would get the event id and send it as a parameter to register the user into the event. But I need to send the user as a parameter also (function register($user, $eventid)) and I have no idea on how to do so.
I did find some similar things around here, but they were related to POST and GET and I'm not sure they work for me and I could not understand how to use in them in my case, so if anyone could help me out, pleaaaaaase, i'd be really thankful
Its very simple you just need to take care of few things.
1: every input field should have a name.
2: set form method either GET(to send values visible in the url) or POST(to send data without showing in the url)
3: on methods.php receive form data if send via GET then $_GET['input_field_name'] or via POST then $_POST['input_field_name']
Look for the explanation in comments below:
//<![CDATA[
// external.js
var post, doc, bod, htm, C, E, T; // for use on other loads
addEventListener('load', function(){ // load
// used in post function below to create String from Object
function phpEncode(obj){
var r = [];
if(obj instanceof Array){
for(var i=0,l=obj.length; i<l; i++){
r.push(phpEncode(obj[i]));
}
return '%5B'+r.join(',')+'%5D';
}
else if(typeof obj === 'object' && obj){
for(var i in obj){
if(obj.hasOwnProperty(i)){
var v = obj[i], s;
if(typeof v === 'object' && v){
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":')+phpEncode(v);
}
else{
v = typeof v === 'string' ? '"'+v.replace('"', '\"')+'"' : v;
s = encodeURIComponent('"'+i.replace('"', '\\"')+'":'+v);
}
r.push(s);
}
}
return '%7B'+r.join(',')+'%7D';
}
else{
r = typeof obj === 'string' ? '"'+obj.replace('"', '\\"')+'"' : obj;
return ''+r;
}
}
// used in post function below to evaluate (make into code) JSON String that comes back from PHP
function phpAccept(url){
return eval('('+decodeURIComponent(url)+')');
}
// here is an example of a post AJAX function
post = function(send, where, success, context){
var x = new XMLHttpRequest;
var c = context || this;
x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200){
if(success)success.call(c, phpAccept(x.responseText));
}
}
if(typeof send === 'object' && send && !(send instanceof Array)){
var r = [];
for(var p in send){
r.push(encodeURIComponent(p)+'='+phpEncode(send[p]));
}
x.send(r.join('&'));
}
else{
throw new Error('send must be an Object');
}
return x;
}
// yes, you can do this - just remember that non-primitive values are the actual Object through assingment
doc = document; bod = doc.body; htm = doc.documentElement;
// simple way to create an Element by tag
C = function(tag){
return doc.createElement(tag);
}
// simple way to document.getElementById()
E = function(id){
return doc.getElementById(id);
}
T = function(tag){
return doc.getElementsByTagName(tag);
}
var form = E('form'), sub = E('sub'), i1 = E('i1'), i2 = E('i2');
// prevent old school submission
form.addEventListener('submit', function(ev){
ev.preventDefault(); // prevents submission
});
// just for testing remove below
var tS = E('test_out').style;
// remove above
// ajax submisson
sub.addEventListener('click', function(){
/* note that if the Elements are not removed from or added
to the DOM you don't need to get them again Element.value
will probably be different so you'll want to get them
on every click
*/
post({phpProp1:i1.value, phpProp2:i2.value}, 'yourPHPajaxResponsePage.php', function(data){
/* before data comes back yourPHPajaxResponsePage.php may look like this:
<?php
session_start(); // super common - read up on it - not needed here - but won't hurt
if(isset($_POST['phpProp1'], $_POST['phpProp2'])){
// usually you affect MySQL using PHP at this point
// we'll just send them back in this lame example
$res = array('jsProp1' => $_POST['phpProp1'], 'jsProp2' => $_POST['phpProp2']);
// makes results come back as JSON
echo json_encode($res);
}
?>
*/
if(data){ // may want more conditions
E('out').innerHTML = data.jsProp1+'<br />'+data.jsProp2;
}
}, this);
// just for testing - remove below
tS.display = 'block';
E('temp_res').innerHTML = i1.value+'<br />'+i2.value;
// remove above
});
// testing only remove below
var ins = doc.querySelectorAll('input[type=text]');
for(var i=0,l=ins.length; i<l; i++){
ins[i].addEventListener('focus', function(){
tS.display = 'none';
});
}
// remove above
form.addEventListener('keydown', function(ev){
// if user hits enter
if(ev.keyCode === 13)sub.click();
});
}); // end load
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
.main{
width:980px; margin:0 auto;
}
#form{
width:266px; color:#fff; background:green; padding:10px;
}
#form>div>label{
display:block; float:left; width:57px;
}
#form>div>input{
width:203px;
}
#form>div{
margin-bottom:10px;
}
#form>#sub{
display:block; margin:0 auto;
}
/* remove below - testing only */
#test_out{
display:none;
}
#test_out>div:first-child{
color:red;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>AJAX Example</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='form'>
<div><label for='i1'>Input 1</label><input id='i1' name='i1' type='text' value='' /></div>
<div><label for='i2'>Input 2</label><input id='i2' name='i2' type='text' value='' /></div>
<input id='sub' type='button' value='submit' />
</form>
<div id='out'></div>
<!-- for testing remove below -->
<div id='test_out'><div>Must have PHPServer code in JavaScript Comments to get real results</div><div id='temp_res'></div></div>
<!-- remove above -->
</div>
</body>
</html>
What do you think?
you can use hidden field or you can use session or cookie for user
<form action="methods.php" method="post">
<input type="hidden" name="txtuser" value="abc">
<input type="text" placeholder="EventID">
<input type="submit" value="Register">
</form>
if you use cookie or session then there is not need to pass it as parameter its a global variable so you can access its value at any page directly, you just need to store value to it and access it any where in your project.
I am writing a program that gets information from forms using AJAX, and I was wondering if there was a way to make a button that clears the form and sort of resets the form. Right now if you press a button, the text won't disappear, but Im hoping to make a home button that would make the text disappear. I am just going to post my .html file because I think thats all we need. Let me know if there is more code you need. I tried making a reset button but it didn't seem to work.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + "period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<button type="reset" value="Reset"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
Your reset-button should already do this, if its within the <form></form> or has the "form"-attribute, see here
You can either use the default reset button, if it is in between the form tag or you can use jquery to do this for you.
You just have to add an event on the click event of the home button and u can achieve what you want.
this is a reference which u can take
$(".reset").click(function() {
$(this).closest('form').find("input[type=text], input[type="password"], textarea").val("");
});
Add all other fields which u want to clear on click of the home button
I want to toggle divs by clicking on links. but things are not going well for me when I click on a link it shows a new div but don hide the previous one
JavaScript Code
<script type="text/javascript">
function toggle(id){
var el = document.getElementById(id);
if(el != null && el.style["display"]== 'none'){
el.style["display"] = "block";
}
}
</script>
My divs code
<?php foreach($titles_data as $title){ ?>
<div style="display:none" id="content_<?php echo $title['idtitles'] ?>">
<div id="left-ad"></div>
</div>
<?php } ?>
My links code
<?php foreach($titles_data as $title){ ?>
<li class="flag_<?php echo strtoupper($title['language']) ?>">
<a id="title_<?php echo $title['idtitles'] ?>" href="" title="<?php echo $title['title'] ?>" onclick="toggle('content_<?php echo $title['idtitles'] ?>')">
</a>
</li>
<?php } ?>
How can it be done so that when i click on link its respective iv becomes visible and the previous one hides?
Thanks
Using native JS:
function toggle(id){
var el = document.getElementById(id);
el.style.display = el.style.display == "none" ? "block" : "none";
}
toggle("myId");
Using jQuery:
function toggle(selector) {
$(selector).toggle();
}
toggle("#myId");
To toggle the display, you dont need to do that much
$("#elementid").toggle();
In reference to your question
$('a').click(function() { // however this is select all anchors, better use class
// selector like $(".mylinkclass")
var id= $(this).attr('id'); //get the id
var ids = id.splite("_"); //split the id on "_", to extract the idtitles
$("#content_"+ids[0]).toggle(); // use that to toggle
});
Assuming that there is always only one div that is displayed, you can check for it:
Alter your logic, to declare a global variable to hold the value of the currently visible div. And then update that variable whenever a link is clicked, to hold the id of the currently visible div. So, using your exisitng code, you can do this :
using core javascript:
var visibleDiv;
function toggle(id){
// hide the previous div using visibleDiv
if(document.getElementById(visibleDiv)!= null) document.getElementById(visibleDiv).style["display"] = "none";
var el = document.getElementById(id);
if ( el.style["display"] == "" || el.style["display"] == 'none' ){
el.style["display"] = 'block';
}
visibleDiv = id; // update the current visible div name
}
using jquery like this :
var visibleDiv;
$("[id^=content_]").each(function() {
if($(this).is(':visible')){
visibleDiv = $(this).attr('id');
}
});
Check my new answer. I just created the sample html page, with 3 divs. Initially all are shown. When you click on one of them, it is hidden. When you click on some other div. The old one is made visible again and the current one is hidden. Modify the logic as per your requirements.
<html>
<head>
<title>asdsa</title>
<script type="text/javascript">
var visibleDiv;
function toggled(id){
//$('#div_2').html($('#div_1').html());
if(document.getElementById(visibleDiv) != null){ document.getElementById(visibleDiv).style["display"] = "block";}
var el = document.getElementById(id);
document.getElementById(id).style["display"] = "none";
visibleDiv = id;
}
</script>
</head>
<body>
<div id="div_1" onclick="toggled('div_1')">div1</div>
<div id="div_2" onclick="toggled('div_2')">div2</div>
<div id="div_3" onclick="toggled('div_3')">div3</div>
<hr/>
</body>
</html>
Thanks.
I using PHP/Javascript - Widget of alexmarandon from link http://alexmarandon.com/articles/web_widget_jquery/
And in project of me is:
script.js
html.php
demo.html
In script i using code:
(function() {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.7.1') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
} else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict(true);
// Call our main function
main();
}
/******** Our main function ********/
function main() {
jQuery(document).ready(function($) {
/******* Load CSS *******/
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "style.css"
});
css_link.appendTo('head');
/******* Load HTML *******/
var jsonp_url = "data.php?callback=?";
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html(data);
});
$('.submit').click(function(){
alert('test');
});
});
}
})(); // We call our anonymous function immediately
Then i call data in data.php
$str = '<div class="widget_advance">';
$str .= '<form method="post" id="form_widget_advance">';
$str .= '<input type="submit" value="Tìm" class="submit" />';
$str .= '</form>';
$str .= '</div>';
echo $_GET['callback'] . '(' . json_encode($str) . ');';
finally, in demo.html is result:
<script src="script.js" type="text/javascript"></script>
<div id="example-widget-container"></div>
=> When I click on button submit is result not show alert('test'); How to fit it ?
Put this inside as such:
$.getJSON(jsonp_url, function(data) {
$('#example-widget-container').html(data);
$('.submit').click(function(){
alert('test');
});
});
You see, it has to be inside the callback. You can't bind to the submit button if it's not in the DOM yet. You could also do something along the lines of: $("#someForm").submit(function() { ... });
Following is the code:-
<script type="text/javascript">
var timer = 150;
var currentWindow;
$(document).ready(function()
{
$("#creditme").button({
icons: { primary: "ui-icon-check" }
}).hide();
$("#viewad").button({
icons: { primary: "ui-icon-play" }
}).hide();
$("#progressbar").progressbar({value: 0}).hide();
var time;
var id;
var title;
var url;
$('.googlep-advertisement').bind('click', function()
{
id = $(this).attr('id');
title = $(this).text();
url = $('#yturl-'+id).text();
timer = $('#ytime-'+id).text();
$("#dialog-message").dialog({
modal: true,
width: 700,
title: title,
resizable: false,
draggable: false,
beforeClose: function() { clearAd(); }
});
if (!$("#progressbar").is(":visible") && !$("#creditme").is(":visible"))
{
$("#viewad").show();
}
});
$("#viewad").bind('click',function() {
$.get("googlep_credit.php" + '?start=' + id);
$("#viewad").hide();
$("#progressbar").progressbar('value', 0).show();
currentWindow = window.open(url, 'videoad', 'height=480,width=640', false);
window.blur();
window.focus();
progresscount(timer);
});
$("#creditme").click(function() {
$.get("googlep_credit.php" + '?id=' + id);
$("#creditme").hide();
$("#dialog-message").dialog('close');
$("#"+id).parent().parent('tr').fadeOut('slow');
});
function progresscount(time)
{
if(time == 0)
{
if(isWindowClosed() == true)
{
alert('You closed the popup before timer reached zero or you are using popup-blocking software.');
$("#dialog-message").dialog('close');
}
else
{
$("#creditme").html('<g:plusone callback="plusone_vote" href="'+url'"></g:plusone>');
$("#creditme").show();
}
$("#progressbar").hide();
}
else
{
time--;
$("#progressbar").progressbar('value', parseInt((timer - time) * 100 / timer));
setTimeout(function() { progresscount(time) }, 100);
}
}
});
function isWindowClosed()
{
if (!currentWindow || typeof currentWindow == 'undefined' || currentWindow && currentWindow.closed)
{
return true;
}
else
{
return false;
}
}
function clearAd()
{
}
</script>
<style>
.dialog-message {
}
</style>
<div id="dialog-message" class="dialog-message" title="View Video" style="display:none">
<p>
<center>
<button id="viewad" style="ui-helper-hidden">Click here to view the video</button>
<div id="progressbar"></div>
<button id="creditme" style="ui-helper-hidden">Test</button>
</center>
</p>
</div>
Nothing wrong with the code.
The problem is:-
http://dl.dropbox.com/u/14384295/70.jpeg
When checked with google chrome inspect element,
The code appears as
http://dl.dropbox.com/u/14384295/71.jpeg
Correctly working will appear as > http://dl.dropbox.com/u/14384295/72.jpeg
It seems that the code is not being converted by the google js which is in the portion. I am sorry if i have been confusing.
I may probably be doing the addition of 'url' var incorrectly
I'm pretty sure your problem lies in this line:
$("#creditme").html('<g:plusone callback="plusone_vote"></g:plusone>');
You are dynamically adding the <g:plusone> element after the Google +1 script has been run, so nothing happens.
To solve it, simply put the +1 markup in the html from the beginning so the +1 script can find it and render it, and only call $("#creditme").show(); when you need to show it.
<button id="creditme" style="ui-helper-hidden">
<g:plusone callback="plusone_vote"></g:plusone>
</button>
If you want to dynamically change the URL after page load, check out the examples from the Google documentation. It will allow you to load the button explicitly.