I am trying to print the current location address using geo location but nothing is getting printed on screen. Can you please help me where am I wrong here?
Or is there any other way to store the current address in variable?
<!DOCTYPE html>
<html>
<body>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+position.coords.latitude+','+position.coords.longitude;
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
var data = JSON.parse(request.responseText);
var address = data.results[0];
x.innerHTML = address.formatted_address;
};
}
</script>
</body>
</html>
This should work: JSFIDDLE
You were missing request.send(); and also not checking request.readyState
<!DOCTYPE html>
<html>
<body>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var request = new XMLHttpRequest();
var method = 'GET';
var url = '//maps.googleapis.com/maps/api/geocode/json?latlng=' + position.coords.latitude + ',' + position.coords.longitude;
var async = true;
request.open(method, url, async);
request.setRequestHeader('Accept', 'application/json');
request.onreadystatechange = function() {
if (request.readyState == XMLHttpRequest.DONE) {
var data = JSON.parse(request.responseText);
var address = data.results[0];
x.innerHTML = address.formatted_address;
}
};
request.send();
}
</script>
</body>
</html>
Related
I need to show the data in handsontable from excle sheet, But I got struck up in the middle, any one please help me here.
My controller code
public ActionResult Index()
{
return View();
}
public ActionResult GetJsonData(FormCollection formCollection)
{
var usersList = new List<User>();
if (Request != null)
{
HttpPostedFileBase file = Request.Files["UploadedFile"];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var user = new User();
user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
usersList.Add(user);
}
}
}
}
return View("GetJsonData",usersList);
}
Index view
<h2>Index</h2>
#using (Html.BeginForm("GetJsonData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td>File:</td>
<td>
<input type="file" name="UploadedFile" />
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="Submit" value="Submit" id="btnsave" />
</td>
</tr>
</table>
}
<div id="example1" class="hot handsontable htColumnHeaders"></div>
<script type="text/javascript">
$('#btnsave').click(function () {
var url = '/Home/GetJsonData';
$.get(url,
null,
function (data) {
debugger;
var container = document.getElementById('#example1');
var hot = new Handsontable(container, {
data: data,
rowheader: true,
colheader: true
});
});
});
</script>
GetJsonData view
<div id="example1" class="hot handsontable htColumnHeaders"></div>
<script type="text/javascript">
$(document).ready(function () {
var url = '/Home/GetJsonData';
$.get(url,
null,
function (data) {
var container = document.getElementById('#example1');
var hot = new Handsontable(container, {
data: data,
rowheader: true,
colheader: true
});
debugger;
});
});
</script>
have resolved this issue.
function UploadExcel() {
var formData = new FormData();
var totalFiles = document.getElementById("Uplaod").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("Uplaod").files[i];
formData.append("Document", file);
}
$.ajax({
url:"/Home/UpoadFile",
type: "POST",
dataType: "JSON",
data: formData,
contentType: false,
processData: false,
//data: JSON.stringify(oInvoice),
//contentType: "application/json; charset=utf-8",
//async: false,
success: function (result) {
debugger;
if (result != null)
{
//var data2 = result,
// container = document.getElementById('example1'),
// hot1;
//hot1 = new Handsontable(container, {
// data: JSON.parse(JSON.stringify(data2))
//});
//document.addEventListener("DOMContentLoaded", function() {
var data = result,
example1 = document.getElementById('example1'),
settings1,
emailValidator;
emailValidator = '^[^##\\s]+##([^##\\s]+\\.)+[^##\\s]+$';
emailValidator=function(value,callback)
{
setTimeout(function () {
if (/.+##.+/.test(value)) {
callback(true);
}
else {
callback(false);
}
}, 10);
}
settings1={
data: data,
colHeaders: ['FirstName','LastName','Email'],
columns:[
{data:'FirstName'},
{data:'LastName'},
{ data: 'Email', validator: emailValidator, allowInvalid: false }
]
} ;
var hot = new Handsontable(example1, settings1);
//function bindDumpButton()
//{
// if (typeof Handsontable === "undefined") {
// return;
// }
// //Handsontable.Dom.AddEvent(document.body, 'click', function (e) {
// // var element = e.target || e.srcElement;
// // if (element.nodeName == "BUTTON" && element.name == 'dump') {
// // var name = element.getAttribute('data-dump');
// // var instance = element.getAttribute('data-instance');
// // var hot = window[instance];
// // console.log('data of ' + name, hot.getData());
// // }
// //});
//}
//bindDumpButton();
// });
}
else {
// alert("Something Seems wrong. try agin afterwards");
}
},
error: function (err) {
}
});
}
I currently using DHTMLX calendar in my application with MVC.
Now i load all events by default as follows :
public ActionResult Index()
{
var scheduler = new DHXScheduler(this);
scheduler.LoadData = true;
scheduler.EnableDataprocessor = true;
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return View(scheduler);
}
/* public ContentResult Data()
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events);
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}*/
public ContentResult Data(int UserId)
{
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
if (UserId != null)
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events.Where(a => a.CreatedBy == UserId.ToString()));
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}
else
{
var data = new SchedulerAjaxData(new TimesheetEventDataContext().Events.Where(a => a.CreatedBy == Session["EmpId"].ToString()));
ViewBag.EmpId = new SelectList(_userRegisterViewModel.GetEmpPrimary(), "EmpId", "First_Name");
return (ContentResult)data;
}
}
Now i want to load the data by selection user in dropdownlist. So, i pass the userid to controller to fetch the events created by that particualar user.
My view page is following :
<!DOCTYPE html>
<html>
<head>
<title>Timesheet Events</title>
<style>
body
{
background-color:#eee;
}
</style>
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#ddlUsers').change(function () {
emId = $(this).val();
window.location.href = "/Calendar/Data?UserId=" + emId;
});
});
</script>
</head>
<body>
<div style="height:700px;width:900px;margin:0 auto;padding-top:10%;">
<table>
<tr>
<td>
Select User :
</td>
<td style="width:30%;">
#Html.DropDownList("EmpId", null, "-- Choose --", new { #class = "form-control", id = "ddlUsers" })
</td>
<td colspan="10">
<div id="calendar"></div>
</td>
</tr>
</table>
#Html.Raw(Model.Render())
</div>
</body>
</html>
Now, when i select user it pass the id to controller but not load the calendar view based on that..
can anyone help me to do this..
Thanks in advance..
I think what your #ddlUsers handler does is navigates browser to Data action, which is not what you need.
Try reloading data using client-side API of dhtmlxScheduler
$('#ddlUsers').change(function () {
var emId = $(this).val();
scheduler.clearAll();
scheduler.load("/Calendar/Data?UserId=" + emId;, "json");
});
Related docs:
http://docs.dhtmlx.com/scheduler/api__scheduler_clearall.html
http://docs.dhtmlx.com/scheduler/api__scheduler_load.html
I am relatively new to upload in MVC, so I have a little clarification. I am performing an ajax upload operation.
The upload operation works absolutely fine, but after the upload, it is redirecting to a new page which is blank page which I do not know how to stop it from doing it.
I used EmptyResult as well, but still the same thing is happening.What is it that I am missing?
#using(Html.BeginForm())
{
<input type="file" id="fileInput" />
<button onclick="startUpload();">Upload</button>
<br />
<progress id="progressBar" max="100" value="0" />
}
<script>
function startUpload() {
var fileInput = document.getElementById("fileInput");
if (fileInput.files.length == 0) {
alert("Please choose a file");
return;
}
var progressBar = document.getElementById("progressBar");
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function (e) {
// alert("in progress");
var percentComplete = (e.loaded / e.total) * 100;
progressBar.value = percentComplete;
};
xhr.onload = function () {
};
xhr.onerror = function () {
alert("Error! Upload failed. Can not connect to server.");
};
xhr.onreadystatechange = function () {
};
progressBar.value = 0;
xhr.open("POST", "/Home/Index", true);
xhr.setRequestHeader("Content-Type", 'application / json');
xhr.send(fileInput.files[0]);
}
</script>
[HttpPost]
public EmptyResult Index(FormCollection frm)
{
// Create JSON Response
var jsonData = new
{
status = "success",
message = "message"
};
return null;
}
You can pass in the event value on your button's onclick function call in order to manipulate the event handling later like this:
<button onclick="startUpload(event);">Upload</button>
Then in your javascript, you can ask it to ignore the default event handling (submit the form this case):
function startUpload(event) {
//do all those stuff
//event.preventDefault() should handle most of the browsers
//but for better compatibility, it's 3 lines here
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
return false;
}
I am developing MVC app.
In the view, I have declare some variable and I want to use it in the Jscript.
#model PaymentAdviceEntity.EMI
#{
ViewBag.Title = "Create";
double TotalAmt = 0;
}
#using (Html.BeginForm("Edit", "EMI", FormMethod.Post, new { #id = "frmEdit" }))
{
#if (Model.EMI_Child.Count > 0)
{
#foreach (var PaidEMIList in Model.EMI_Child)
{
TotalAmt = TotalAmt + PaidEMIList.Amount;
}
}
}
<script>
$(document).ready(function () {
CheckBalAmt();
});
function CheckBalAmt()
{
var nTotalAmount = document.getElementById("TotalAmount").value;
var nAllreadyPaidAmount = document.getElementById("AllreadyPaidAmount").value;
var BalAmt = nTotalAmount - nAllreadyPaidAmount;
var totalAmt1 = #TotalAmt; <- Shows error here...
var BalAndTotalAmt = BalAmt +totalAmt1;
$('.BalanceAmt').text("Bal Amt. : " + BalAndTotalAmt );
}
</script>
in above CheckBalAmt() method I want to show the value of variable TotalAmt ...
but it dont show anything...
var totalAmt1 = ('#TotalAmt');
var BalAndTotalAmt = BalAmt - totalAmt1;
alert(#TotalAmt);
$('.BalanceAmt').text("Bal Amt. : " + BalAndTotalAmt );
this code works...
function CheckBalAmt()
{
alert('#TotalAmt');
}
You have to use the razor symbol
I am trying to build a website that is hosted on Azure as a free website, it is using MVC4, with KnockoutMVC. The website is updating a table every 4 seconds from the controller. The code executes without problem locally, however when I deploy it to the Azure website, it does not process updates.
I now have started a completely new MVC 4 project, with some simple functions using knockout, showing the current time, and updating this every .5 of a second from the controller, it is using the same structure as the javascript I have written for the proper website. It is giving the same problem, and it appears as if the ko.ServerAction call is halting the javascript function.
View
#using PerpetuumSoft.Knockout
#model MVCHelloWorld.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time"></div>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</body>
#ko.Apply(Model)
Controller
namespace MVCHelloWorld.Controllers
{
public class HelloWorldController : BaseController
{
public HelloWorldModel model = new HelloWorldModel();
public ActionResult Index()
{
GetTimeDoCalculation();
return View();
}
public void GetTimeDoCalculation()
{
model.Time = DateTime.Now.ToString("H:mm:ss");
}
}
}
Model
namespace MVCHelloWorld.Models
{
public class HelloWorldModel
{
public string Time { get; set; }
}
}
Try adding this to the body of your view:
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
Your entire view will look like this:
#using PerpetuumSoft.Knockout
#model MvcApplication2.Models.HelloWorldModel
#{
var ko = Html.CreateKnockoutContext();
}
<script type="text/javascript">
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
#ko.ServerAction("Index", "HelloWorld");
t = setTimeout(function() { startTime(); }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
</script>
<body onload="startTime()">
<h2>Hello World - 2</h2>
<div id="time">
<script type="text/javascript">
#* Replace 4000 with the timeout, in milliseconds *#
window.setInterval(startTime, 4000)
</script>
<label>Knockout time</label>
#ko.Html.Span(m => m.Time)
</div>
</body>
#ko.Apply(Model)