I have created a function to get the IP Address of the user. Then I tried to give separate AD to the user. So I use if condition and try to use the value of the function (getIP) to execute the if condition. But I am not success. The main problem is that I couldn't able to use the ip variable out side of the function. Can anybody see to help me.
<script type="application/javascript">
function getIP(json) {
ip=json.ip; //Here I got the user IP Address
}
getIP(json);
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
if( ip==KivaHan ){
document.write("Kiva Han IP Address: " + ip);
}else{
document.write("Office IP Address: " + ip);
}
</script>
<script type="application/javascript" src="https://api.ipify.org?format=jsonp&callback=getIP"></script>
Change it like this.
function getIP(json) {
return json.ip;
}
var ip = getIP(json);
If your getIP function is synchronous, return the IP address from it:
function getIP() {
var ip; // Don't forget to declare this
// ...get the IP address into `ip`
return ip;
}
usage
var ip = getIP();
if (ip) {
// Your code uses `ip` here
} else {
// Failed to get it, handle that here
}
If your getIP function is asynchronous, you have two options:
Have it accept a callback, and call the callback with the IP:
function getIP(callback) {
var ip; // Don't forget to declare this
// ...get the IP address into `ip`, maybe have it set to null on error
callback(ip);
}
usage:
getIP(function(ip) {
if (ip) {
// Your code uses `ip` here
} else {
// Failed to get it, handle that here
}
});
Or use a Promise (ES2015, but there are libs that polyfill it well enough on JavaScript engines that don't do it natively):
function getIP(callback) {
var ip; // Don't forget to declare this
return new Promise(function(resolve, reject) {
// ...get the IP address into `ip`
if (/* we got the IP */) {
resolve(ip);
} else {
// it failed:
reject();
}
});
}
usage:
getIP()
.then(function(ip) {
// Your code uses `ip` here; perhaps ip == null means failure
})
.catch(function() {
// Failed to get it, handle that here
});
Only place where javascript creates a new scope is function. Whenever you see function keyword, its safe to assume that a new scope will be created. The problem you are facing here is you are defining ip inside a function and trying to access it outside which is logically not possible. However, you can make a global variable and can access it anywhere in your program. But downside of it is, it will clutter your global namespace and if you are unlucky you may face issues that will be weird and hard to debug.
You can make use of IIFE (Immediately Invoked function expression) which is one of the most used design pattern in javascript.
(function(){
var ip = ""; //Define ip variable here.
function getIP(json) {
ip=json.ip; //Here I got the user IP Address
}
getIP(json);
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
if( ip==KivaHan ){
document.write("Kiva Han IP Address: " + ip);
}
else{
document.write("Office IP Address: " + ip);
}
})();
Hope this be of some help.
Happy Learning :)
I have tried with most of the Solution but not get real output which I want. Perhaps there is problem withe the function getIP(json) and the site from where I get the function to get user IP address. I think the value of this can't run out side of the function. So I used another site to get the user IP.
Now I give the alternative solution of my demand.
In this topic I want the IP Address of an user which I get in that function. But I could not trace out this from the function which I couldn't use more time in this page.
So I use the solution given below to fill my demand..
<head>
<script type="text/javascript" src="https://l2.io/ip.js?var=userip"> </script><!-- To get IP Address of the user -->
<script type="text/javascript"><!-- Here variables are decleared.. -->
var userip;
var KivaHan="221.120.101.58"
var Office="221.120.99.186"
</script>
</head>
<!-- Javascript for tracking and comparing the user IP-->
<!-- Below code is for implementation-->
<div class="main-bottom">
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
<div class="ad">
<script type="text/javascript">
if (userip==KivaHan){
document.write("Welcome");
}
else
{
document.write("Coming Soon");
}
</script>
</div>
</div>
Related
I use a js to display some content on my app (I use Dreamweaver and PhoneGap). When i preview the html separately works, but when i load the html from other page dont.
I receive this msg on the Firefox Security: ReferenceError: requestCrossDomain is not defined
This is my HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Mobile Web App</title>
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/cross-domain-request.js"></script>
</head>
<body>
<div id="container">
<p id="sitename"> http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0
</p>
function codeAddress(){
var elem = document.getElementById("sitename");
elem.value = "http://catedralaltapatagonia.com/invierno/partediario.php? default_tab=0";
var path =$('#sitename').val();
requestCrossDomain(path, function(results){
$('#container').html(results);
});
return false;
};
</script>
</body>
</html>
And my cross-domain-request.js:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(data){
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
});
}
Some clue to resolve it?
You appear to have an error in your external JS file, and it's not running. The final else statement is not correct. Try this:
/ JavaScript Document
// Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + 'http://catedralaltapatagonia.com/invierno/partediario.php?default_tab=0' + '"'+' AND xpath="//*[#id=\'meteo_recuadro\']"') + '&format=xml&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, function(data){
// If we have something to work with...
if ( data.results[0] ) {
// Strip out all script tags, for security reasons.
// BE VERY CAREFUL. This helps, but we should do more.
data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else {
throw new Error('Nothing returned from getJSON.');
}
});
}
I add the line
<script src="js/cross-domain-request.js"></script>
and the js is loaded
I'm attempting a slight variation of the Google+ web sign-in server side flow as described on the Google Developer's website.
I have a staff login page (staff_login.php) which uses javascript via Google+ (plusone.js).
If the user is already signed in to Google then the authorization code from Google is stored to a session variable.
If the user is not signed in then a 'Staff Login' button is displayed. If the user clicks the button then Google authorization takes place and, if successful, then the authorization code from Google is stored to a session variable.
In both cases, after the session variable has been stored, the user is redirected to another web page (google_login.php).
Most of the time the login process works as expected, but sometimes google_login.php generates an error message: Google_Auth_Exception' with message 'Error fetching OAuth2 access token, message: 'invalid_grant'.
I'm fairly sure the problem lies in the signInCallback function. How do I make it bulletproof?
Here's the (cut-down) code:
staff_login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="google-signin-clientid"
content="CLIENT-ID.apps.googleusercontent.com">
<meta name="google-signin-scope" content="email">
<meta name="google-signin-cookiepolicy" content="single_host_origin">
<meta name="google-signin-callback" content="signInCallback">
<title>Login</title>
</head>
<body>
<button id="xyzStaffSignIn">Staff Sign In</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"
type="text/javascript"></script>
<script type = "text/javascript" >
jQuery(document).ready(function ($) {
console.log('Google (plusone.js) will invoke signInCallback');
window.___gcfg = {
lang: 'en-GB',
parsetags: 'onload'
};
var po = document.createElement('script');
po.type = 'text/javascript';
po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
});
function signInCallback(authResult) {
if (authResult) {
if (authResult['error'] == undefined) {
if (authResult['code']) {
setSessionValue('GoogleAuthorisationCode',
authResult['code'], callGoogleLogin);
}
} else if (authResult['error']) {
// There was an error.
// Possible error codes:
// "access_denied" - User denied access to your app
// "immediate_failed" - Could not automatically log in the user
console.log('There was an error: ' + authResult['error']);
if (!authResult['status']['signed_in']) {
console.log('gapi.signin.render will invoke signInCallback');
gapi.signin.render('xyzStaffSignIn');
}
} else {
console.log('Empty authResult'); // Something went wrong
}
}
}
function setSessionValue(key, value, callback) {
$.post(
'session.php',
{
xyzAction: 'set',
xyzKey: key,
xyzValue: value
},
function (result) {
// Handle or verify the server response if necessary.
if (result['status'] == undefined) {
alert('xyz status problem. Please email our IT department!');
} else {
switch (result['status']) {
case 'Success':
callback();
break;
default:
alert('xyz unexpected status problem.
Please email our IT department!');
console.log(result['status']);
}
}
}
)
}
function callGoogleLogin() {
gapi.client.load('plus', 'v1', loadProfile);
}
/**
* Uses the JavaScript API to request the user's profile, which includes
* their basic information. When the plus.profile.emails.read scope is
* requested, the response will also include the user's primary email address
* and any other email addresses that the user made public.
*/
function loadProfile() {
var request = gapi.client.plus.people.get({'userId': 'me'});
request.execute(loadProfileCallback);
}
/**
* Callback for the asynchronous request to the people.get method. The profile
* and email are set to global variables. Triggers the user's basic profile
* to display when called.
*/
function loadProfileCallback(profile) {
var emailAddress;
// Filter the emails object to find the user's primary account, which might
// not always be the first in the array. The filter() method supports IE9+.
emailAddress = profile['emails'].filter(function (v) {
return v.type === 'account'; // Filter out the primary email
})[0].value; // get the email from the filtered results, should always be defined.
var domain = emailAddress.replace(/.*#/, "");
if ("xyz.com" == domain) {
window.location.href = "google_login.php?xyzEmailAddress=" + emailAddress;
} else {
alert(emailAddress + ' is not a recognized xyz staff member email address.');
}
}
</script>
</body>
</html>
google_login.php
<?php
// This code is called from the javascript on the login screen only
// AFTER Google authorization has succeeded
// Google_Client is as defined at
// https://github.com/google/google-api-php-client/blob/master/src/Google/Client.php
$googleClient = new Google_Client ();
$googleClient->setRedirectUri('postmessage');
$googleClient->authenticate($_SESSION['GoogleAuthorizationCode']);
Need to add/enable APIs from the left hand side panel here https://console.developers.google.com.
APIs which I have added are "google+ API" and "gmail API". I tried and it worked for me.
I am making a mobile web app using jquery mobile and jquery.
Now I have it so far that when I check my checkbox it saves my variables into the local storage from your browser. But it won't put these variables back into my input fields.
Here is my script. The function validate() saves the variables into local storage.
$(document).ready(function () {
if (localStorage["mail"]) {
$('#mail').val(localStorage["mail"]);
}else{
$('#mail').val("");
}
if (localStorage["password"]) {
$('#password').val(localStorage["password"]);
}else{
$('#password').val("");
}
});
function validate(){
if ($("remember:checked")) {
var mail= $("#mail").val();
var password= $("#password").val();
localStorage["mail"] = mail ;
localStorage["password"] = password;
localStorage.setItem("mail", mail) ;
localStorage.setItem("password", password) ;
}else{
alert("You didn't check it! Let me check it for you.")
}
}
Can anybody help me ?
thank you
it seems that $("remember:checked") is not a valid selector (a . or a # is missing). So probably your values are never saved into localstorage
when you check for existence of an element you should use length property instead
if ($("<your selector>").length) {
...
}
You are doing it wrong for setting and getting an item in local storage Use
localStorage.setItem('someval',1)
localStorage.getItem('someval'); // 1
can someone explain me why this script is not working?
<script type="text/javascript">
function destroy(ID) {
if (confirm("Deleting is a very bad thing! Sure?"))
{
location.href='#Url.Action("SomeAction", new { id = ID })'
}
}
The error is: The name 'ID' does not exist in the current context, and occures here new { id = ID }
If I just replace ID in this way: new { id = 3 } it works fine. What is the problem?
You mix your Server code with the client code.
ID is a javascript variable- exist only on the client.
#Url.Action("SomeAction", server code, Exist only on the server.
You can't mix them!
You can do something like this:
function destroy(ID) {
if (confirm("Deleting is a very bad thing! Sure?")){
var url ='#Url.Action("SomeAction")';
url += '/?id =' + ID;
location.href = url;
}
}
You have to remember all the # stuff in the views are compiled and executed in the server and no longer exist in the client. tricky razor...
By the way, I would have change the confirm message...
On my forum-based website, I have a link below every post for reporting spam or abuse. Whenever this link is clicked, a web service is called on the server, when the call returns, the span containing the link (see the code below) is updated with something like 'Post reported' or if an error occurs it shows something like 'An error occurred while reporting the post', this is the javascript code:
<script src="/js/MicrosoftAjax.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript" language="javascript">
var spanToUpdate;
function ReportPost(updateSpan, postID)
{
if (confirm("Are you sure you want to report this post as spam or abuse?"))
{
spanToUpdate = updateSpan;
var proxy = SiteWS.ReportPost(postID, onReportPostSuccess, onReportPostFailure);
}
}
function onReportPostSuccess(sender, e)
{
spanToUpdate.innerHTML = "Post reported";
}
function onReportPostFailure(sender, e)
{
spanToUpdate.innerHTML = "An error occurred while reporting the post";
}
</script>
And this is the reporting link:
<div class="post">
<p>post text here</p>
<span>Report Post</span>
</div>
Other posts ...
As you can see, I use a variable, spanToUpdate, to hold a reference to the span that contains the reporting link, which means that if the user reports another post (ie. clicks another reporting link) before the call returns, the span of the last post will be updated twice and the previous one won't be updated at all, is there any workaround for this?
Many thanks
You can use anonymous functions and closures for that.function ReportPost(updateSpan, postID) {
if (confirm("Are you sure you want to report this post as spam or abuse?")) {
var proxy = SiteWS.ReportPost(
postID,
function(sender,e) {updateSpan.innerHTML = "Post reported" },
function(sender,e) {updateSpan.innerHTML = "An error occurred while reporting the post" }
);
}
}
edit: hmm .. just wondering, will updateSpan be referring to the same span when the anonymous method is called? – Waleed Eissa
Yes, that's the magic of closures. Try this little example:
<head>
<script>
function foo()
{
bar(1, 100);
bar(2, 150);
bar(3, 200);
bar(4, 250);
bar(5, 300);
document.getElementById("div1").innerHTML += "foo() is done. ";
return;
}
function bar(val, timeout) {
window.setTimeout(
function() {
document.getElementById("div1").innerHTML += " " + val + " ";
},
timeout
);
}
</script>
</head>
<body>
<button onclick="foo()">click</button>
<div id="div1"></div>
</body>You will see that each time the anonymous function is called it has preserved "its own" value of val from the time/context when bar() was called.
Not a JavaScript developer so this might not work. Would it be possible to hold a reference to the post id and the spanToUpdate and then have the response from the server include the post id. Then you could retrieve the correct spanToUpdate.