Using ASP.Net session in Javascript - javascript

I have to process an operation in Javascript using data stored in session (System.Web.HttpContext.Current.Session["Filtre"])
Is it even possible to catch and do operation in Javascript using the asp.net session ?
I already tried some sample like this one without success :
var f = '<%=Session["Filtre"]%>';
In the case where this is impossible (for security issues I guess), is it possible to call a aspx.cs function in javascript who will perform the operation ?
Have a good day.

You cannot mix client side javascript and server side code (such as sessions). The processes do not run at the same time.
Your code
var f = '<%=Session["Filtre"]%>';
could work, BUT:
First the server needs to execute the <% %> block to generate a string, which is placed in some text
That text is sent to the browser, possibly as part of a page
Only in the browser it is interpreted and executed as javascript
There is no easy way for the browser to execute random server side code.
Complicated ways use AJAX calls to call specifically designed methods on the server (instead of arbitrary code).

using <scriptmanager> you can do
Please go through the below article
http://www.codeproject.com/Articles/525364/AJAX-for-Beginners-Part-3-Calling-Server-Side-Meth

Yes, your JavaScript can call a C# method if you annotate the method with WebMethod. This makes the method callable from remote Web clients (i.e. it becomes a 'page method'). MSDN.
You would need the EnableSession property set to true in order to use the Session. Example:
[WebMethod(EnableSession=true)]
public static int Example() {
...
Then call the page method from JavaScript, probably using jQuery.
$.ajax({
type: "POST",
url: "MyPage.aspx/Example",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{ }",
error: function (XMLHttpRequest, textStatus, errorThrown) { alert(langError + " " + textStatus); },
success: function (msg) {
alert(msg.d);
}
});

Related

How to call a Javascript function inside a Jade/Pug file

I have a node.js project with frontend written in Pug. On the pug side I have written a Javascript function that is making an Ajax call and returning a string, I am trying to call this function inside that same pug file but it gives me a function not defined error. Can anyone please help with this?
header(class="global-header")
p Current Status: #{getCurrentAvail()}
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data){
console.log("===1")
currentAvail = data.message
console.log(currentAvail)
return data.message
},
error: function(data){
console.log("Error function avail");
}
});
}```
It appears you have some piece of external data and you want that data to show in a rendered web page. You have two basic choices here:
1. Server-side fetching and rendering of the data. You can have your server get the data before rendering the page and pass that data to your template engine so your template engine can insert the data into the page at the appropriate place.
2. Client-side fetching and insertion of the data. You can call the getCurrentAvail() function from within a <script> tag in the web page. This will send the rendered web page to the browser. As it loads, the browser will then execute your script, fetch the data from your server and then you would use DOM APIs in the browser to insert the result of that ajax call into the web page to make it visible to the user in the page.
Also, please note that your function getCurrentAvail() has no return value at all. You aren't returning anything from the outer function. Your return data.message is inside the asynchronous success callback so that just go back to nowhere. If you're going to go with the client-side option #2, then you can just put the DOM manipulation code right into the success callback function.
Your current code is attempting to do 1/2 server and 1/2 client and that is not something that will work.
At all times, have total clarity on what is in the server and what is in the client. Ajax methods run in the browser. A #{variable} construct exists only in Pug, and the substitution occurs on the server.
I think this is what you need:
header(class="global-header")
p Current Status:
span#status
script.
function getCurrentAvail(){
$.ajax({
url: "/admin/account/accountAvailability",
type: "GET",
contentType: "application/json; charset=utf-8",
async: false,
success: function(data) {
document.getElementById("status").innerText = data.message
},
error: function(data){
console.log("Error function avail");
}
});
}
getCurrentAvail();

C# function called in javascript and it's execute before the page load. why?

I tried to call c# function in javascript so i used this: var a = <%=MYC#FUNCTION()%>, but the function in the weird brackets execute even before my page load. like executing the function is the top priority of my code.
i want the function to execute when i am calling it in my javascript code.
Please help me, i need this for my project in school.
i tried to use this but i didnt really understood this ->
<script type="text/javascript"> //Default.aspx
function DeleteKartItems() {
$.ajax({
type: "POST",
url: 'Default.aspx/DeleteItem',
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#divResult").html("success");
},
error: function (e) {
$("#divResult").html("Something Wrong.");
}
});
}
</script>
[WebMethod] //Default.aspx.cs
public static void DeleteItem()
{
//Your Logic
}
You are misunderstanding the life cycle of the request/response. In your code, the order of execution will be
Web browser sends a request to your web server.
Web server (C# code) now handles the request and start creating HTML response.
Web server uses your controller/view (MVC) or .aspx/.aspx.cs (web form) to create the response.
Your code "MYC#FUNCTION()" is now executed. Let assume it returns a number 123.
After this, your html response is sent back to web browser.
Web browser receives the response and display to UI. Now, if you inspect HTML you will see "var a = 123;" (123 coming from your "MYC#FUNCTION()")
If you want to execute "MYC#FUNCTION()" after page load. Then you need to look at AJAX.

Send log errors to a file

I developed a website for my graduation however it still only one thing I have do. What I want is when the script is installed on a website I want to send the name of the website who has installed my script, also whenever there is an error I want to send it to my website so for example:
This website installed my script
www.security-dz.com/myscript
I want to see the path + website in an other file in other website. For example:
www.getlog.com/mylogs.php
The purpose of this is keep my customers update and give them support and see the errors that happen so I can fix them in next updates.
You might want to take a closer look at the JQuery docs for ajax requests, so you can use a secure http connection for logging. This javascript code basically describes a function that sends the errors in text-format to your server-side script. This script can in turn write the error description to a file on the server. I'd recommend using a DB instead; That way you can easily write a web-client that displays all reported errors (and filters and the other good stuff).
You can extract the origin url from the referer [sic] field in the ajax http get-request on the server.
(function () { // function operator, in case console doesn't exist
!console ?
(console = {}) : console;
!console.log ?
(console.log = function () { }) : console.log;
!console.info ?
(console.info = console.log) : console.info;
!console.error ?
(console.error = console.log) : console.error;
}());
// Uses JQuery
function reportError (errDesc) {
var path = "www.getlog.com/mylogs.php";
$.ajax({
url: path,
type: "GET",
async: true,
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
crossDomain: true,
data: errDesc,
dataType: "jsonp",
error: function (req, type, errObj) {
console.error("Reporting error failed: " + type + "\nAt url: " + path + "\n" + errObj);
// In case you need to debug the error reporting function
},
succes: function (res) {
console.info("Reported error to server:\nRequest:" + errDesc + "\nResponse: " + res);
// extra error logging facility on client-side, invisible to most users
},
global: false // prevent triggering global ajax event handlers
});
return errDesc; // in case you want to reuse the errDesc
}
Code has been validated with jshint. Please let me know if there are still issues, because I didn't take the time to completely replicate your setup (setting up 2 different domains etc.)
Addendum: Some useful reading if you're having issues with cross-domain messaging, JSON is not a subset of javascript, Cross-origin resource sharing, JSONP.
What you could do is post both the name of the website that uses your script and the error code variable with AJAX through URL to your logging website, which will then get the variable and name from the URL and use these to add to your log.
You should, however, by using this tactic, also make use of some URL validation, otherwise this will leave you wide open to injection attacks.
it is easy when your script installed , get the site info and send by socket and http request with get method and then recive it on your server.
for errors, php has some method to control error logs so custom it.

JQuery server side method call internal

i often call my aspx server side method with the help of jquery....like
$.ajax({
type: "POST",
url: "login.aspx/Authenticate",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
sHtml = data.d;
if (sHtml != "") {
alert(sHtml);
location.href = sHtml;
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
but the funny things is that i dont know how jquery call my static method from outside.
i saw that when i call my server side method then page_load does not fire but in case of updatepanel partial postback page_load execute first.
so i want to know the internal logic of jquery that how it can call server side method directly........looking for good explanation. thanks
so i want to know the internal logic of jquery that how it can call server side method directly
It can't.
jQuery can cause the browser to make an HTTP request to a URI.
The server can run code in response to a URI being requested in order to decide what content and headers to return.
What happens in jquery case is that the method is marked as webmethod which means that it works as an endpoint for an httprequest as if it is a webservice and when you do that, then the jquery make a httprequest to this method as if he is calling a webservice.
this URL will give you a deep view on what happen when you are making any ajax call http://msdn.microsoft.com/en-us/magazine/cc163499.aspx
your server side methods are marked with the [WebMethod] attribute, right? this attribute exposes the method as an xml web service.
http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.71).aspx
since this autogenerated "webservice" has nothing to do with the page, page_load is not called.

use javascript variable into python Block

I want to use JavaScript variable into python Block.
<script>
$(document).ready(function() {
$("#WO_cpp_id").change(function() {
id = this.selectedIndex;
ajax('{{=URL(r=request,f='get_CIs',vars={'CPP_Id':'#here I want to use id variable')}}', ['WO_cpp_id'], 'WO_ci_id');
})
.change(); }); </script>
Thanks in Advance
Your python code is running on the server. Your JavaScript code (as quoted) is running on the client. So you can't directly use a JavaScript variable in your Python code. What you do is send the data you want to send from the client to the server in any of several ways.
One of those ways is "ajax". This client-side code will send the contents of the variable foo to the server as a "fooParameter" parameter on a POST:
var foo = "This is some information";
$.ajax({
url: "myscript.py",
method: "POST",
data: {fooParameter: foo},
success: function(responseData) {
// Successful POST; do something with the response if you want
},
error: function(jxhr, statusText, err) {
// Error, handle it
}
});
More in the jQuery docs and the Wikipedia article on ajax.
That won't work. Python runs on the server before the page is ever rendered on the client; Javascript runs in the browser after the page is rendered. The id variable isn't even set when the Python code runs.
Instead, you should have your javascript code add the extra data you want to set to an existing query string (or by using the data attribute of jQuery's ajax options).

Categories