How to stay on same position after submitting an html form? - javascript

I have a simple html form:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?

-Every time I click on "submit", it brings me straight back to top.
Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.
-which creates a poor user experience because the user would have to scroll back down where he was browsing the products
To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.

Ajax is your best bet if you want to achieve what you want
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});

Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
Script:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

Related

How to prevent repeatative submit while using ajax or javascript?

I have a controller in c# and inside the controller there is a save method. The save method saves/updates data that is submitted by submit button click and javascript. The problem is, if you click on the button multiple time, it should only process the very first click and rest of them should be identified as duplicate submit and should be discarded by controller. How to do this in c# mvc web application?
Disable the button after it's clicked. So it can just be clicked once.
Simple way
when button clicked disabled it then actived again after you got response result from ajax! u can also add loader that make ur web look so cool!
<button id="btnSend" onClick="send()">submit</button>
<script>
btnSend=document.getElementById("btnSend");
function send(){
btnSend.disabled=true;
//set disabled button here
$.ajax({ type: "GET",
url: "http://www.google.de",
async: false,
success : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
},
fail : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
}
});
}
</script>
I would also disable the button on the client side. But you could also check if the submitted data is different from the stored data. If no changes were made you could just return without further saving logic.
Should it be possible to just save the data once? Maybe a redirect to a different view after saving could be a possible solution in special cases.

How to use checkbox value asdata parameter in ajax

I need to reload a page when clicking in a submit button. What the new page should show depends on the checkboxes selected previously to the reloading.
My problem is that, when I click "submit", $("button").click(function()... takes the correct values but $(document).ready(function ()... takes always the values true (which are selected as default).
How can I save those values before the reloading so that I can use them on $(document).ready(function ()...? Can I send them as data parameter
$(document).ready(function() {
var selectedCheckboxes = new Array();
$.ajax({
url: 'getNewForm.php?accion=value1',
data: 'selectedCheckboxes',
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
//Do something
}
}
});
$("button").click(function() {
var selectedCheckboxes = new Array();
selectedCheckboxes[0] = document.getElementById("checkbox1").checked;
selectedCheckboxes[1] = document.getElementById("checkbox1").checked;
});
});
Note: I did var selectedCheckboxes twice trying to get different results, donĀ“t know where I should do it.
You have several problems here:
You have a syntax error in your code sample. Make sure the code you post to StackOverflow compiles and runs without syntax errors (assuming you're not asking why a particular code snippet is generating syntax errors :) ).
The data attribute of your AJAX request is incorrectly specified as the literal string 'selectedCheckboxes', which means that your browser will send the literal string "selectedCheckboxes" as the payload to your server.
In addition, as you correctly surmise, you don't correctly handle the initialization of selectedCheckboxes. Variables initialized with var in JS are scoped to the containing function, which means the selectedCheckboxes declaration inside your click() handler are never going to be seen outside it.
Also, you're getting the value of "checkbox1" twice; you probably want to get something named "checkbox2" or similar. Related: If you are just serializing the only inputs in the form, use jquery's serialize() method so you have less code.
If you're really reloading the entire page anyway, don't use an AJAX request to do it? Using AJAX for form submissions is common when you do not want to reload the entire page (see below), but for your stated use case, it adds complexity you don't need. Just have a simple form with checkboxes and a submit button, and let the browser do it's default action.
Here's an example of using AJAX to submit a form behind the scenes, without reloading the entire page:
http://jsfiddle.net/Palpatim/rLeGv/
Given the HTML:
<form id="checkboxForm">
<input type="checkbox" name="check" value="check1" checked="checked" id="ch1"/>
<label for="ch1">check1</label>
<br/>
<input type="checkbox" name="check" value="check2" checked="checked" id="ch2" />
<label for="ch2">check2</label>
<br/>
<button>Click me</button>
</form>
This JS will submit a form when the button is clicked:
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url: 'getNewForm.php?accion=value1',
data: $('#checkboxForm').serialize(),
dataType: 'json',
error: function() {
alert("ERROR");
},
success: function(res) {
alert("SUCCESS");
}
});
});
});
As far as loading a new page with the previous selections, you will have to maintain the state somehow. Your options include passing the state back from the server, storing the selections in the browser's local storage, or a cookie. I'd suggest passing the state back from the server, but your use case is a bit unclear.

How do you use twitter bootstrap button with jquery?

What I want to do is when a user clicks on the submit button in a forum, it should send the data collected to the php script and ideally, stay on the same page. Currently, I have in the form(I have other tags in the form but these are the two things I need to focus on)
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
As you can see, I use a form that sends the data to sqlinserter.php when the user clicks the submit button. Basic form stuff. Right now, when it clicks submit it goes to the actual sqlinsert.php page which is blank because it is just sending data to the database.
However, I would like to create a simple jquery script where you click the button it sends the data using ajax. I have been noticing that twitter bootstrap works differently with buttons and I am not sure how to use their buttons with jquery. Any help with this would be great.
So,
I need to figure out how to use twitter bootstrap buttons with
jquery. Specifically, I need to figure out how to use the submit
button.
How to send data using ajax?
I need to figure out how to use twitter bootstrap buttons with jquery. Specifically, I need to figure out how to use the submit button.
Bootstrap can be used together with jQuery, no additional steps required. Actually even bootstrap itself use jQuery in their framework.
You can still use jQuery like usual, and bootstrap like usual. Both will work, without any conflicts.
How to send data using ajax?
It can be done by using one of jQuery AJAX function, for example $.ajax.
Just add new event, click, on your button #newThread. Write the AJAX inside the event handler. Example based on your code can be seen in below.
HTML
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
JS
$(function() {
$('#newThread').on('click', function (e) {
e.preventDefault(); // disable the default form submit event
var $form = $('#replyForm');
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize(),
success: function (response) {
alert('response received');
// ajax success callback
},
error: function (response) {
alert('ajax failed');
// ajax error callback
},
});
});
});
There isn't any specific way to use a twitter bootstrap button. Just grab the id of this submit and submit the data via ajax like below:
$.ajax({
type:'GET',
dataType:'xml',
url:'path/to/phpfile.php',
success:function(data) {
// Do the handling here
},
error:function() {
alert("Sorry, Ajax call Failed");
}
});
There is nothing specific to form submission with bootstrap. You just need to make sure the button is insde the form (which you should want even if it wasn't bootstrap).
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
you are missing the closing </form> tag

ajax call doesn't work when a submit button is used

I'm trying fetch a live currency rate using the following API.
"http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj"
When I click on a button, it alerts the rate and works just fine. I'm using the following Ajax code.
<script type="text/javascript" language="javascript">
function testCurrencyRate()
{
$.ajax({
datatype:"html",
type: "GET",
url: "ajax/LiveCurrencyRate.php",
data: "t="+new Date().getTime(),
success: function(response)
{
alert(response);
},
error: function(e)
{
alert('Error while fetchig the live currency rate.');
}
});
}
</script>
The Ajax request goes to the LiveCurrencyRate.php page which is as follows.
$url="http://www.exchangerate-api.com/INR/USD/1?k=FQRxs-xT2tk-NExQj";
$result = file_get_contents($url);
echo $result;
and the <form></form> which contains the only button which when clicked makes an Ajax request on this URL ajax/LiveCurrencyRate.php.
<form id="testForm" name="testForm" action="" method="post">
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test" onclick="testCurrencyRate();"/>
</form>
Everything is fine. The problem however arises when I change the button type from type="button" to type="submit", it doesn't work. The alert box in the error part of the Ajax function shows the alert box just for a while and all of a sudden it disappears. I can't find any reasonable cause that may prevent this request from being completed. The same thing worked for me in my previous project but I was using XMLHttpRequest for making Ajax requests. What's going wrong here?
type="submit" causes the web browser to submit the form via a postback (because your method attribute is set to "POST"), which causes the page to refresh. The action attribute of the <form> tag determines where the data gets sent to, and then that page loads with the data provided. When this happens, all javascript on the page terminates because you are effectively going to a different page or reloading the current one.
The page is submitting because you are not cancelling the default action of the click. You need to stop that event from happening. With your code, you can add a return false to the onclick, but it is better to add the events in an unobtrusive manner.
$("#btnTestCurrencyRate").on("click",function(e){
testCurrencyRate();
e.preventDefault();
});
better to catch it on the form submission and not onclick
$("#testForm").on("submit",function(e){
testCurrencyRate();
e.preventDefault();
});
When you click the submit button your form is being posted to you web server. You need to prevent the form from posting by using something like:
$("#testForm").submit(function(e){
e.preventDefault();
});
because your page is submitting. you need to return false from the onclick handler if you want to prevent the submit.
HTML:
<input type="submit" id="btnTestCurrencyRate" name="btnTestCurrencyRate" value="Test"/>
JS:
document.getElementById('btnTestCurrencyRate').onclick = testCurrencyRate;
function testCurrencyRate() {
... snip ...
return false;
}

database query via javascript & servlet

I am trying to do a simple query for info from a database through an html page. I've got all the backend stuff working fine, but I'm having trouble on the client side. I currently have a form where the user submits their ID# to get some info on their case.
But with my current setup, it returns an entirely new page and I just want to read in a text string, process it and update the content on the current html page without opening up a new one and replacing the old one. How can this be done?
Here's my code so far:
function showInfo() { } // I want to make the request here instead
<form name="register" action="http://localhost:8080/testapp/authenticate" method="get">
<p><label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
<button id="checkButton" type="submit" onClick="showInfo()">Enter</button>
</p>
</form>
My guess is that you're actually submitting the form, which is posting back to the server. What you will want to do is cancel the form from submitting and submit it using AJAX (which is what I believe you want?).
To do so, your showInfo() function should do one of these three things (I can never remember which one)
return false;
cancel the event, something like e.preventDefault()
stop the propagation, something like e.stopPropagation()
Once you've successfully prevented the form from hard-submitting, you can then do what you'd like by submitting your data via AJAX and manipulating your response however you'd like.
1st - Jason is absolutely right that what you want for this situation is AJAX, below is an example in motion.
2nd - You should be using a Javascript library such as jQuery, which might look intimidating (as it did for me at first), but it is really easy and completely worth the small effort to get it going.
3rd - With jQuery, your application tidbits should look something like this, using the example you provided:
HTML -
<p>
<label for="badge">ID #:</label>
<input id="badge" name="ID" type="text" pattern="[0-9]{6}"
placeholder="xxxxxx">
// Please note that I removed the onClick section from the line below.
<button id="checkButton" type="button">Enter</button>
</p>
JQUERY -
// The default function you described to take information and display it.
function showInfo(data) {
// Insert your function here, probably using JSON as the Content Type
}
// This is the key AJAX function, using jQuery, that takes your info and gets a
// response from the server side, the sends it to the function above in order for it
// to be displayed on the page.
function processIdInfoCheck() {
$.ajax({
type: 'post',
url: '/http://localhost:8080/testapp/authenticate',
data: {
'id': $('#badge').val();
},
dataType: 'json',
success: displayIdInfoReturn,
error: function () {
alert("There was an error processing your request, please try again");
}
});
}
// When the page loads, the code below will trigger, and bind your button click
// with the action you want, namely triggering the AJAX function above
(function ($) {
$('#checkButton').bind('click', processIdInfoCheck);
})(jQuery);
Just remember, AJAX takes some effort to get the desired effect, but when you look at page load times, request numbers, etc... It is totally worth it. Please let me know if this was helpful and if you need any specifics.

Categories

Resources