How to ensure Else statement remains on the same html page? - javascript

Using - HTML, JavaScript, JQueryMobile, Phonegap. (One page architecture, all pages are on one html page)
I have an if/else statement for user login, so the if statement directs the user to the homepage (if user/pass found in the database) which works perfectly fine, however I currently have a notification for the else statement but the issue is that after the notification it redirects the user back to the index page instead of remaining on the same page and allowing the user to try again.
What can I use to prevent the page being reloaded to another page for the else statement? I have already tried event.preventDefault(); and event.stopPropagation(); but I just get an error.
See below my current code -
function loginUser()
{
db = window.openDatabase("SoccerEarth", "2.0", "SoccerEarthDB", 2*1024*1024);
db.transaction(loginDB, errorCB);
}
function loginDB(tx)
{
var Username = document.getElementById("username").value;
var Password = document.getElementById("password").value;
tx.executeSql("SELECT * FROM SoccerEarth WHERE UserName='" + Username + "' AND Password= '" + Password + "'", [], renderList);
}
function renderList(tx,results)
{
if (results.rows.length > 0) {
navigator.notification.alert("Login Success!");
window.location = "#page4";
}
else
{
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
}

function renderList(event, tx, results) {
if (results.rows.length > 0) {
window.location = "#page4";
} else {
event.preventDefault();
event.stopPropagation();
/* navigator.notification.alert("Incorrect! Please try again. "); */
}
You need to pass the event in as a arguement. Then prevent the default behaviour on it by using event.preventDefault();
But I'd like to point out that you aren't using an event here, this is just checking to see if something is on the page.

Related

Get access token of instagram API

I want to get the access token in order to diaply the images of an account. So I display a pop up where the user can connect. The pop up works but it redirects to instagram site, with the user connected instead of send me the code. The link to the connection is something like :
https://www.instagram.com/accounts/login/?force_classic_login=&next=/oauth/authorize/%3Fclient_id=aaaaaaaa&redirect_uri=url&response_type=token
I log in and then, it redirects me to :
https://www.instagram.com/oauth/authorize/?client_id=aaaaaaa&redirect_uri=url&response_type=token
I don't understand how I can get the code. And I also used the exact same code as : https://github.com/radykal/instagram-popup-login
Can someone help me please ?
EDIT
var loc = window.location.host+window.location.pathname;
var accessToken = null; //the access token is required to make any endpoint calls, http://instagram.com/developer/endpoints/
var authenticateInstagram = function(instagramClientId, instagramRedirectUri, callback) {
//the pop-up window size, change if you want
var popupWidth = 700,
popupHeight = 500,
popupLeft = (window.screen.width - popupWidth) / 2,
popupTop = (window.screen.height - popupHeight) / 2;
//the url needs to point to instagram_auth.php
var popup = window.open('instagram_auth.php', '', 'width='+popupWidth+',height='+popupHeight+',left='+popupLeft+',top='+popupTop+'');
popup.onload = function() {
//open authorize url in pop-up
if(window.location.hash.length == 0) {
popup.open('https://instagram.com/oauth/authorize/?client_id='+instagramClientId+'&redirect_uri='+instagramRedirectUri+'&response_type=token', '_self');
}
//an interval runs to get the access token from the pop-up
var interval = setInterval(function() {
try {
console.log(window.location);
//check if hash exists
if(popup.location.hash.length) {
//hash found, that includes the access token
clearInterval(interval);
accessToken = popup.location.hash.slice(14); //slice #access_token= from string
popup.close();
if(callback != undefined && typeof callback == 'function') callback();
}
}
catch(evt) {
//permission denied
console.log("error");
}
}, 100);
}
};
function login_callback() {
alert("You are successfully logged in! Access Token: "+accessToken);
}
function login() {
authenticateInstagram(
'16edb5c3bc05437594d69178f2aa646a', //instagram client ID
'localhost/facebook', //instagram redirect URI
login_callback //optional - a callback function
);
return false;
}
The code is ok, I think it is a problem with your app settings: Login to Instagram Developer, go to "Manage Client" and the "security" tab an disable "Implicit OAuth".

ajax image viewer , back button and history - missing html and css

I am playing with jquery and js, trying to build an ajax overlay image viewer for a PHP website. With this code included at the bottom of the 'gallery page', the viewer opens and i can navigate with next and previous links inside the viewer. But the back button and the history is hard to understand. The browser often shows only the response of the ajax call, without the underlying page and css files, after some clicks back.
Perhaps somebody knows what is generally happening in such a case? I would like to understand why back sometimes results in a broken page, i.e. only the ajax response.
<script type="text/javascript">
$(document).ready(function() {
function loadOverlay(href) {
$.ajax({
url: href,
})
.done(function( data ) {
var theoverlay = $('#flvr_overlay');
theoverlay.html( data );
var zoompic = $('#zoompic');
zoompic.load(function() {
var nih = zoompic.prop('naturalHeight');
var photobox = $('#photobox');
if($(window).width() >= 750){
photobox.css('height',nih);
}
theoverlay.show();
$('body').css('overflow-y','hidden');
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 750) {
photobox.css('height','auto');
zoompic.removeClass('translatecenter');
}else{
photobox.css('height',nih);
zoompic.addClass('translatecenter');
}
});
});
});
return false;
}
var inithref = window.location.href;
$(window).on('popstate', function (e) {
if (e.originalEvent.state !== null) {
//load next/previous
loadOverlay(location.href);
} else {
//close overlay
$('#flvr_overlay').hide().empty();
$('body').css('overflow-y','scroll');
history.replaceState(null, inithref, inithref);
}
});
$(document).on('click', '.overlay', function () {
var href = $(this).attr('href');
history.pushState({}, href, href);
loadOverlay(href);
return false;
});
});
</script>
edit
clicking forward works:
/photos (normal page)
/photos/123 (overlay with '/photos' below)
/locations/x (normal page)
/photos/567 (overlay with '/locations/x' below)
clicking back gives me the broken view at point 2.
Do you need to prevent the default behaviour in your popstate to prevent the browser from actually navigating back to the previous page?
you have to manage it by own code.
You have a few options.
Use localstorage to remember the last query
Use cookies (but don't)
Use the hash as you tried with document.location.hash = "last search" to update the url. You would look at the hash again and if it is set then do another ajax to populate the data. If you had done localstorage then you could just cache the last ajax request.
I would go with the localstorage and the hash solution because that's what some websites do. You can also copy and paste a URL and it will just load the same query. This is pretty nice and I would say very accessible
Changing to document.location.hash = "latest search" didn't change anything.t.
This goes into the rest of the jQuery code:
// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
if ('myTable' in localStorage && window.location.hash) {
$("#myTable").html(localStorage.getItem('myTable'));
}
}
// Save the search result table when leaving the page.
$(window).unload(function () {
if (('localStorage' in window) && window['localStorage'] !== null) {
var form = $("#myTable").html();
localStorage.setItem('myTable', form);
}
});
Another solution is that use INPUT fields to preserved while using back button. So, I do like that :
My page contains an input hidden like that :
Once ajax content is dynamicaly loaded, I backup content into my hidden field before displaying it:
function loadAlaxContent()
{
var xmlRequest = $.ajax({
//prepare ajax request
// ...
}).done( function(htmlData) {
// save content
$('#bfCache').val( $('#bfCache').val() + htmlData);
// display it
displayAjaxContent(htmlData);
});
}
And last thing to do is to test the hidden field value at page loading. If it contains something, that because the back button has been used, so, we just have to display it.
jQuery(document).ready(function($) {
htmlData = $('#bfCache').val();
if(htmlData)
displayAjaxContent( htmlData );
});

Leaving a page - message appears twice

I've added this Javascript to my website which detects when the user navigates away from the page, but I only want a warning to appear if the navigator is offline AND one of my elements contains the word "unsaved":
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine===false) {
// See if any fields need saving...
for (i = 1; i <= 500; i++) {
try {
ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved")!=-1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
}
catch(err) { }
// If got this far, nothing needs saving anyway...
}
}
return undefined;
};
window.onbeforeunload = window.thisPage.closeEditorWarning;
The code works fine except; if the message pops up the first time and I choose "Stay on this page", then try to navigate away again and the second time click "Leave this page" - rather than navigating away it displays the message again but I can't work out why.
Try returning true from your catch, so the unload will execute. You can also remove the return undefined; from the end.
This works for me, is this what you're after?
This works for me in Firefox.
Fiddle: http://jsfiddle.net/518myq0j/3/ (clicking 'Run' triggers the onbeforeunload)
Updated JavaScript code:
window.thisPage = window.thisPage || {};
window.thisPage.closeEditorWarning = function (event) {
if (navigator.onLine === false) {
// See if any fields need saving...
for (i = 1; i <= 5; i++) {
try {
var ToSave = document.getElementById("Q" + i).innerHTML;
if (ToSave.indexOf("unsaved") != -1) {
return "You are currently offline and some of your responses are not yet saved.\r\n\r\nIf you want to save the changes you've made, choose to 'Stay on this Page' and then reconnect to the internet and any unsaved responses will save automatically.";
}
} catch (err) {
return true;
}
}
}
};
window.onbeforeunload = window.thisPage.closeEditorWarning;

Display warning alert and close session when the browser is closed

The web page is displayed upon redirection from another website and the URL changes during this process to point to a different port number.
So, I would like the JavaScript to detect if the URL is correct.
If the user closes the browser/tab, display an Alert Box with warning message.
Run PHP script to close the user Session
My code is:
if (window.location.href === "http://abc123.net.au:2048 ") {
$(function () {
try {
opera.setOverrideHistoryNavigationMode('compatible');
history.navigationMode = 'compatible';
}
catch (e) {
}
function OnBeforeUnload() {
$(window).onbeforeunload;
// Post to script that will log the user out
xmlhttp.open("POST", "../logscript.php", true);
xmlhttp.send();
}
function ReturnMessage() {
return "Wait, by closing this session I will end your session. You will be required to log in again t access the site.";
}
function UnBindWindow()
{
$(window).unbind('beforeunload', ReturnMessage);
}
$(window).bind('beforeunload', ReturnMessage);
});
}
else {
document.write('<div>code is not working</div>')
}
This is the solution to your second work order:
window.onbeforeunload = bunload;
function bunload() {
dontleave = "Are you sure you want to leave?";
return dontleave;
}

HTML OnBeforeUnload function not working on browser close

In the body element I have 'onBeforeUnload = "leaveChat()";' with the purpose of eliminating the user ID from the database when he leaves the page (function code below). The function does its job when the user refreshes the page and when he goes to another URL. The problem is when the user closes the tab/browser directly, because his userID isn't deleted from the databases.
What do I have to add/remove from my code, so my script can eliminate the userID everytime, even when the users are closing the browser?
function leaveChat()
{
playTitleFlag = false;
xmlHttp3 = GetXmlHttpObject();
if (xmlHttp3 == null)
{
alert("Browser does not support HTTP Request");
return;
}
var url = "leaveChat.php?userId=" + userId;
xmlHttp3.open("GET", url, true);
xmlHttp3.onreadystatechange = stateChanged3;
xmlHttp3.send(null);
}
function stateChanged3()
{
}

Categories

Resources