Here is my java script
$('#geoLocation').click(function () {
alert("I am Here");
if (navigator.geolocation) {
// Get Latitude and Longitude
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
// Hide Locator Panel, if Browser not supported
document.getElementById('panel1').style.display = 'none';
}
});
function showPosition(position) {
// x.innerHTML = "Latitude: " + position.coords.latitude +
// "<br>Longitude: " + position.coords.longitude;
document.getElementById('latitude').innerHTML = position.coords.latitude;
document.getElementById('longitude').innerHTML = position.coords.longitude;
}
I need to get at the latitude and longitude values (which are hidden on the screen), in Postback on the CodeBehind. How do I do this?
You can use $('#HiddenFieldId').val() to assign data to HiddenField at client side.
<div id="geoLocation">Click me to retrieve Geo Location</div>
<asp:HiddenField runat="server" ID="LatitudeHiddenField" />
<asp:HiddenField runat="server" ID="LongitudeHiddenField" />
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$('#geoLocation').click(function () {
if (navigator.geolocation) {
// Get Latitude and Longitude
navigator.geolocation.getCurrentPosition(showPosition, geoLocationErrors);
} else {
// Hide Locator Panel, if Browser not supported
document.getElementById('panel1').style.display = 'none';
}
function showPosition(position) {
$('#<%= LatitudeHiddenField.ClientID %>').val(position.coords.latitude);
$('#<%= LongitudeHiddenField.ClientID %>').val(position.coords.longitude);
}
function geoLocationErrors() {
alert("Your browser doesn't support Geo Location.");
}
});
</script>
Then you can retrieve those value from HiddenField at server side as -
var latitute = LatitudeHiddenField.Value;
var longitude = LongitudeHiddenField.Value;
I assume 'latitude' and 'longitude' are HTML elements on the page ?
That being the case, you should be able to add a runat="server" attribute to them and then they will be available in server-side code. If you're site is ASP.NET 4/4.5 you can also add ClientIDMode="Static" and your showPosition function will work as it is; if not you could a class to them and use a jQuery class selector to get your two items.
Related
I have a img button. When it is clicked, I set the session value using jquery. however I cannot get the session on vb code behind. My process is like that after the user click the image, I set the session. When the user open popup page and return the page. I need to check the session to do something. However in the vb code, the session is nothing. Would some one tell me how to do it.
The below code call the function:
<asp:Image ID="img" runat="server" onclick="SetSession(hdID);" ImageUrl="pic_bottle.gif" />
The jquery script:
function SetSession(hdID) {
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
$.session.set('UpdateProdOrder', -1);
}
else {
var hdProdID = $('#hdProdID').val();
$.session.set("UpdateProdOrder", hdProdID);
}
alert($.session.get("UpdateProdOrder"));
}
The vb code behind never get the session
If Not Session("UpdateProdOrder") Is Nothing Then
'do something
updateOrder()
end if
The localStorage and sessionStorage properties allow saving key/value pairs in a web browser.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).
These values are maintained on the client side, but you are trying to retrieve it on the server side. session variables are server side
Solution:
Method 1:
You'd have to have a little ajax call to talk to the server to set it.
please check it out
Method 2 :
Assigning the ASP.NET Session Variable using Javascript.
<script type="text/javascript">
function SetSession(hdID)
{
var hd = $('#' + hdID);
var hdValue = hd.val();
if (hdValue == "s") {
'<%Session["UpdateProdOrder"] = "' + -1+ '"; %>';
}
else {
var hdProdID = $('#hdProdID').val();
'<%Session["UpdateProdOrder"] = "' + hdProdID+ '"; %>';
}
alert('<%=Session["UpdateProdOrder"] %>');
}
</script>
Accessing ASP.NET Session variable using Javascript:
<script type="text/javascript">
function GetSession()
{
var updateProdOrder= '<%= Session["UpdateProdOrder"] %>';
alert(updateProdOrder);
}
</script>
You cannot change a server side Session object with javascript directly. You need to send it to the server somehow. This can be done by changing the image to an ImageButton and do a PostBack to modify the Session object. But since you seem to have some data in hdID. You cannot send that to the server with a ImageButton alone, you'll need a HiddenField
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSession(hdID);"
ImageUrl="pic_bottle.gif" OnClick="ImageButton1_Click" />
<asp:HiddenField ID="HiddenField1" runat="server" />
<script type="text/javascript">
var hdID = 'test';
function SetSession(hdID) {
$('#<%= HiddenField1.ClientID %>').val(hdID);
}
</script>
And then in code behind
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Session["UpdateProdOrder"] = HiddenField1.Value;
Label1.Text = string.Format("Session value is now '{0}'", Session["UpdateProdOrder"]);
}
You could do this also without the javascript SetSession, but that depends on where and when hdID is used on other parts of the page.
i am working on a project in c#.net , I have a jquery code in my master page and the master page is included in my home page. I have created hyperlinks dynamically in my home page.
i want that when ever a user clicks on the hyperlink, instead of the wholepage only 1 part of the page with div class=refresh1 will reload.
i have include following jquery in my head tag.
<script type="text/javascript">
$(document).ready(function () {
$("a").click(function () {
var link1 = $(".mylink").text();
$.post("loaddata.aspx",
{
link: link1
},
function (responseTxt, statusTxt, xhr) {
if (statusTxt == "success")
alert("Done!");
if (statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
$(".refresh1").load('loaddata.aspx .part1');
});
});
});
</script>
here mylink is class of 'a' tag.
i want that when ever the hyperlink will be clicked it will load the refresh1 class part from another page i.e from loaddata.aspx with class=part1.
in loaddata.aspx i want to retrive the value of link that i have passed in post method .how can i do it plzzzzzzzzz reply aasap.
You can use .load() like so:
$('a').click(function () {
var link1 = $(this).text();
$(".refresh1").load('loaddata.aspx .part1',{
link : link1
},function(data){
//optional callback code
});
});
the .load() fires a GET request though. To do it using POST, you must use .post() and parse the data it retrieves:
$('a').click(function () {
var link1 = $(this).text();
$.post('loaddata.aspx',{
link : link1
},function(data){
$(data).find('.part1').appendTo('.refresh1');
});
});
You can use Request["link"] to get the value.
Also make sure you decode the value after you retrieve.
I want to set the Image URL of Image control using client side code and save the image to the server using C# code. Here is what i have implemented:
<asp:Button ID="btnImageUpload" OnClick="btnImageUpload_Click" runat="server" Text="Preview" CausesValidation="false" OnClientClick="Image_View();"/>
C# Code:
protected void btnImageUpload_Click(object sender, EventArgs e)
{
if (Directory.Exists(#"C:\\Images"))
SaveImage_Server();
else
{
Directory.CreateDirectory(#"C:\\Images");
SaveImage_Server();
}
}
public void SaveImage_Server()
{
try
{
if (FlUpldImage.PostedFile.ContentLength > 0)
{
String fn = Convert.ToString(DateTime.Now) + Path.GetFileName(FlUpldImage.FileName);
if (fn.Contains('/'))
{
fn = fn.Replace("/", "");
}
if (fn.Contains(':'))
{
fn = fn.Replace(":", "");
}
if (fn.Contains(" "))
{
fn = fn.Replace(" ", "");
}
String Saved_ImagePath = #"C://Images/" + fn; // making the path with created dynamically folder name
FlUpldImage.SaveAs(Saved_ImagePath);
HidnLocalImageURL.Value = Saved_ImagePath;
}
}
catch (Exception re)
{
}
}
JavaScript
function Image_View() {
// __doPostBack('<%= btnImageUpload.ClientID %>', '');
// var clickButton = document.getElementById("<%= btnImageUpload.ClientID %>");
// clickButton.click()
var idFlUpload = '<%= FlUpldImage.ClientID %>';
var fu1 = document.getElementById(idFlUpload);
var idImgCntrl = '<%= imgCorrect.ClientID %>';
var ImgCntrl = document.getElementById(idImgCntrl);
alert("You selected " + fu1.value);
ImgCntrl.setAttribute('src', fu1.value);
}
Now my issue is that once the server side code is executed the page gets refreshed and the link set to Image control using JS gets reset to default value.
How can i get this working wherein the image also gets saved and Image URL property also gets set through JS.
If there is any other way to implement this than please let me know. Thanks in Advance!
You have to set it on server too. You can use hidden field to save the url and access that hidden field on server to get the url to set mgCntrl.ImageUrl
In html
<input type="hidden" runat="server" id="hdnImageSrc" />
On Client javascript
hdnImageSrc = document.getElementById('<%= hdnImageSrc.ClientID %>');
mgCntrl.setAttribute('src', fu1.value);
hdnImageSrc.value = fu1.value;
On server side code
mgCntrl.ImageUrl = hdnImageSrc.Value;
I have a link like that. It's getting from instagram api.
http://localhost:60785/access_token.aspx/#access_token=43667613.4a1ee8c.791949d8f78b472d8136fcdaa706875b
How can I get this link from codebehind?
I can take it with js but i can't get it after assign to label. I mean:
<script>
function getURL(){
document.getElementById('lblAccessToken').innerText = location.href;
}
</script>
This js function is in body onload event. How can I reach this innerText value from codebehind?
If you are using ASP.NET 4.0 and jQuery, its fairly easy. Otherwise you may have to deal with mangled id and have to deal with DOMReady on your own. Try this
Markup
<asp:Label ID="lblAccessToken" runat="server" ClientIDMode="Static"></asp:Label>
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token");
$("#lblAccessToken").html( myToken );
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
You want the value on Page_Load right? I haven't figured out a way myself to fetch the hash value on Page_Load.I usually do one of these things
Pass the hash value to a jQuery ajax method and store it there.
Grab the hash value and redirect to the same page after converting it to a querystring
JavaScript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var myToken = GetHashParameterByName("access_token") || "";
if(my_token !=== ""){
window.location = window.location.split("/#")[0] + "?access_token=" + myToken;
}
});
function GetHashParameterByName(name) {
var match = RegExp('[#&]' + name + '=([^&]*)')
.exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Now at Page_Load, grab it like
string token = Request.QueryString["access_token"];
Please note that it takes one more round trip to the server and so not very efficient. But this is what I do.
Can java script add the contents below to a asp table aswell at the same time (with html tags)
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
return false;
});
});
</script>
<textarea style="border: 0" cols="77" rows="2">Write Something....</textarea>
<button>Post Message</button>
<div id="test1"></div>
</asp:Content>
something like:
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
$('#test1').append('<div id="test">' + x + '</div>');
//$save append aswell to Table1
return false;
});
});
</script>
<script type="text/javascript">
$(function () {
$('button').click(function () {
var x = $('textarea').val();
$('textarea').val('');
var newdiv = $("<div></div>").html(x).attr('id','test');
$('#test1').append(newdiv);
$('#Table1').append(newdiv);
//$save append aswell to Table1
return false;
});
});
</script>
It seems like you are using jquery here.
Have you got your jquery framework loaded & tried your code to see if it works??
It is running fine on jsfiddle.net here
Updates
If your Table1 is on the same page.
All you need to do is to get hold of the DOM element.
if you have a table
<table id="Table1">
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
You can add after your code
$('#test1').append('<div id="test">' + x + '</div>');
this code
$('#Table1 tr:last').after('<tr><td>'+ x +'<td></tr>');
Hope you find this helpful