Dont autoscroll to top when submitting a from. Stay on current position - javascript

I don't want to automatic scroll up the page when a form I submitted. I want to stay on the same position as when the form was submitted. How can I do that?
<script type="text/javascript">
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
<script>
function submitForm2()
{
document.getElementById('form').submit();
popsup();
}
</script>
<div onclick='submitForm2();'></div>
<form id='form' action='' method='post'>
<input name='test' value="ok">
</form>
I tried the solutions in the link;
return false results in the page opening in a new window and in the new window the page autoscrolls to top after submit.
"#" or #! in action = form isn't submitted and page scrolls to top.
javascript:void(0); - form doesn't get submitted and page still scrolls to top

document.getElementById('form').submit(); doesn't fire the frm.submit handler. Use $('#form').submit() instead, because the jQuery version of submit() calls any onsubmit handlers, whereas vanilla Javascript submit() bypasses them.
Edit
Another thing - your script that adds the submit handler function is being executed immediately - before the form has been rendered. So it's probably failing. Also you seem to have a wayward <script> tag in there. Try this:
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
});
function submitForm2() {
$('#form').submit();
}
</script>

Related

Update form status by changing submit button text

I've small JS code which is not working as per my need.
Actually my backend PHP code contains so many functions which i want to process by pressing submit button and meantime i also want to show the status "Scanning" in place of submit button and when the data got fully processed, then i want to show "Completed" Status in place of submit button.
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
$(#response).show();
$(#form).hide();
}
});
});
});
</script>
You can simply show whatever you want when user clicks the button. And when you get the response you can change to whatever you want. Something like.
This is just an example of mocking your ajax request.
var $button = $("#btn");
$button.click(function() {
$button.text("Scanning...");
var promise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('foo');
}, 5000);
});
promise.then(function(){
$button.text("Done");
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn"> Submit </button>
You can use beforeSend...
beforeSend is a pre-request callback function that can be used to modify the jqXHR..
You can refer here for more detail.
And you can follow my code below for your ease.
..
Javascript:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
let submitBtnEl = $(this).find('button[type="submit"]'); //submit button element
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
beforeSend: function( xhr ) {
submitBtnEl.html('Scanning'); //the submit button text will change after click submit
},
success: function () {
$(#response).show();
$(#form).hide();
submitBtnEl.html('Completed'); //the submit button text will change after the form is completely submit
}
});
});
});
</script>
.
.
HTML:
<form>
<input type="text" name="input1" />
<button type="submit">Submit</button>
</form>
.
.
For your ease, you can try the code on this fiddle

Django : Ajax form still reloads the whole page

I am using a django form with ajax using this code:
<form id="form-id">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
and the Javascript code:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
});
But here is the thing, everytime the submit event is triggered, I feel like the whole page is reloaded (it blinks). What could I do to prevent this from happening?
Your change event is submitting your form and page refreshes. Delete it and add change event to second function, where you're currently waiting for submit event.
$('#form-id').on('change', function(evt) {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
});
To prevent submit on enter, add keypress event to function and detect when enter is pressed. Like this:
$('#form-id').on('change keypress', function(evt) {
var key = evt.which;
if (key == 13) {
return false;
} else {
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
}
});
Key number 13 is enter. When it's pressed, nothing is returned. You could have also replaced return false with evt.preventDefault(). And for other keys, Ajax will be triggered.
What if you add:
return false;
To your code, like so:
$( document ).ready(function() {
$('#form-id').on('change', function() {
this.submit();
})
$('#form-id').on('submit', function(evt) {
evt.preventDefault();
var form = evt.target;
$.ajax({
url: form.action,
data: $(form).serialize(),
success: function(data) {
$('.results').html(data);
}
});
return false;
});
});
Got this from:
https://simpleisbetterthancomplex.com/tutorial/2016/11/15/how-to-implement-a-crud-using-ajax-and-json.html
A very important detail here: in the end of the function we are
returning false. That’s because we are capturing the form submission
event. So to avoid the browser to perform a full HTTP POST to the
server, we cancel the default behavior returning false in the
function.
How I specify my form in html / django template:
<form id="form-id" action="required-url-goes-here" method="post">
<p> Search : <input name="{{ form.query.html_name }}" value="{{ form.query.value }}" type="search" id="form-input-id" autofocus onfocus="var temp_value=this.value; this.value=''; this.value=temp_value">
</p>
</form>
The tutorial I pointed to above works in a different way then you do. It specifies, inside the ajax request:
- url
- type
- data
- dataType
It also uses a different way to reference the form, and it is the only way I know, so I can't judge if there is an error in the rest of your code.

aJax Javascript Multiple Forms on Page

So I'm using this piece of javscript/ajax to create a form that submits to another page on my site without reloading the page. My question is how can I program this same code to work with multiple forms on the same page? If I have two forms that I want to submit to two separate locations how do I specify which form triggers which piece of javascript?
<script type="text/javascript">
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'csverify.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});});//here
}
$(document).ready(function() {
submit();
});
</script>
Not sure if it matters but I would like to use either name="" or ID="" to designate each form with a name.
You can create a method passing form's ID.Then get the form attribute action on different by form's ID.
Html part
<form id="form1" action="form1.php">
...
</form>
<form id="form2" action="form2.php">
...
</form>
JS part
<script type="text/javascript">
function submit(formID) {
var $form = $('#'+formID);
$form.submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});
});//here
}
$(document).ready(function() {
submit('form1');
submit('form2');
});
</script>

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

after submit clear textbox

I'm inserting data into a table using Ajax. I'm using ajax so my page wouldn't get refresh. Here is my Ajax code for calling the inserting page:
<script type="text/javascript">
var i = jQuery.noConflict();
i(document).ready(function(){
i('#myForm').on('submit',function(e) {
i.ajax({
url:'insert.php',
data:$(this).serialize(),
type:'POST'
});
e.preventDefault();
});
});
</script>
Now every time i write in the textbox and hit the submit button the data gets entered but it remains in textbox and i have to press the delete button to erase it.
Question: how can I make so my data gets cleared when I press the submit button?
You can reset the form in the ajax success handler
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
context: this
}).done(function () {
this.reset();
});
e.preventDefault();
});
});
document.getElementById('myForm').reset(); // In Javascript
$("#myform")[0].reset(); // In jQuery Fashion
You can reset form fields on the completion as suggested by arun or on success as below
var i = jQuery.noConflict();
jQuery(function ($) {
$('#myForm').on('submit', function (e) {
$.ajax({
url: 'insert.php',
data: $(this).serialize(),
type: 'POST',
success:function(data) {
$('#myForm')[0].reset();
}
});
e.preventDefault();
Hope it helps

Categories