Javascript Variable to C# - javascript

I have a question about getting Javascript Variables from a local PC JS File to a Local C# Program.
I'm writing a C# Program for the PC which needs some Variables from a Webpage which is locally located on my PC with just HTML CSS and JS which is displayed in a webview function in my C# Form.
Now I'm reading a Value from the User in my "Webpage" and want to pass this variables to my C# Code so I can use this variables further.

There are at least two ways to get any variable from a browser to your backend. One is to Post a form that contains the variable. The other is to make an AJAX call to send the variable data to some backend service. The AJAX call would, in most cases, be the way to go since no screen refresh is done and involves no interaction or initiation from the user.

use below code :
HTML and Javascript :
<head runat="server">
<title></title>
<script type="text/javascript">
function HandleIT() {
var name = document.getElementById('<%=txtname.ClientID %>').value;
var address = document.getElementById('<%=txtaddress.ClientID %>').value;
PageMethods.ProcessIT(name, address, onSucess, onError);
function onSucess(result) {
alert(result);
}
function onError(result) {
alert('Something wrong.');
}
}
</script>
Code Behind :
[WebMethod]
public static string ProcessIT(string name, string address)
{
string result = "Welcome Mr. " + name + ". Your address is '" + address + "'.";
return result;
}
More information :
C# functions returns a value and show in webpage

Related

Razor page javascript execute c# only once

I'm trying to use a javascript loop to update data from my c# code. But it only execute the c# method once.
I made a test class :
public class testClass
{
public static int result;
public static int nb1;
public static int add()
{
result = result + 1;
return result;
}
}
And in my javascript I made this :
<script>
setInterval(Testing,3000);
nb1 = 0;
function Testing() {
nb1 = nb1 + 1; //this is to test that the function really restart after 3 seconds
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
}
And it display this on the page :
this is what is displayed on my html page
As you can see the number that show if the javascript function is restarting after 3 seconds works, but the c# method is not updating.
Do you have any solutions ?
It seems like you don't really have an understanding how HTML, JS and C# work in unison.
When a request is made to your server, It will perform calculations to return a document. This document is presented in HTML, with added logic in the form of JS to compliment it.
When using Razor, you can effectively use C# to help building the document, but not at runtime. If you want your front end document to be able to interact with the backend C# code, you are bound to using sockets(for example SignalR), or AJAX(which would be the most prominent way of asynchronous communication between a web page and a back end).
I will help you understand by stepping through the code with you..
Your razor page will start building. at one point it will detect the following line:
document.getElementById('label').innerHTML = nb1 + " | " + #testClass.add(); ; // calling my c# method and print into a html label
this is where it will call on the C# method, convert it to a value, and put the value in the JS code, so when the document gets sent to the client (your webbrowser) the code will look as follows:
document.getElementById('label').innerHTML = nb1 + " | " + {THE CALCULATED VALUE} ; // calling my c# method and print into a html label
I will refer you to this answer. Where it is explained how to do what you are trying to do.

Sending array from php to javascript, parsing PHP variables to JS

I want to be able to pickup variables from php example: public var $PHPVariable = "Hello World"; or something in that way. But how will I possible send this to javascript without XML HTTP(S) requests?
PHP File example
<?php
public var $secure_connection = $secure['ssl']['type']['connection']['valid_id'] // This is equal to (int)25
public var $userRank = $_SESSION['user']['active']['secure']['rank']; // Returns Admin or Default
public var $userFullName = $_SESSION['user']['unactive']['secure']['require']['name']['first'.'middle'.'last']
?>
JavaScript file / document
function get(variable, type){
if(!empty(variable) && !empty(type)){
if(!exist(variable)){ // the exist function will check if the public variable exist in the php setting file.
return 'The variable does not exist!';
}
if(type=='output'){
return recieve(variable, 'As String'); // the recieve function will collect the data from the public variable.
}
if(type=='setting'){
return recieve(variable, 'As Setting') // returning the recieve function as a setting will basicly mean it can return anything such as string/array/integer/boolean
}
}else{
return 'ERROR: Please fill in required fields!';
}
}
if(get('secure_connection', 'setting')==25){/* Returns true */}
if(get('userRank', 'setting')=='Admin'){/* Returns true */}
if(get('userFullName', 'output')){/* Returns the variable as a string no matter what the php variable was in ex int/boolean*/}
Take in mind I want to do this without XML http(s) requests!
Thanks for taking your time help! Richard.
EDIT
I know it is possible sending JSON Requests to a PHP Object class, which could solve this solution but it is not secure enough for my website, though it allows the user to even edit their own rank into other ranks or change SQL Connection properties of databases and change the row values, etc. Just with enough knowledge of using the (example) Chrome Console to use the function to change the php files content. Which will result resolving no ones problems.

How can I access Session variables in code-behind

In script I set Session.
<script>
$(document).on('click', '.Pagination', function () {
'<%Session["Pagination"] = "' + $(this).attr('id') + '"; %>';
alert('<%=Session["Pagination"] %>');
});
</script>
Alert works.
I can't access When i want to session from code-behind
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Val = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
String Val equal to ' + $(this).attr('id') + '
I used to put the value in the hidden variable and this will be accessible in code-behind, anyway the session object is active in code behind you can set the variable to session successfully.
Advantage:
Globally declared session strings are accessible in code-behind and you can use the variables by calling the property files
ASP
<asp:HiddenField id="session_obejct" runat="server" />
Javascript
document.getElementById('session_obejct').value = "Variable you want to set in session";
C#
session["SESSION_NAME"] = session_obejct.Value;
you can use other methods as well, I hope this will meet your requirement
I used this way and do it if one have better way pleas tell me
Javascript function:
<script>
$(document).on('click', '.Pagination', function () {
PageMethods.NumPagination($(this).attr('id'));
});
</script>
Code behind :
[System.Web.Services.WebMethod]
public static string NumPagination(string Num)
{
Page Pagination = new Page();
Pagination.Session["Pagination"] = Num;
return Num;
}
if (!string.IsNullOrEmpty(Session["Pagination"] as string))
{
string Select = "1";
Select = Session["Pagination"].ToString();
Session["Pagination"] = null;
}
LINK
You cannot write to the (server-side) Session from within client side code.
The alert('<%=Session["Pagination"] %>'); works because it is executed server side first, reading the value of Session["Pagination"] and inserting that into the javascript source, before sending that source to the browser.
By the time the browser sees that text and interprets it as javascript, the server-side commands (<% ... %>) have been replaced. The browser wouldn't know what to do with them anyway.

passing a value from one file to another javascript

I have a file called functions.js where I have the functiom sum which computes the score that a student takes at a test. I want that sum to be printed into a table in the file admin.php so that the administrator sees all the scores that each student has.
So how can I pass the sum variable to another file? I tried calling the function using the onlick action but that didn't work
I guess you probably want something like this
document.getElementById('saveScoreButton').onclick = {
var r = new XMLHttpRequest,
message = document.getElementById('message'),
score = sum();
message.innerHTML = 'Saving your score; please wait a second';
r.open('get', 'savescore.php?score=' + score, true);
r.send(null);
r.onreadystatechange = function () {
if (r.readyState == 4 && r.status == 200) {
message.innerHTML = 'Saved your score';
}
}
}
This passes the score to a PHP programme savescore.php when you click a button with id saveScoreButton. The PHP programme then has to retrieve it using $_GET["score"].
Note that this would be easy for the user to trick if they understand javascript and see what is happening. They could just type 'savescore.php?score=100' in the browser's address bar. If you want a secure solution the javascript should only pass the user's answers to the PHP programme, which would then mark the test and sum the results.
It is also possible to use the POST method instead of GET to pass a value:
...
r.open('post', 'savescore.php?score=' + score, true);
r.send('score=' + score);
...
Then pick it up in the PHP programme using $_POST["score"].
As mentioned in comments, if you want to compare/tabulate scores, then savescore.php will need to store the values in a database or file so that they can be retrieved by admin.php.
Javascript is ran client-sided, PHP is ran server-sided. Therefor, you have to code something in your javascript which alters the HTML page returned by the PHP script, displaying the result.
Once all of your files are loaded on the client, there isn't a concept of separate js files. The client (browser + javascript) and server (php) are 2 separate entities. When your data is one place the other has no clue it exists. Either research ajax as a method of communicating between the 2 locations or use a form and submit the page to the server.
Good overview of how the server and browser communicate: How does the communication between a browser and a web server take place?
Basics of Form submission: http://www.htmlgoodies.com/tutorials/forms/article.php/3479121/So-You-Want-A-Form-Huh.htm
Basics of Ajax: http://webdesign.about.com/od/ajax/a/aa101705.htm
Ajax with PHP: http://www.switchonthecode.com/tutorials/simple-ajax-php-and-javascript

Calling server side function with parameter from Javascript in ASP.NET

I have an ASP.NET application in VB.NET. I have a Javascript function in mypage.aspx and another one in my callback.aspx page. I need this scripts to render and submit an IFrame on mypage.aspx.
When I click on the submit button:
<asp:Button ID="subbtn" Name="Submit" OnClientClick="onsubmit_action();" runat="server" />
this script is executed, where iframeId is the id of the IFrame:
function onsubmit_action() {
submitPage('iframeId');
}
The response of the IFrame (validation or success) is submitted to the callback.aspx file. I guess this happens through cross-site scripting that calls the callback function in the callback.aspx file;
function callback()
{
parent.pagecallback_success('<%=Request.QueryString("Id")%>');
}
that calls the function in mypage.aspx
function pagecallback_success(ref_id) {
var Url = "mypage.aspx?";
Url += "id=" + id;
window.location.href = Url;
}
The script works as expected. Now, I would like to call a server function
Protected Function Store(ByVal id As String) As Boolean
in mypage.aspx.vb and pass the variable id:
function hostedpagecallback_success(id) {
var Url = "mypage.aspx?";
Url += "id=" + id;
window.location.href = Url;
"<%= Store(id) %>"
}
The problem is that the compiler considers id as a server side function and gives a compile error. However if I use a sub (without parameters) instead of a function, the sub is executed 3 times, on page_load, when the IFrame is received and another time (connection is https cannot debug Javascript efficiently).
I am not good in cross-site scripting and code nuggets, probably it is really trivial but I do not know how to solve this problem. Anybody?
I think you are looking for page methods a feature of MS-Ajax. Put the [WebMethod]
on the method you want to call (server side) and call it client side with something like PageMethods.GetData(f, s, OnRequestComplete, OnRequestError);
The whole pattern takes an article to describe.
http://www.dotnetfunda.com/articles/article454-using-pagemethods-and-json-in-aspnet-ajax.aspx

Categories

Resources