Call JS function from code behind C# - javascript

I have a function onRowClick called RowClick and is working fine. I am trying to move it to a button and call the function from the code behind. For some reason is not triggering the function.. Anyone knows why and how I can fix this?
aspx.cs
if (e.CommandName == "Addvoucher")
{
GridDataItem item = (GridDataItem)e.Item;
var id = item.GetDataKeyValue("RowID");
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "RowClick("+id+");", true);
}
aspx
<script>
var popUpObj;
function RowClick(sender, eventArgs) {
var filterId = eventArgs.getDataKeyValue('RowID');
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
function LoadModalDiv()
{
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display="block";
}
function HideModalDiv() {
var bcgDiv = document.getElementById("divBackground");
bcgDiv.style.display = "none";
}
</script>
IN page voucher.aspx
<script type = "text/javascript">
function OnClose() {
if (window.opener != null && !window.opener.closed) {
window.opener.location.reload(); //refreshing parent when popup close
// window.opener.HideModalDiv();
}
//if (window.closed==true) window.open("~/routedoc.aspx");
}
window.onunload = OnClose;
</script>

Change your js function like this
function RowClick(filterId) {
popUpObj = window.open("voucher.aspx?param=" + filterId + "",
"ModalPopUp",
"toolbar=no," +
"scrollbars=no," +
"location=no," +
"statusbar=no," +
"menubar=no," +
"resizable=0," +
"width=530," +
"height=500," +
"left = 450," +
"top=130"
);
popUpObj.focus();
LoadModalDiv();
}
There is no need of this line now var filterId = eventArgs.getDataKeyValue('RowID'); Now you can directly use the parameter filterId in your js function.

Calling JavaScript function on code behind i.e. On Page_Load
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);
If you have UpdatePanel there then try like this
ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

Because you are calling RowClick() and in your code you are calling the second parameter eventArgs and actually it's an undefined value.
Make sure you pass the correct parameters.
Since you just calling a javscript function then I would recommend to just on the grid row data bound just assign the value to an anchor a tag or a button to just call the javascript.

The problem is you are not passing any arguments for that js function from server side but you are getting data key value in client function as in your edited question pass row id from server side and change the client side function as below,
function RowClick(rowId)
{
// use rowId
popUpObj = window.open("voucher.aspx?param=" + rowId + "",
}

Related

Chrome won't load simple JavaScript

My JavaScript inside the head tag:
<script type="text/javascript">
function over1() {
var img1 = document.getElementById("1").src;
document.getElementById("big").src = img1;
}
function out() {
document.getElementById("big").src = "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/shop-icon.png";
}
function london() {
var city = document.getElementById("city").value;
var check = city.toLowerCase();
var province = document.getElementById("province").value;
if (check == "london" && province == "ON") {
alert("Visit our company travel store at Masonville Mall!");
}
}
function  checkinput()  {
var email = document.contest.email.value;
var emailcheck = email.search("#");
if (!document.contest.name.value)  {
alert("Enter a name!")
} else {
alert("Thank You " + document.contest.name.value + " " + document.contest.lastname.value + " For Entering The Contest!")
window.open(calculator.html,'_blank');
}
}
</script>
I have the simple JavaScript inside the HTML file, but Chrome won't read it. In Inspector View, it throws ReferenceErrors for all my functions. Please help.
Why do you say that, those are all functions, nothing is invoked from these functions. call the functions and see if they are invoked correctly or not
checkinput();
over1();
/* the rest of them */

Load javascript on page load using asp.net

I have some working code (jQuery/Javascript) that makes a call to an API and submits data to it. The same service then returns a success or failure message depending on whether the data was inserted into the API db. The below works flawlessly when loaded in the browser.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$(document).ready(function () {
var groupType = getParameterByName('group').trim();
if (groupType == 'm') {
groupId = 'ICM.RealLife.Mobile';
} else if (groupType == 'd') {
groupId = 'ICM.RealLife.Desktop';
}
var email = getParameterByName('email').trim();
var mobileTel = getParameterByName('mobile').trim();
var panelistId = mobileTel;
var password = 'icm001';
var locale = 'en';
alert('email=' + email + '\n\nMobile=' + mobileTel + '\n\nGroup=' + groupId);
if (mobileTel != '' && email != '' && groupId != '') {
//Build up querystring to pass to API
var dataString = "panelistId=" + (encodeURIComponent('+') + mobileTel) + "&groupId=" + groupId + "&emailAddress=" + email + "&password=" + password + "&locale=" + locale + "&mobileNumber=" + (encodeURIComponent('+') + mobileTel) + "";
//var apiResult;
//send to API
$.getJSON('https://www.analyzeme.net/api/server/prereg/?', dataString + '&callback=?', function (getResult) {
//apiResult = JSON.stringify(getResult);
//alert(apiResult);
});
//} else {
// alert('Incorrect parameters!');
}
});
I now have to get this working using a 1x1 tracking pixel using aspx like below;
<img src="http://www.somedomain.com/pixel.aspx?email=email#email.com&mobile=+441111222222&group=d" width="1" height="1"/>
BUT, I do not know how to get my JavaScript to fire in the asp.net page when it is hit? I know I need to do something with RegisterStartupScript but how do I get all that JS into it and how do I get it to fire when the page is hit. I know how to return an img/gif using response headers, so I am cool with that.
Help greatly appreciated! :)
Call the JS function from your Page_Load event in code behind. This will fire every time the page is loaded.
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(Page, GetType(), "myFunction", "myFunction();", true);
}
JavaScript
function myFunction() {
//Code you want to run from document.ready
}

Calling a jQuery Function from code behind

I want call jQuery Function from code behind because I must send variable for function.
I Used this code in code behind :
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "ValidateTB("+ num+ "," + count +");", true);
And my function is :
function ValidateTB(num,count) {
var check = false;
alert("alert");
for (var i = 0; i < num; i = i + 1) {
check = false;
for (var j = 0; j < count; j = j + 1) {
var id = "myTextBox" + i + j;
if ($("input[type='text']").val().length > 0) {
check = true;
}
if (check == false) {
$("#error").text("error");
return false;
}
}
}
return true;
};
Why my function doesn’t work? It sounds my function doesn’t run
Make sure that this function is declared in a <script> block which is in the <head> section.
Your code should look like this.
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "return ValidateTB("+ num+ "," + count +");", true);
Your jquery function return true or false value, so you have to write "return" when you will call your function.
While calling any jquery code from codebehind make sure, you surround your code with $(document).ready. You need to change your codebehind call to below:
ClientScript.RegisterClientScriptBlock(this.GetType(), "myfunction", "$(document).ready(function(){ValidateTB('"+ num+ "','" + count +"');});", true);
Use RegisterStartupScript instead
Documentation
Suppose we have the following jquery class "ChangeDate" with some properties and an OnSelect event which will be invoked during selection,then if we want to use this class in codebehind and change it,then one way is to take a stringbuilder and do as follows,
$(document).ready(function () {
$('.ChangeDate').datepicker({
beforeShowDay: $.datepicker.noWeekends,
changeMonth: true,
changeYear: true,
dateFormat: 'mm/dd/yy',
yearRange: '-100:+100',
showButtonPanel: true,
onSelect: function (date) {
sMsg = sMsg + getErrorMessage('HME0002');
if (confirm(sMsg) == true) {
$('.ChangeDate').val('As of ' + date);
$(this).datepicker("hide");
return true;
}
else {
$('.ChangeDate').val('As of ' + oldD);
return false;
}
}
}); });
Taking StringBuilder in codebehind and append to it the function which is required and calling it using RegisterClientScriptBlock as follows
StringBuilder sb = new StringBuilder();
sb.Append("$(document).ready(function () {");
sb.Append("$('.ChangeDate').val('As of " + DateTime.Now.ToString("MM/dd/yyyy") + "');");
sb.Append("});");
BuildJSString("KEY", sb.ToString());
private void BuildJSString(string keyStr, string scriptStr)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), keyStr, scriptStr,true);
}

How to change a javascript function's parameter from callback function

I have an HTML input element generated by the server and it looks like this:
HERE IS THE SERVER SIDE
"<input id='" + cRoadList.getRoadListNumber() + ",start_km' style='' type=\"text\" value='"+ cRoadList.getStartKm() + "' onkeypress='handleRoadListDataUpdate(\""+cRoadList.getStartKm()+"\")'
As you see the attrbutes of the input element are generated dynamically but that is not the case so let's simplify it by putting some static data like this:
"<input id='myID' style='' type=\"text\" value='100' onkeypress='handleRoadListDataUpdate(\"100\")'
The most important part of this HTML input element is the onkeypress event which calls the function handleRoadListDataUpdate
HERE IS THE CLIENT PART
function handleRoadListDataUpdate(oValue) // The function accpets the old value of the *input* element
{
var event = handleRoadListDataUpdate.caller.arguments[0] || window.event ;
var keyPressed = event.keyCode;
if(keyPressed == 13)
{
var roadListNumber = event.target.id.split(",")[0];
var inputId = event.target.id.split(",")[1];
var nValue = event.target.value;
if(nValue != oValue)
{
var userAction = confirm("Are you sure you want to change this value?\nPrevious value: " + oValue + "\nNew value: " + nValue);
if(userAction == true)
{
var url = "/GBS/RoadListController";
var params = "type=updateRoadList&roadListNumber=" + roadListNumber + "&updateData="+inputId + "&newValue="+ nValue;
dhtmlxAjax.post(url,params,function(loader)
{
var xmlDoc = loader.xmlDoc.responseXML;
var sqlResponse = xmlDoc.documentElement.getElementsByTagName("response");
var result = sqlResponse[0].getAttribute("value");
if(result == "sql_error")
{
alert("The operation could not be completed because of an network error!");
event.target.value = oValue;
}
else if(result == "sql_success")
{
alert("The operation completed successfully!");
//Change the parameter oValue of the parent function
}
});
}
else
{
event.target.value = oValue;
}
}
}
}
Basically this function is about updating (using ajax) the database with the new value the user enters inside the input element and press key Enter. If the parameter oValue is different than the parameter in the input element an ajax request is made so the database can be updated with the new value.
When the operation completes we have the new value in the input element (which is entered by the user) but the problem is that if he press Enter again the function get executed AGAIN because its parameter oValue is not changed with the new value.
So my very question is:
How to change the handleRoadListDataUpdate() function's parameter oValue to become the same as nValue so if the user press Enter by accident the function does not execute the ajax part again?
P.S.
Please no jQuery code! Only pure javaScript!

Javascript Redirect with SetTimout Not Working

Can't seem to get this javascript redirect to work?
Suggestions?
Should I maybe do it with a meta refresh and how?
// If we have a successful location update
function onGeoSuccess(event)
{
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
var redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
}
// If something has gone wrong with the geolocation request
function onGeoError(event)
{
alert("Error code " + event.code + ". " + event.message);
}
function redirect()
{
window.location = redirectUrl;
}
setTimeout(redirect,15000);
The problem is the scope of redirectUrl variable. You declared redirectUrl as local for onGeoSuccess function, so it will be visible only inside of it. For workaround ,you can put all this stuff:
function redirect()
{
window.location = redirectUrl;
}
setTimeout(redirect,15000);
inside of onGeoSuccess function, or make redirectUrl global, by removing var before redirectUrl:
redirectUrl = "track.cfm?track=s&Lat="+...
//^-----no 'var'
Declare redirectUrl in parent scope, and run onGeoSuccess function.
var redirectUrl;
function onGeoSuccess (event) {
document.getElementById("Latitude").value = event.coords.latitude;
document.getElementById("Longitude").value = event.coords.longitude;
document.getElementById("location").href = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
redirectUrl = "track.cfm?track=s&Lat=" + event.coords.latitude + "&Long=" + event.coords.longitude;
}
function onGeoError (event) {
alert("Error code " + event.code + ". " + event.message);
}
function redirect () {
window.location = redirectUrl;
}
onGeoSuccess(...);
setTimeout(redirect, 15000);
Two problems:
1) The redirect URL is being set by a function which, at least from the code you posted, is not being called
2) Even if it was called, redirectUrl is a local variable to that function, so the timeout cannot access it.
Always check the error console.

Categories

Resources