how is document.form.submit() received in code behind? - javascript

I have document.form1.submit() in javascript. I want to know how it's received in code behind. In which class, in which method? Something like that. Coz I want to get the value inside a textbox to store it in session. And do i need an actual "submit" button for this to work? This really confuses me.
If i put it like this:
function CallSubmit() {
var thetext = document.getElementById('textbox1').value;
document.form1.submit(thetext);
}
will I be able to pass the value of textbox1 to a specific method in code behind if it has, like, a receiving variable? I mean, how do i get the value of textbox1?
By the way, I'm trying to do this before the page unloads. Because I need to store the text from textbox1 so that I can re-assign that value back after the page refreshes.

You can get the post back values on code behind using the 'Form' as
Request.Form["textbox1"]
and if you read this Request.Form you get all data from post
Comments.
In asp.net we general avoid to use direct the Request.Form and we use asp.net controls that all ready handle the post values.
For example if you use an asp:TextBox with ID=textBox1 then you read the post from textBox1.Text
and if you like to read it using the Request.Form you need to call the Request.Form[textBox1.UniqueID]
The textBox1.UniqueID is the name value on the html control, and the name used for the post back.

Related

my jQuery parameter is not recognized by the C# method in which is accessed in script area

I tried to access the my C# method in my JavaScript, but this method is not accepting the local parameters and saying, the parameter does not exist in the current context.
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber));
The above typeofServiceNumber is not recognized by the method
Razor code is executed server side before the HTML is returned in the response stream.
Javascript is executed client side within the resultant HTML.
Therefore you cannot pass a Javascript variable through to a Razor method, and you receive the message that typeOfServiceNumber is not recognized.
To be recognized, it would either need to be handled server side via data being passed to the View (ViewBag, Model etc), or it would need to be declared and assigned to within Razor tags on the page itself.
EDIT: to clarify the last point:
var typeofServiceNumber = $("#serviceType").val();
#MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber))
The first line you have here is all happening in the browser of the end user.
The second line is all happening on the server. You see the error message because you are trying to pass "typeofServiceNumber" to your method, and the variable isn't even declared at that point.
Without knowing exactly what you're trying to achieve it's hard for me to give a precise answer as to how to solve your problem. But here are two possibilities:
1) You know what $("#serviceType").val() is going to be before you serve the web page to the end user because that value is being set server side.
Controller:
public ActionResult MysteryController()
{
...your code here to work out what the service type is...
ViewBag.serviceType = serviceType;
return View();
}
View:
...lots of lovely html and such...
<script>
#MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
</script>
I can't see what the output of #MyStaticClass.StringEncoding() is but I have to assume at this point that it is doing whatever it is supposed to do.
Although the logic is split between the controller and the view, all of this is happening server side.
The second half of my point "or it would need to be declared and assigned to within Razor tags on the page itself." refers to the fact that one variation of this method could involve manipulating data in the View itself by enclosing it in a Razor code block like this:
#{
var typeofServiceNumber = #MyStaticClass.StringEncoding(Convert.ToString(ViewBag["serviceType"]));
}
The alternative, which I did not really address originally is:
2) You don't know what the value of $("#serviceType").val() is going to be before the page is loaded because it is being set by the end user and your function needs to be used before the data is submitted to the server:
If that's the case then #MyStaticClass.StringEncoding(Convert.ToString(typeofServiceNumber)) is no good to you, you will have to replicate the function in JavaScript and include it in the webpage itself.

jQuery ajax parameter value pulled dynamically

Wondering if there is someway to do this without using a timeout.
Right now I have an ajax request that pulls in a token via an external js. I don't have full control over this script as its provided by a 3rd party.
So it basically does an ajax request and passes me back a token vaule. I then take that value and update a form input with it.
My problem is the form submits before it has time to fully get value, hence the value is never passed.
I have some responses to work with that this 3rd party script provides, right now I am doing something like.
resonseData is passed back to me from this script..
if(responseData.dataValue !='') {
$('[name=payment_token]').val(responseData.dataValue, function(){
$("#userPaymentUpdate").submit();
});
}
^ The problem is the form submits before it has time to update the $('[name=payment_token]').val()
Is there anyway way round this aside for putting a timeout in? I thought by adding a callback like above would solve it, but apparently it doesn't.
I also have event.preventDefault(); on the form click handler, but when thats enable the 3rd party script wont execute at all. So basically need to only submit the form if that payment_token value has been updated.
If I'm reading this correctly, it looks more like an issue of order. responseData.dataValue has the value, otherwise that if condition wouldn't have processed.
Your code should look something like this:
if(responseData.dataValue !='') {
$('input[name=payment_token]').val(responseData.dataValue); /* I'm guessing you're using a hidden field for the payment token. */
$("#userPaymentUpdate").submit(); /* at this point, the value will have already been assigned. */
}

Safe way to store data for button clicks

I am trying to find out what the safest way to store data for use when the user clicks on a button.
I know that you can store data in attributes(either the value attribute or a data- attribute) of the button tag like so:
<button type="button" value="1" data-value="1">Click me!</button>
But the problem with this is that the user(probably really only advanced users) can manipulate the value with firebug or some other app and THEN click the button and send over different data. I fully understand that I need to check the input before I try to do anything with the sent data.
I also found out that I could use jQuery's .data() to attach data to dom elements, which seems a bit more useful. I'm not exactly sure how the data is stored, but I assume its harder to manipulate.
What got me really interested in this question was when I was looking through Soundcloud's code in firebug, I saw that none of the "like" buttons had data attached to the buttons. I tried deleting/manipulating elements/data and the buttons still worked. So it got me thinking that they are probably using a similar process to what jquerys data() is doing.
I just want to know if there is a safer way to store data or a way so that the user can't manipulate the data before clicking the button.
Consider this function:
function setupPrivateData(element) {
var private = 1;
element.setPrivate = function ( d ) { private = d; }
element.getPrivate = function ( ) { return private; }
}
When called with some DOM element it will add two methods to it: .setPrivate(val) and .getPrivate().
These are the only methods that will allow you to access and modify that private variable associated with the element.
The user can always manipulate data. Nothing stops an advanced user to access object properties or call a jquery.data() on their own.
Something you could do in vanilla js would be:
var div = document.getElementById("test");
div.something = "hidden value";
div.addEventListener("click", function() {
alert(this.something);
});
<div id="test">click me</div>
The best way would to be a serverside verification if the sent data is valid or not.
Besides that, you could try to wrap your code in an anonymous function to deny the user access to the object:
(function() {
var data = {};
data.something = "test";
})()
But even that fails as soon as the user manipulates your files and adds for instance a debugger statement.
You can obfuscate your javascript but the only validation has to be done on your server. For example, I tried to get the weather from theweathernetwork. They have hidden their API call using multiple files and callbacks. In my opinion, it's just more challenging (funnier) if you want to reverse-engineer their site.
Javascript can't be secure. Never trust user input
If you are logging button clicks, the safest way to keep track is to save and validate on the server side.
For example, when you click a like button on Soundcloud, it makes an HTTP request to Soundcloud's server, records that you clicked the button, and marks it as a favorite. This way, if the same user clicks the button anytime in the future, it can check before incrementing the number of favorites.
The number displayed in the button is also pulled in from the database when the view is rendered.
This is a huge topic, and you have a lot to learn, far too much for a comment here. Anything "stored" in an attribute in the HTML source is absolutely not secure, it can be changed very very easily.
The most common way of dealing with this would be to use a cookie, but even with some effort these can be manipulated.
If security is important, find some way of identifying your users (possibly by IP, but even that isn't fool proof!) and keep the data on your server, linked to a user ID which can be retrieved after the button is clicked.

PrimeFaces get the current page number on page change event

I have a primefaces datatable.
I need to know the current page number on page change event using client side API.
I am using,
<p:ajax event="page" oncomplete="myFunction(usersWidget);"/>
Inside myFunction() i have
debugger;
console.log(usersWidget.paginator.getCurrentPage());
The problem is, callbacks inside oncomplete of page event are called before the new page is set (PrimeFaces.widget.Paginator.setPage) on the paginator. I traced this with the debugger.
That being said, i would get the previous page number i was on and not the current page number, inside oncomplete callback.
If i could get a callback after the page is set after i click the page link, i would know the current page.
EDIT: Docs say that its a callback called after ajax completion and after DOM is UPDATED.
then what could be potentially wrong?
Pointers please?
Its strange , cause oncomplete being called after the page was updated...
How about calling oncomplete="myFunction();" without passing the parameter ?
You might be passing the old object (with outdated information) that way... the usersWidget is global variable anyway... ans should be present in your js file
Since it seems that client side api is not synced with the right values
As a workaround you could try to pass the page value from server like this
DataTable dataTable = (DataTable)
FacesContext
.getCurrentInstance()
.getViewRoot()
.findComponent("someOformID:someTableId");
or try, instead of the line above,
PageEvent.getPage(); //PageEvent is an argument to you listener
myPageHolder = dataTable.getPage();
Than place this value to bean property and put it inside some hidden value in xhtml , than update that hidden value with p:ajax update and access it from within js

Javascript and session variables

I have a database that stores events in it and a page with a calendar object on it. When rendering the days it looks through the months events and if any match the current day being rendered it creates a linkbutton to represent the event in the day on the calendar and adds it to that cell. I add some javascript to the linkbutton to change the window.location to a page to view event details passing EventID in the querystring ( I tried setting the postbackurl of the newly created linkbutton but it wasnt causing a postback... no luck). I need to set a Session variable ie. Session("EditMode") = "Edit" So the new page will know it is to get an existing event info rather than prepare to create a new event? Any SUGGESTIONS?
Your session vars are controlled by the server,
JS runs client side, and as such cannot modify the vars directly.
You need to make server requests using POST or GET and hidden
iframes, or XMLHTTPRequest() calls to send data from the JS to
the server, and then have your server side code handle the vars.
Add another query string variable that the page can use to trigger existing vs new.
Add another query string variable that the page can use to trigger existing vs new.
If you are using something like Struts2, you can have a hidden variable in your jsp
<s:hidden id="EditModeId" value="%{#session.EditMode}"/>
And within javascript simply access this variable
alert(document.getElementById('EditModeId').value);
You definitely need to add a variable to the target page. But I take it that you are doing a popup scenario, so you should be able to create a javascript function OpenWindow() and fire it off when the user clicks the link.
<script>
function OpenWindow(eventId, editMode)
{
var window = window.open("popup.aspx?eventId=" + eventId + "&editMode=" + editMode);
}
</script>
On the server side you need to build the call to the OpenWindow function. For example:
onclick="OpenWindow(eventId=" + row["eventId"].ToString() + "&editMode=" + editMode.ToString() + ");"
So in other words, prep everything on the serverside to set your javascript to post all variables to the new page. Hope this helps.
var page1 = document.getElementById("textbox").value;
sessionStorage.setItem("page1content", page1);
in other page use this value as like session variable
document.getElementById("textbox2").value=sessionStorage.getItem("page1content");

Categories