It would be of significant benefit to my business if we could display information corresponding to a user's location when they reach our website's home page. I understand that trying to obtain geolocation from only an IP address is not an exact science, but we're willing to take what we can get.
What techniques are there available for determining approximate locations of a web user?
your best bet is to use the google apis. You can have the IP set in a form field that is submitted. Or you could use a .net api
google.loader.ClientLocation to get a person's lat/long using their IP address
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABQIAAAALDWeTDQHOJCbCf0JnUqL8BT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQA7AE8xB9MyWgHECPY2qimOp7BUQ"></script>
<script src="scripts/clientLocation.js" type="text/javascript"></script>
<script type="text/javascript">
function $g(id) {
return document.getElementById(id);
}
function displayLocation(latitudeEl, longitudeEl, cityEl, regionEl, countryEl, country_codeEl) {
var cloc = new ClientLocation.Location(google.loader.ClientLocation);
if (latitudeEl) latitudeEl.innerHTML = cloc.latitude;
if (longitudeEl) longitudeEl.innerHTML = cloc.longitude;
if (cityEl) cityEl.innerHTML = cloc.address.city;
if (regionEl) regionEl.innerHTML = cloc.address.region;
if (country) country.innerHTML = cloc.address.country;
if (country_codeEl) country_codeEl.innerHTML = cloc.address.country_code;
}
function init() {
displayLocation($g("latitude"), $g("longitude"), $g("city"), $g("region"), $g("country"), $g("country_code"));
}
</script>
</head>
<body onload="init()">
<form id="form1" runat="server">
<div>
latitude : <span id="latitude"></span>
<br />
longitude : <span id="longitude"></span>
<br />
city : <span id="city"></span>
<br />
region : <span id="region"></span>
<br />
country : <span id="country"></span>
<br />
country_code : <span id="country_code"></span>
<br />
</div>
</form>
</body>
</html>
// <copyright file="clientLocation.js" company="Sky Sanders">
// This source is placed in the Public Domain.
// http://skysanders.net/subtext
// Attribution is appreciated.
// </copyright>
/*
object literal format for google.loader.clientlocation
{
"latitude": 33.324,
"longitude": -111.867,
"address": {
"city": "Chandler",
"region": "AZ",
"country": "USA",
"country_code": "US"
}
}
*/
var ClientLocation = {};
ClientLocation.Address = function() {
/// <field name="city" type="String" />
/// <field name="region" type="String" />
/// <field name="country" type="String" />
/// <field name="country_code" type="String" />
/// <returns type="ClientLocation.Address"/>
if (arguments.length > 0) {
this.city = arguments[0].city;
this.region = arguments[0].region;
this.country = arguments[0].country;
this.country_code = arguments[0].country_code;
return;
}
else {
this.city = "";
this.region = "";
this.country = "";
this.country_code = "";
}
}
ClientLocation.Location = function() {
/// <field name="latitude" type="Number" />
/// <field name="longitude" type="Number" />
/// <field name="address" type="ClientLocation.Address" />
if (arguments.length > 0) {
this.latitude = arguments[0].latitude;
this.longitude = arguments[0].longitude;
this.address = arguments[0].address;
}
else {
this.latitude = 0;
this.longitude = 0;
this.address = undefined;
}
}
You can't tell for sure and it can be inaccurate but services do exist to map IP addresses to their geographical location.
I just Binged for it and I got: http://www.ip2location.com/
They tend to need subscriptions to their service, though
The best option is to licence the data from someone like MaxMind - they use a lot of different methods, some of them pretty clever, to find out the location associated with an IP address and in my experience their data is pretty easy to integrate with as well.
Related
I am Making a Lib Managment System to Add Books to My DB.
I am doing this through ASP.NET MVC AND my view is in REACT.JS
My Controller for CREATE BOOK is :
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "BookName,BookSerialNumber,BookAuther,BookPublisher")] Book book)
{
using (LibraryManagmentSystemDBEntities db = new LibraryManagmentSystemDBEntities())
if (ModelState.IsValid)
{
db.Books.Add(book);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(book);
}
My view which is in React.js is as follows
Error is coming Uncaught TypeError: Cannot read property 'value' of undefined
I have also added a screen shot so that it is easier to point my mistake out.
<div id="app" class="container">
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.6/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script type="text/babel">
class InputValues extends React.Component
{
constructor(props)
{
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e)
{
e.preventDefault();
const data = new FormData();
data.append('BookName', this.BookName.value);
data.append('BookSerialNumber', this.BookSerialNumber.value);
data.append('BookAuther', this.BookAuther.value);
data.append('BookPublisher', this.BookPublisher.value);
var xhr = new XMLHttpRequest();
xhr.open('post', this.props.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function()
{
if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200)
{
alert("good!!!");
}
}
xhr.send(data);
}
render()
{
return(
<div>
<form onSubmit={this.handleSubmit}>
<label htmlFor="BookName">Book Name </label><br />
<input id="BookName" type="text" placeholder="Enter BookName" ref={this.BookName} />
<br /><br />
<label htmlFor="BookSerialNumber">Book Serial Number: </label><br />
<input id="BookSerialNumber" type="text" placeholder="Enter BookSerialNumber" ref={this.BookSerialNumber} />
<br /><br />
<label htmlFor="BookAuther">BookAuther: </label><br />
<input id="BookAuther" type="text" placeholder="BookAuther" ref={this.BookAuther} />
<br /><br />
<label htmlFor="BookPublisher">BookPublisher: </label><br />
<input id="BookPublisher" type="text" placeholder="Enter BookPublisher" ref={this.BookPublisher} />
<br /><br />
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
);
}
}
ReactDOM.render
(<InputValues />, document.getElementById("app"));
</script>
I am trying to build a simple ASP.net MVC application.
My Controller Looks like below.
namespace CustomerReadAndLoad.Controllers
{
public class CustomerController : Controller
{
//
// GET: /Customer/
public ActionResult Index()
{
return View();
}
public ActionResult LoadCustomer()
{
return View();
}
[HttpPost]
public ActionResult DisplayCustomer()
{
Customer obj = new Customer();
obj.ID = Convert.ToInt16(Request.Form["CuatomerID"]);
obj.Name = Convert.ToString(Request.Form["CuatomerName"]);
obj.Amount = Convert.ToInt16(Request.Form["CuatomerAmount"]);
return View(obj);
}
}
}
I trying to Include the action DisplayCustomer in LoadCustomerView like below
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>LoadCustomer</title>
</head>
<body>
<div>
<form action ="DisplayCustomer" method ="post">
Welcome to Customer management System<br />
Enter the below details <br />
Customer ID :- <input type="text" name = "CuatomerID" /><br />
Customer Name :- <input type="text" name = "CuatomerName" /><br />
Customer Amount :- <input type="text" name = "CuatomerAmount" /><br />
<input type ="button" value="ClickHere" />
</form>
</div>
I am unable to move to the view DisplayCustomer once i click Submit Button.
Try this:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>LoadCustomer</title>
</head>
<body>
<div>
<%using(Html.BeginForm("DisplayCustomer", "Customer", FormMethod.Post)){%>
Welcome to Customer management System<br />
Enter the below details <br />
Customer ID :- <input type="text" name = "CuatomerID" /><br />
Customer Name :- <input type="text" name = "CuatomerName" /><br />
Customer Amount :- <input type="text" name = "CuatomerAmount" /><br />
<button type ="submit">"ClickHere"</button>
<%}%>
</div>
I am trying to attach onBlur and onFocus handler to a SSN input field. However, I am seeing an error saying object has no method 'ON'. The code is at http://jsfiddle.net/H4Q5f/
As you can see, I commented out to figure out the details, however had no luck so far. Any help is appreciated. For convenience, here is the code:
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script type="text/javascript" src="../../appjavascript/ssa/mkwr/mytest.js"></script>
</head>
<body>
<div data-role="page" id="MyTestPage">
<div data-role="header" data-position="fixed" data-logo="true" data-tap-toggle="false" data-fullscreen="false" >
<h1> Page Title </h1>
</div>
<div data-role="content">
<div class="content-primary divcontent">
<h1 class='h1title'>Using This App</h1>
<p> Here are the instructions </a>
</p>
</div>
<div class="inputdata">
<br /> <br />
<input type="text" name="accessCode" id="AccessCode" value="" placeholder="Access Code:" /> <br />
<input type="text" id="ssn1" class="ssn" value="" placeholder="SSN1:" /> <br />
<input type="text" id="ssn2" class="ssn" value="" placeholder="SSN2:" /> <br />
</div>
<input type="button" id="myalert" value="Next" />
</div>
<!-- /content -->
</body>
</html>
And here is the java script
if (typeof TEST == "undefined" || !TEST) {
var TEST = {};
}
( function() {
TEST.mkwr = {
init : function() { // this is a public function
$("[data-role='page']").on("pagebeforeshow", TEST.mkwr.hideError());
$("[data-role='page']").on("pageshow", TEST.mkwr.setHandlers());
},
// On Blur, we need to add the '-'s if they doesn't exist so the user
// view edit the entered value formatted
ssnOnBlurHandler : function(input) { // Auto format SSN on blur
if ($(input).val().length == 9) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(3, 5);
var _ssnSegmentC = _ssn.substring(5, 9);
$(input).val(
_ssnSegmentA + "-" + _ssnSegmentB + "-" + _ssnSegmentC);
}
}, // _ssnOnBlurHandler
// On focus, we need to remove the '-'s if they exist so the user
// can edit the entered value
ssnOnFocusHandler : function(input) {
// allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
if ($(input).val().length == 11) {
var _ssn = $(input).val();
var _ssnSegmentA = _ssn.substring(0, 3);
var _ssnSegmentB = _ssn.substring(4, 6);
var _ssnSegmentC = _ssn.substring(7, 11);
$(input).val(_ssnSegmentA + _ssnSegmentB + _ssnSegmentC);
}
}, // _ssnOnFocusHandler
// Hide all errors
hideError : function() {
$(".error").hide(); // Hide all errors
},
setHandlers : function() {
alert("Set Handlers");
// $(".ssn").each( function() {
// var input = this; input.blur(TEST.mkwr.ssnOnBlurHandler(input))
// });
// $(".ssn").each( function() {
// var input = this; input.focus(TEST.mkwr.ssnOnFocusHandler(input))
// });
}
};
})(); // end the anonymous function
$("[data-role='page']").bind("pageinit", TEST.mkwr.init());
I found a couple of issues with the code on the jsfiddle. Here is an updated one that is working to fire handlers and parse code. It looks like your ssn logic might need to be fixed a little but everything is getting you to there.
http://jsfiddle.net/H4Q5f/10/
The problems I saw were partly what was mentioned before you were using .on instead of .bind given the jquery version. But also you were not setting your handlers but rather firing your handlers. You had this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler(input))
which would return the result of the function to the set method which is not what you were looking for. So I changed it to this:
input.bind("blur",TEST.mkwr.ssnOnBlurHandler)
So now you are passing the handler to the set method so that it will fire when the event takes place.
Hope this makes sense.
The .on() function was introduced in jQuery 1.7. The code you've posted above includes jQuery 1.6.4 (<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>), which doesn't have that function. You can either upgrade to the latest version of jQuery (recommended) or use the equivalent function - .bind() - for the older versions.
does anybody know how i get phpmailer to work on an uploaded website.
include("class.phpmailer.php");
include("class.smtp.php");
$mail = new PHPMailer();
$body = "You have been added to the University of Portsmouth project
database. Your password is
'".$_POST['Password']."'
And your username is
'".$_POST['Username']."'
please click the link below, login to the website, select account settings and change
the password to become verified";
$mail->IsSMTP();
$mail->SMTPAuth = true; // enable SMTP authentication
$mail->SMTPSecure = "tsl"; // sets the prefix to the servier
$mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
$mail->Port = 25; // set the SMTP port
$mail->Username = "projectnateabiola#gmail.com"; // GMAIL username
$mail->Password = ""; // GMAIL password
$mail->From = "projectnateabiola#gmail.com";
$mail->FromName = "Nathan Abiola";
$mail->Subject = "You have been added to the project database, this email is important";
$mail->AltBody = "Please click"; //Text Body
$mail->WordWrap = 50; // set word wrap
$mail->MsgHTML($body);
$mail->AddReplyTo("projectnateabiola#gmail.com","Webmaster");
$mail->AddAddress($_POST['Email'],"First Last");
$mail->IsHTML(true); // send as HTML
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}
}
}
}
The code works when offline, but once i upload it i get the following error when i submit it. Am i missing something like you cant use phpmailer online. Does any body have any potential alternatives. Thanks for any possible help.
SMTP Error: Could not connect to SMTP host. Mailer Error: SMTP Error: Could not connect to SMTP host.
I use this for my sites. It is a form on a webpage that calls a php file to send an email. I have found that it has issues sometimes on College servers so keep that in mind.
create a file called mailto.php and paste this in (note that you need to put the correct email address in)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form Submitted!</title>
</head>
<body>
<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail( "PUT YOUR EMAIL ADDRESS HERE", "Subject: $subject",
$message, "From: $email" );
echo "Your message has been sent successfully!";
}
else
//if "email" is not filled out, display the form
{
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
Then put this in the body of your html file
<form name="formcheck" onsubmit="return formCheck(this);" action="mailto.php" method="post">
<br />
E-mail: <input type="text" name="email" id="email" size="42" />
<br />
<br />
<br/>
Subject: <input type="text" name="subject" id="subject" size="42" />
<br />
<br />
<br />
Message:
<br />
<textarea rows="5" cols="40" name="message" id="message"></textarea>
<br />
<br />
<input type="submit" onClick="return checkmail(this.form.email)" value="Submit" /><input type="reset" />
</form>
Hope this helps and if anyone has suggestions on how to make this better let me know :)
I wrote a small shopping cart in .Net that sends someone to PayPal upon order completion to make payment. To send them to PayPal I have the following form on a generic "paypal.aspx" page that has no real user functionality on it:
<form action="http://www.paypal.com/cgi-bin/webscr" method="post" id="paypal">
<input type="hidden" name="cmd" value="_cart"/>
<input type="hidden" name="upload" value="1"/>
<input type="hidden" name="business" value="email#email.com"/>
<input type="hidden" name="tax_cart" id="tax_cart" />
<input type="hidden" name="handling_cart" id="handling_cart" />
<input type="hidden" name="return" id="return" value='<%="http://" + Request.Url.Authority + "/" %>' />
<input type="hidden" name="custom" id="custom" />
<input type="hidden" name="first_name" id="first_name" />
<input type="hidden" name="last_name" id="last_name" />
<input type="hidden" name="address1" id="address1" />
<input type="hidden" name="address2" id="address2" />
<input type="hidden" name="city" id="city" />
<input type="hidden" name="state" id="state" />
<input type="hidden" name="zip" id="zip" />
<input type="submit" id="paypalButton" value="PayPal" style="display: none; visibility: hidden;"/>
</form>
When the page containing this form loads, there is another form directly below it with a bunch of hidden fields that are filled in with data from the actual order (which is pulled based on a Guid query string value). The JavaScript in that form fills in the values that PayPal requires like this:
<form runat="server">
<asp:ScriptManager runat="server" />
<div id="ppItems">
<asp:Repeater runat="server" ID="rpItems">
<ItemTemplate>
<input type="hidden" id='<%#"hv_quantity_" + Container.ItemIndex %>' value='<%#Eval("Quantity") %>' />
<input type="hidden" id='<%#"hv_item_" + Container.ItemIndex %>' value='<%#Eval("Color") + " Tactical Hat" %>' />
<input type="hidden" id='<%#"hv_amount_" + Container.ItemIndex %>' value='<%#Eval("UnitCost", "{0:n2}") %>' />
</ItemTemplate>
</asp:Repeater>
</div>
<asp:HiddenField runat="server" ID="hvCustom" />
<asp:HiddenField runat="server" ID="hvTax" />
<asp:HiddenField runat="server" ID="hvShipping" />
<asp:HiddenField runat="server" ID="hvFirstName" />
<asp:HiddenField runat="server" ID="hvLastName" />
<asp:HiddenField runat="server" ID="hvAddress1" />
<asp:HiddenField runat="server" ID="hvAddress2" />
<asp:HiddenField runat="server" ID="hvCity" />
<asp:HiddenField runat="server" ID="hvState" />
<asp:HiddenField runat="server" ID="hvZip" />
<script type="text/javascript" language="javascript">
var paypal = document.getElementById('paypal');
function load() {
Sys.Application.remove_load(load);
//set the items
var ppItems = document.getElementById('ppItems');
var items = ppItems.getElementsByTagName('input');
var itemsCount = items.length / 3;
for (var i = 0; i < itemsCount; ++i) {
var quantity = document.getElementById('hv_quantity_' + i).value;
var item = document.getElementById('hv_item_' + i).value;
var amount = document.getElementById('hv_amount_' + i).value;
addFormItem('item_name_' + (i + 1), quantity + " " + item);
addFormItem('amount_' + (i + 1), amount);
addFormItem('quantity_' + (i + 1), quantity);
}
//set global items
var custom = document.getElementById('<%=this.hvCustom.ClientID %>').value;
document.getElementById('tax_cart').value = document.getElementById('<%=hvTax.ClientID %>').value;
document.getElementById('handling_cart').value = document.getElementById('<%=this.hvShipping.ClientID %>').value;
document.getElementById('return').value += 'thanks.aspx?p=' + custom;
document.getElementById('custom').value = custom;
document.getElementById('first_name').value = document.getElementById('<%=this.hvFirstName.ClientID %>').value;
document.getElementById('last_name').value = document.getElementById('<%=this.hvLastName.ClientID %>').value;
document.getElementById('address1').value = document.getElementById('<%=this.hvAddress1.ClientID %>').value;
document.getElementById('address2').value = document.getElementById('<%=this.hvAddress2.ClientID %>').value;
document.getElementById('city').value = document.getElementById('<%=this.hvCity.ClientID %>').value;
document.getElementById('state').value = document.getElementById('<%=this.hvState.ClientID %>').value;
document.getElementById('zip').value = document.getElementById('<%=this.hvZip.ClientID %>').value;
//submit to paypal
document.getElementById('paypalButton').click();
}
function addFormItem(name, value) {
var item = document.createElement('input');
item.setAttribute('type', 'hidden');
item.setAttribute('name', name);
item.setAttribute('id', name);
item.setAttribute('value', value);
paypal.appendChild(item);
}
Sys.Application.add_load(load);
</script>
So when this overall page loads, order detail is pulled from the database based on the query string guid value, a bunch of hidden fields are filled with the required values from the database and then the above script runs on load setting the PayPal form values and then clicking the hidden button submits everything to PayPal so the end user can pay.
The issue I have is this works great in IE7+ and FF3+, but Safari and Chrome are not playing nicely. In Chrome I get redirected to the PayPal home page instead of being asked to pay. Safari is even stranger in that both redirect to the PayPal payment screen (like IE7+ and FF3+), but on the Mac version only it doesn't pre-populate all the fields (specifically name/address), but other fields (such as amount, tax, etc.) do populate.
Can anyone provide any suggestions as to why Chrome and Safari (Mac only) don't work right, but everything else seems to?
I finally figured it out by going the old school route and redirecting instead of executing a POST:
var order = (from o in data.Orders where o.PayPal == Request.QueryString["p"] select o).Single();
//build the generic PP detail
sb.Append("http://www.paypal.com/cgi-bin/webscr/?cmd=_cart");
sb.AppendValue("upload", "1", false);
sb.AppendValue("business", "email#domain.com", true);
sb.AppendValue("handling_cart", (this.CurrentCart.Tax.HasValue ? this.CurrentCart.Tax.ToString() : "0"), false);
sb.AppendValue("return", this.Request.Url.Authority, true);
sb.AppendValue("custom", order.PayPal, true);
sb.AppendValue("first_name", (order.Customer.Name.IndexOf(" ") > -1) ? order.Customer.Name.Split(' ')[0] : order.Customer.Name, true);
sb.AppendValue("last_name", (order.Customer.Name.IndexOf(" ") > -1) ? order.Customer.Name.Split(' ')[1] : order.Customer.Name, true);
sb.AppendValue("address1", order.Customer.Address1, true);
sb.AppendValue("address2", order.Customer.Address2, true);
sb.AppendValue("city", order.Customer.City, true);
sb.AppendValue("state", order.Customer.StateProvince, true);
sb.AppendValue("zip", order.Customer.PostalCode, true);
for (int i = 0; i < order.OrderItems.Count; ++i)
{
string index = (i + 1).ToString();
sb.AppendValue("item_name_" + index, order.OrderItems[i].ProductAttribute.Name, true);
sb.AppendValue("amount_" + index, string.Format("{0:n2}", order.OrderItems[i].UnitCost), false);
sb.AppendValue("quantity_" + index, order.OrderItems[i].Quantity.ToString(), true);
}
Response.Redirect(sb.ToString());
The AppendValue method is an extension method for a StringBuilder and it looks like this:
public static void AppendValue(this StringBuilder sb, string name, string value, bool encode)
{
sb.Append("&" + name + "=" + ((encode) ? HttpUtility.UrlEncode(value) : value));
}