.ajax() refreshes the page after ENTER is hit - javascript

I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>

This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.

Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});

Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.

Related

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.

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

Form submit Ajax using jQuery sometimes does not works

I am doing form data submit using Ajax with jQuery.
When I submit form on popup window, I refresh the parent page.
My code:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webapp/addSpeedDataAction.do",
data: $(this).serialize(),
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});
However page gets refreshed on success of callback but i can not see update on my parent page. Sometimes I can see updates and sometimes not. What is the issue? I also need to know how I can write it in native javascript and submit form using ajax javascript.
Maybe your getting this error due the fact that javascript is async and your code will proceed even when you have yet no response from the request.
Try this:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST",
url: "/webfdms/addSpeedDataAction.do",
data: $(this).serialize(),
async: false, // This will only proceed after getting the response from the ajax request.
success: function(data) {
//console.log("Data: " + data);
window.opener.location.reload();
}
});
});
});

AJAX: Submitting a form without refreshing the page

I have a form similar to the following:
<form method="post" action="mail.php" id="myForm">
<input type="text" name="fname">
<input type="text" name="lname">
<input type="text" name="email">
<input type="submit">
</form>
I am new to AJAX and what I am trying to accomplish is when the user clicks the submit button, I would like for the mail.php script to run behind the scenes without refreshing the page.
I tried something like the code below, however, it still seems to submit the form as it did before and not like I need it to (behind the scenes):
$.post('mail.php', $('#myForm').serialize());
If possible, I would like to get help implementing this using AJAX,
Many thanks in advance
You need to prevent the default action (the actual submit).
$(function() {
$('form#myForm').on('submit', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
// This is executed when the call to mail.php was succesful.
// 'data' contains the response from the request
}).error(function() {
// This is executed when the call to mail.php failed.
});
e.preventDefault();
});
});
You haven't provided your full code, but it sounds like the problem is because you are performing the $.post() on submit of the form, but not stopping the default behaviour. Try this:
$('#myForm').submit(function(e) {
e.preventDefault();
$.post('mail.php', $('#myForm').serialize());
});
/**
* it's better to always use the .on(event, context, callback) instead of the .submit(callback) or .click(callback)
* for explanation why, try googling event delegation.
*/
//$("#myForm").on('submit', callback) catches the submit event of the #myForm element and triggers the callbackfunction
$("#myForm").on('submit', function(event, optionalData){
/*
* do ajax logic -> $.post is a shortcut for the basic $.ajax function which would automatically set the method used to being post
* $.get(), $.load(), $.post() are all variations of the basic $.ajax function with parameters predefined like 'method' used in the ajax call (get or post)
* i mostly use the $.ajax function so i'm not to sure extending the $.post example with an addition .error() (as Kristof Claes mentions) function is allowed
*/
//example using post method
$.post('mail.php', $("#myForm").serialize(), function(response){
alert("hey, my ajax call has been complete using the post function and i got the following response:" + response);
})
//example using ajax method
$.ajax({
url:'mail.php',
type:'POST',
data: $("#myForm").serialize(),
dataType: 'json', //expects response to be json format, if it wouldn't be, error function will get triggered
success: function(response){
alert("hey, my ajax call has been complete using the ajax function and i got the following response in json format:" + response);
},
error: function(response){
//as far as i know, this function will only get triggered if there are some request errors (f.e: 404) or if the response is not in the expected format provided by the dataType parameter
alert("something went wrong");
}
})
//preventing the default behavior when the form is submit by
return false;
//or
event.preventDefault();
})
try this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
The modern way to do this (which also doesn't require jquery) is to use the fetch API. Older browsers won't support it, but there's a polyfill if that's an issue. For example:
var form = document.getElementById('myForm');
var params = {
method: 'post',
body: new FormData(form),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
};
form.addEventListener('submit', function (e) {
window.fetch('mail.php', params).then(function (response) {
console.log(response.text());
});
e.preventDefault();
});
try this..
<form method="post" action="mail.php" id="myForm" onsubmit="return false;">
OR
add
e.preventDefault(); in your click function
$(#yourselector).click(function(e){
$.post('mail.php', $(this).serialize());
e.preventDefault();
})
You need to prevent default action if you are using input type as submit <input type="submit" name="submit" value="Submit">.
By putting $("form").submit(...) you're attaching the submit handler, this will submit form (this is default action).
If don't want this default action use preventDefault() method.
If you are using other than submit, no need to prevent default.
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'save.asmx/saveData',
dataType: 'json',
contentType:"application/json;charset=utf-8",
data: $('form').serialize(),
async:false,
success: function() {
alert("success");
}
error: function(request,error) {
console.log("error");
}
Take a look at the JQuery Post documentation. It should help you out.

Categories