Set Session value from JavaScript and Get Session value in C# - session

Is it available to set the value from javascript(Session / ViewState) and get the value in C# without using hidden field??
Its work to store the value from javascript , and available to get the value in C# (page.request["Token"]) , but its not working for me because there have a postback action " form.submit();"
function setToken(Token) {
try {
var form = document.createElement("form");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'Token');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} catch (err) {
}
}

If you want to submit a value from your clientside code to your serverside code, you'll need to submit it in some kind of request. A form post would be one way, but if you don't want the page to reload it could equally well be an AJAX request:
function setToken(accessToken) {
$.post('/SetToken', { Token: accessToken });
}
Using jQuery there as it'll save you a lot of the trouble involved in getting AJAX to work the same way across browsers.
In the example I'm posting a request to a page called /SetToken, which could be any url in your website where you have code that can update the token. Your own example submits a form without an action, which means it'll submit to the current page. You could easily do that as well
$.post(location.href, { Token: accessToken });

Related

Spring-Boot: Redirect and Refresh model and page

I have a spring-boot application, with theyemleaf. I repeatedly update the page, and redirect it to the same page, so i expect that the elements of the page get updated:
#GetMapping("/suggested-events/vote/{eventId}")
public String voteForEvents(Model model,
#PathVariable("eventId") Long eventId,
#RequestParam(value = "message", required = false) String message ) {
log.info("The message is: "+message);
SuggestedEvent event = suggestedEventService.findSuggestedEventById(eventId);
ArrayList<SuggestedEvent> events = suggestedEventService.findSuggestedEventsByArea(event.getArea());
model.addAttribute("mainEvent",event);
model.addAttribute("events",events);
model.addAttribute("message",message);
return "/suggested-event/vote";
}
and when a button get pushed in the view it triggers the below post method:
#PostMapping("/suggested-events/vote")
public String voteForASuggestedEvent(RedirectAttributes redirectAttributes){
log.info("You have made a vote");
redirectAttributes.addAttribute("message", "Success");
return "redirect:/suggested-events/vote/1";
}
This second controller method, performs an operation an makes a message, and redirects it to the first method. So, it successfully redirected to the first method and it logs
log.info("The message is: "+message);
but it does not refresh my page, and i do not get the message as model?
When i redirect to the first method, i expect it adds the message to my models:
model.addAttribute("message",message);
But it does not added to my page
and when a button get pushed in the view it triggers the below post
method:
It sounds like this trigger is using AJAX, rather than a form submit. Doing so would match the symptoms you describe.
If you POST to /suggested-events/vote using AJAX, the server will return a 302, and the browser will follow it. However, the response for that 302 is still the result of an AJAX call. You have access to it in your success callback, but the browser isn't going to render it for you.
but it does not refresh my page
If a 302 doesn't cause your page to re-render, this also suggests you're using AJAX.
If you actually use a form submit instead, the browser will re-render using the markup returned by the successful redirect.
This can be verified by using the following two buttons in your vote.html:
<form action="http://localhost:8080/suggested-events/vote" method="POST">
<input type="submit" text="Submit" />
</form>
<button onclick="postmessage();" >Button</button>
<script>
function postmessage() {
$.ajax({
method: 'POST',
data: {},
url: 'http://localhost:8080/suggested-events/vote'
});
}
</script>
The first button will work as expected, and the second button matches the symptoms you describe.
If you are already using a form, please update the question with it (or better yet, the entire Thymeleaf template).
I had the same problem as OP described and Mike's explanation brought me in the right direction.
I am reading a db-table and populating it with thymeleaf using th:each. I wanted to add a javascript-confirmation before deleting an item. Sending an ajax GET without an event-listener and reloading with location.reload(true) didn't reach the #GetMapping("/delete/{id}") in the controller.
This SO-thread gave me the answer to the ajax-call.
<a class="btn btn-danger" href="#" th:onclick="|confirmDeletion('${u.id}')|"></a>
<script th:inline="javascript">
function confirmDeletion(id) {
if (confirm("Delete this id? " + id)) {
var http = new XMLHttpRequest();
http.open("GET", "/delete/" + id, true);
http.addEventListener("readystatechange", function() {
if (http.readyState === 4 && http.status === 200) {
window.location.reload(true);
}
});
http.send();
}
}
</script>
there are many ways to redirect page in Spring, but be sure if the model attribute off message its passing correctly to FrontEnd or passing like parameter to another handler , you can see this document : http://javainsimpleway.com/spring-mvc-redirecting-model-attributes-from-one-controller-to-other-controller/ , hope this is useful !!

Insert Data Using Ajax

I am using Laravel 5.3. I want to insert the data using blade template.But my when i press submit button it gets refreshed every time. what to do? and please anyone tell me how to use ajax url,type,data
If you try to submit via Javascript make sure prevent form default action with e.preventDefault(). This code prevent the form submitted in a regular way. Just add this code to wrap your AJAX call:
$('#form-id').submit(function(e){
e.preventDefault();
$.ajax({...});
});
I just assume you are using jquery if you are talking about ajax. It's really simple. Your laravel routes listen to "post", "get", "patch", "delete" methods.
Everything of these can be created with a ajax request - example:
$.ajax({
method: "POST",
url: "/posts",
data: { title: "Hello World", text: "..." }
})
.done(function( post ) {
// assuming you return the post
alert(post.title + " created");
});
Now that you use ajax you will not want to return a view to the ajax call. You have different options here (create a new route, helper functions etc.) I will give the most easy example
Controller function:
public function store(Request $request) {
$post = App\Post::create($request->all());
if($request->ajax()) {
return $post;
} else {
return redirect('/posts');
}
}
now you controller will return data on ajax calls and will redirect you on default calls without ajax.
Finally you have a last thing to keep in mind. If you have web middleware applied ( done by default ) you need to handle the csrf token. The most easy way to handle this is by adding a meta tag to your html head
and then (before doing all your calls etc.) add this to configure your ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
this will add the valid csrf token which is in your head to every ajax call and will ensure you not run into token missmatch exceptions.
Things to keep in mind:
- if you stay very long on one page tokens might expire ( laravel-caffeine will help here )
- you need to handle validation for ajax calls

Send Multiple data with ajax

I want to use ajax for add data in database and i found following code in net and it is working fine.
<script language='javascript'>
reqObj=null;
function saveCust(){
document.getElementById('res').innerHTML='processing';
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject('Microsoft.XMLHTTP');
}
reqObj.onreadystatechange=processSave;
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
reqObj.send(null);
}
function processSave(){
if(reqObj.readyState==4){
document.getElementById('res').innerHTML=reqObj.responseText;
}
}
</script>
Above code sends only one String but, i have 5 Strings in my form.
Please anybody alter the code for sending multiple data.
The problem is that you're sending a single parameter in the reqObj.open function:
reqObj.open('POST','./custSave?reqObj.open('POST','./cName?id='+document.getElementById('CustCode').value,true);,true);
Note that the only parameter you send is id.
You can add more parameters in the flavor of QueryString:
id=something&otherParameter=else //and more parameters
IMO the easiest way to handle an ajax request would be using jQuery, as shown and heavily explained by BalusC in How to use Servlets and Ajax?.
Based on the samples there and jQuery Ajax POST example with PHP, you can come with the following code:
Assuming the 5 Strings are in the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
Assuming there's data outside the form
function saveCust(){
$('#res').html('processing');
var $form = $(this);
var serializedData = $form.serialize() + "&id=" + $('#CustCode').val();
$.post('./custSave', serializedData, function(responseText) {
$('#res').html(responseText);
});
}
And you can even enhance this using more jQuery functions, but that's outside the scope of this answer.

Validate $.getJSON before its being sent to the server in JQmobile

I'm trying to Validate my form before it's being sent to the server. I tried couple of J/S plugins for regular validation and none of them seem to work.
I tried looking for getJSON validation method with jquerymobile but haven't seen anything related. Is using $.getJSON the right approach?
Here is a fiddle http://jsfiddle.net/Kimbley/kMsXK/2/
Thanks :D
Code Here:
function mAddBusiness() {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").attr("value"),
bsnCity: $("#mBsnCity").attr("value"),
bsnAddress: $("#mBsnAddress").attr("value"),
bsnMenu: $("#mBsnMenu").attr("value"),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").attr("value", "");
$("#mBsnCity").attr("value", "");
$("#mBsnAddress").attr("value", "");
$("#mBsnMenu").attr("value", "");
alert("Business was added successfully ");
}
);
}
Inside your mAddBusiness() function you can just do your validation before sending the AJAX request. Something like:
function mAddBusiness() {
if ($("#mBsnName").val() !== '') {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").val(),
bsnCity: $("#mBsnCity").val(),
bsnAddress: $("#mBsnAddress").val(),
bsnMenu: $("#mBsnMenu").val(),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").val("");
$("#mBsnCity").val("");
$("#mBsnAddress").val("");
$("#mBsnMenu").val("");
alert("Business was added successfully ");
}
);
} else {
alert('Please enter a business name.');
}
}
Note that you will have to add the data-ajax="false" attribute to the <form> tag in question so that jQuery Mobile does not attempt to submit the form itself.
Also, note that $('input').attr('value') will not return the current value of an input, it will return the initial value before the user had a chance to input anything. To get the current value of a form input, use .val(): http://api.jquery.com/val

get $.post to work with the validate plugin on multiple forms without seperate functions

On a fansite im doing http://yamikowebs.com/ee/
I have a few forms (2 atm). I used $.post to find out what form is being submited. submit the form and display that pages results where the form was originally with .html().
My next step was to use the validator which is working fine but im not sure how to put the 2 together.
submitHandler: function(form){} seems to be the setting for how its submitted. However, I can't get this to work with my $.post function or find out what form is being processed.
If I leave the defaults for validation plug-in if there no errors it will send you to the page. the ajax plug-in that it works with doesn't do what I want. Below is my $.post function
form validation:
//ajax post
$("form").submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent("div")
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
http://docs.jquery.com/Plugins/validation#source is the validation plugin
You're correct in thinking that submitHandler is the right callback to use. However, I ran into some interesting issues while using it with multiple forms (like you're trying to do). For example, in this code:
$("#form1, #form2").validate({
submitHandler: function(form) {
alert(form.action);
alert(form.id);
}
});
The submitHandler callback does not get supplied the correct parameter (it always gets #form1). I believe this is actually a bug in jQuery-validate (so I've filed it here).
Anyway, a decent workaround would be to wrap the validate call in .each():
$("form").each(function() {
$(this).validate({
submitHandler: function(form) {
/* 'form' has the correct value */
var values = $(form).serialize(),
$div = $(form).parent("div");
alert(form.action);
alert(form.id);
/* Perform AJAX call here */
}
});
});
Example: http://jsfiddle.net/andrewwhitaker/MmCXN/

Resources