ASP.NET call a Javascript function - javascript

I'm working on a project that uses IP Payments to process transactions. The project involves a web form written in ASP with Code-Behind written in C#.
IPP offers an iFrame implementation, where you can put an iFrame in your page and display a small IPP page with fields for entering credit card information. The idea behind this is that the credit card info will only be handled by IPP and never by the server running the page, thus there is no requirement to ensure that card data is kept secure.
In order to display the IPP page in the iFrame though, a session needs to be initiated with IPP. The server initiates the session, and passes in a SessionID variable. Upon a successful session initiation, a Secure Session Token is returned to the server. The server then needs to "force" the client's browser to GET or POST the SessionID and the SST (Secure Session Token) to the IPP website. This is where my problem is.
I wrote a Javascript function in the ASPX page that would accept two parameters - the SessionID and SST - and send them to the IPP website. I'm now trying to call this Javascript function from my C# code upon successful initiation of the IPP session. However, I have been completely unable to do so.
I've done a lot of searching, and the one answer I keep coming across is to use either RegisterStartupScript or RegisterClientScriptBlock. The problem is, these seem to insert text directly into the page, rather than calling an existing function. Assuming I inserted my function into the page via one of those functions rather than writing it into the page myself, it still doesn't solve my problem of how to call said function.
Now it is possible that I'm going about this the wrong way, and there's a much better way to get the client's browser to GET/POST the SessionID and SST; if so, please tell me. I'm inexperienced with web programming and am thus learning as I go and making up solutions along the way that are quite likely not ideal.
Thanks in advance.

I think this should work:
Lets say you have something like this in your HTML:
<html>
<head>
<script>
function sendValuesToIPP(sessionId, sst){
//do stuff
}
</script>
</head>
</html>
If you do this in your C# code it should work
ClientScriptManager.RegisterStartupScript(
this.Type,
"some_key_you_want_to_identify_it",
string.Format("sendValuesToIPP('{0}','{1}')", SessionID, SST),
true);
Keep in mind that I'm assuming you have SessionID and SST properties server side, you can get them from wherever you want and just add them to the string that will actually call the function when registered in your ASPX.

Related

How do I verify the user with AJAX after user logined?

I'm totally new to make a website with javascript AJAX. I want to provide every experience on my website with one domain(like Facebook), thus I made every page-changing method with javascript AJAX. At first, when you visit my website, you have to log in, after that it turns to the main page and you can go to several menus with clicking button which triggers page-changing method.
The problem what I faced is.. I've recently seen someone typed javascript code into the console to delete all of his(or her) photos on Tumblr instead of clicking all of that. The idea hit my head.
Every page-changing method in my website also can be called without login. Someone can input page-changing javascript code in the console without login and see the contents of pages.
The first idea came to my head to prevent this situation was, to send id/pw every time when I make a post request to the server and everytime server gets the request, server checks the id/pw to assign the browser to change page. For instance, when a user wants to go to menu A, he(or she) has to send his(or her) id/pw to see the content of menu A.
I thought this is such a bad idea. As I guess it will result overload in server CPU when the server always has to check id and pw(sorry, I don't know well about server CPU and process, this is just my supposition). So I guess there is another way to verify the user and their requests without sending id/pw every time.
Does anyone know about that? Or should I check id/pw with every post requests?
To answer you, you are talking about Cross Site Scripting. Let me first point you to some documents in order to make you aware of what you are dealing with:-
Its called Cross Site Scripting using which a user on the client side inject script in your website and change the different stuff on it.
https://en.wikipedia.org/wiki/Cross-site_scripting
Now to deal with such things there are remedies as following:-
CSRF Token
JWT
Both of them work in somewhat identical way but there are data and payload carrying capacity and encryption involved in JWT and I recommend that.
This is a very known problem in the community and is also pretty old.
On the other hand I will also recommend you to do a data sanitization before storing it into your database. Someone can easily input some JS in your site and you can be defaced in no time.
Have a look at this Sanitizing user input before adding it to the DOM in Javascript
Last but not the least. Stop exposing the functions in the Global level while writing JavaScript. Stop creating global variables and functions and rather use closures.
(function(){
var a =10;
var b = 20;
function add(msg){
console.log(msg)
return a+b;
}
add("I am calling from Inside the self executing function");
})();
add("I am calling from outside the self executing function");
Have a look at the code above and how it protects that add() method to be called from outside.
Hope this answers your questions.
Yes, on stateless scenarios you should send some client identification like a token and verify on the server. Don't worry about the performance :)
You could take a look to JWT: https://jwt.io/

How to send a variable from node server to javascript client on page load?

My webapp is 99% static except for the fact that on page load, I want to send to the client their username if they are logged in and the name of the room they are connecting to if they specify that in the URL. These two variables need to be accessed in the client-side Javascript. So I've been trying to figure out what feels like a simple task but I am having little luck.
Use templating engine.
Problem: Overkill because I only need it for one/two variables on an otherwise static page and I need to access it in the Javascript, not the HTML
Make an AJAX request after page load
Problem: Causes flickering because first the page loads and then the DOM updates a second or two later because have to wait for the request to be sent and received. Also it's not efficient because it requires a second request/response.
Use WebSockets
Problem: Same problem as above.
Send it in the header information on page load
Problem: Can't access header information in Javascript unless you do a weird hack which only works as a separate AJAX call. Could just use #2 for that.
So what I ended up doing was using cookies and this works, 100%. There's actually no problems with it currently I just think the code is very ugly and fragile and I'm looking for a better way. Here's a snippet of what the cookie solution looks like:
app.get('/room/:roomName', function(req, res) {
res.clearCookie('room');
if (req.isAuthenticated()) {
res.cookie('username', req.user.username);
} else {
res.cookie('username', '');
}
var roomName = req.params.roomName;
if (roomNameToRoom.hasOwnProperty(roomName)) {
res.cookie('room', req.params.roomName);
}
res.sendFile(path.join(__dirname, '../public/index.html'));
});
As you can see I grab the username from the request and validate the room and if it's valid, I send that back. I then parse the cookies with RegEx on the client side (very messy) and use those two variables in Javascript functions. I'm looking for alternative solutions that would allow me to send this all in one request while avoiding a lot of complexity and messiness.
Redirect to special URL, for example index.htm?var1=5&var2=6 and use location.search.substr(1).split('&') in JS.
Use embed js-file in html, for example <script src='ajax.js'></script>. In this example ajax.js is not cached and contains something like this:
window.var1 = 5;
window.var2 = 6;
It can be dynamically generated.
Use cookies.
By the way I don't think that using templates is bad. You can use javascript templates. It shoudn't be performance issue because templates are fast and you need execute just only one template. I would use templates.

How to pass javascript variables to rails variables

How can I pass a javaScript variable into ruby. I want to do something like this but I don't know how to express it.
function save(){
var g = document.getElementById("self").value;
<% #owner.info = g %>
}
Another possible work around is that i would need to be able to extract contents of a text area through rails and not javascript.
Can anyone help me?
What you are attempting to do doesn't make sense with a vanilla rails installation and javascript. Here's a good workflow that accomplishes what you're trying to do along with some details:
1. A page is requested from the server
The ruby code that runs rails and your application is executed on the server. The server receives a request, executes the ruby code, and sends the response as an html document.
2. A user gets the response from the server
The user's browser receives the html and turns it into a pretty web page. It's at this point that any javascript related to your application is executed in the user's browser. The connection with the server has been severed and no further ruby code will be executed until another request is made.
3. The user fills out an ajax form
On the page rendered in step 2, you have a form. Following this guide you can tell this form to submit via ajax. That means instead of requesting a new web page, the browser will send a special request using javascript to the server. The server can save the form values to your database and send a response back to the browser. All the while the user hasn't left the page they are currently viewing.
Alternatively you can skip the ajax and have the user submit the form, but you'll need to redirect them back to the page they were viewing (and probably adding a note the form they submitted was saved).

can't make window.location.reload() inside the ajax call

Problem
I am not able to refresh the page with window.location.reload() which is used inside the success call made to yahoo.
Any hints how it can be fixed.
The whole of the code is working fine it is making call to cse server getting contents from there saving on yahoo. but i have to manually refresh the page to bring the contents. I want it to be automatic so I used window.location.reload() but thats not working. Any suggestions how it can be done. The function below is actually a function for a button.
That's the problem, right there.
If your script is running from the CSE server's domain, you cannot send data to the yahoo server. This is javascript's main limitations. Likewise, if running off of the yahoo domain, you can send data to it, but cannot send data to the CSE server, unless it is part of the yahoo domain.
Would work:
Get data from blahblahblah.yahoo.com, then send data to somedomain.yahoo.com
Would not work:
Get data from blahblahblah.somesite.com and send data to somedomain.yahoo.com
Main point, if you're getting data from "csce.unl.edu" and running off of that domain (aka running your script in a browser window from that domain), you can only send data to a site that ends with ".unl.edu". So you can send or receive from "test.unl.edu", but not some yahoo site.
A solution:
Host a proxy script on some webserver, or write all of your code in PHP. Here is two great references on what a proxy script is, and the second link actually provides one for you:
Link 1
Link 2
Any more help needed, you can let me know, I had to set one up myself, on my server, and I can help you out if you run into problems.
did you tried:
window.location = window.location;

How far can I go with JavaScript?

I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.

Categories