Prevent redirecting after post - javascript

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.

The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.

You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example

In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.

Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

Related

Issue with AJAX form submit

Required the form to be submitted via an ajax call and you will intercept the result and update your page. You never leave the index page.
I'm having trouble having the ajax call working
<form action="/cart" method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="{{id}}">
<input type="hidden" name="update" value="0">
</form>
var form = $('#addProduct');
form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/cart",
data: form,
dataType: "json",
success: function(e) {
window.location.href = "/";
}
});
})
you can use
JavaScript
new FormData(document.querySelector('form'))
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
You are changing the whole meaning of the ajax call. Ajax call is used for updating something without page refresh. In your case on success, you are changing the URL which is not right. Remove window.location.href = "/"; from your code and try to append messages or alert something like alert('Product is added to cart');
Your ajax call is not sending data to the server. Use formdata object or serialize() to get form input values then send it to the server.
Use
var form = new FormData($('#addProduct')[0]);
OR
var form = $("'#addProduct").serialize();
Instead of
var form = $('#addProduct');
And on success, send response from server and update your DOM in success function. Don't use window.location.href = "/";
To update your document after success you can use append(e) to update your DOM
<form method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="2">
<input type="hidden" name="update" value="0">
</form>
<div id="display">
</div>
$(function(){
$("#addProduct").submit(function(e){
e.preventDefault();
var quantity = $(this).children("input[name=quantity]").val();
var productid = $(this).children("input[name=productid]").val();
var update = $(this).children("input[name=update]").val();
$.ajax({
type:"post",
url:"/cart.php",
data:{update:update,quantity:quantity,productid:productid},
success: function(feedback){
$("#display").html(feedback);
},
error: function(err){
alert("error");
}
});
});
});
I update my answer and i use the div with id display to show my data return from ajax success

Prompt recently entered values for forms without getting submitted and not ajax posting to any urls

I am running a simple Embedded web-server where a form needs to be filled and the data can be submitted in 3 different ways for a Truck weighing operation. As i am having 3 different buttons to submit the data through an ajax call to a lua webserver i don't want the form gets submitted in default way.
<form id="formTruck" class="form-group">
<label class="form-label" for="reg-num">Rego:</label>
<input class="form-input" type="text" id="rego">
<label class="form-label" for="product">Product:</label>
<input class="form-input" type="text" id="product">
<label class="form-label" for="valuePT">Preset Tare</label>
<input class="form-input" type="text" id="valuePT">
<input id="dump-submit" style="display:none" value="Submit_Dump" type="submit">
</form>
<div id="weighInOutGroup">
<button id="weighIn" onclick="weigh(this.id);">WEIGH IN</button>
<button id="weighOut" onclick="weigh(this.id);">WEIGH OUT</button>
<button id="weighInPt" onclick="weigh(this.id);">WEIGH IN (PT)</button>
</div>
I have JS function to do the ajax request depends on the button clicked
function weigh(type) {
var weighData = {};
if (type == "weighIn") {
$.ajax({
//ajax request
},
});
} else if (type == "weighInPt") {
//ajax request
} else if (type == "weighOut") {
//ajax
}
};
Also i have used following jquery function to prevent pressing enter navigating to default action
$("#formTruck").submit(function(e){
e.preventDefault();
console.log("weighIn submit prevented")
});
but by doing this i couldn't get the recent inputs prompted on text input fields, as the form is not actually submitted in default action.
Can anyone suggest me a way to achieve this without doing any posts or navigating to any pages?
i don't understand why you use 3 send buttons, use instead a radio buttons, in the jquery submit add your if's and for catch the form data use $("#formTruck").serialize()
$("#formTruck").submit(function(e){
console.log("weighIn submit prevented");
let data = $("#formTruck").serialize() ;
if ($("#rdWeighIn").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighOut").prop("checked")) {
$.ajax({ data: data, ...
} else if ($("#rdWeighInPt").prop("checked")) {
$.ajax({ data: data, ...
} else {
//
}
return false;
});

How to disable other input when this input OnKeyUp?

How to disable other input when this input OnKeyUp ?
When i input data into input name="inputid1" , i want to disabled other input
when i input data into input name="inputid2" , i want to disabled other input
when i input data into input name="inputid3" , i want to disabled other input
when i input data into input name="inputid4" , i want to disabled other input
How can i do this with javascript loop ?
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<input type="text" id="inputid1" name="inputid1" onKeyUp="fn_test1()">
<br>
<input type="text" id="inputid2" name="inputid1" onKeyUp="fn_test2()">
<br>
<input type="text" id="inputid3" name="inputid1" onKeyUp="fn_test3()">
<br>
<input type="text" id="inputid4" name="inputid1" onKeyUp="fn_test4()">
<br>
<span id="myplace"></span>
</form>
<?PHP
for($i=1;$i<=4;$i++)
{
?>
<script>
function fn_test<?PHP echo $i; ?>() {
$("#inputid2").prop('disabled', true);
$("#inputid3").prop('disabled', true);
$("#inputid4").prop('disabled', true);
setTimeout(function(){
$.ajax
(
{
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
$("#inputid2").prop('disabled', false);
$("#inputid3").prop('disabled', false);
$("#inputid4").prop('disabled', false);
$('#myplace').show();
$('#myplace').html(data);
}
}
)
}, 2000);
}
</script>
<?PHP
}
?>
This will work
$('#form-id input').on('keyup',function() {
$('#form-id input').attr('disabled','disabled'); //disable all
$(this).removeAttr('disabled'); //enable the one that triggers the event
doPost();
});
function doPost() {
$.ajax({
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
$('#myplace').show();
$('#myplace').html(data);
},
always: function() {
$('#form-id input').removeAttr('disabled');
}
}
)
}
Working example:
http://jsfiddle.net/z4apqjan/
Edited: I put the doPost function to execute the Ajax request.
There are to much messy things in your code, but I've made some corrections for you:
You have same names for four input elements, so you will always get inputid1 param in your PHP and I think this is not want you want to achieve.
You don't need to bind keyup for each element manually in html, better use advantage of jQuery, for this purpose I've added class attribute to all four inputs with value strangeInputs, you can change it respectively as you wish.
No need to create functions for each input, you already have enough information which separates the meaning of them.
Also after once keyup occurs to one of the input elements I think you no longer need keyup handler, so we will remove it after first it's been fired with jQuery's .off function. Edit: but because you send request all the time keyup occurs to the input we should not disable event listener
Finally your simplified code would look like this:
HTML:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<form id="form-id" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);">
<input type="text" id="inputid1" class='strangeInputs' name="inputid1">
<br>
<input type="text" id="inputid2" class='strangeInputs' name="inputid2">
<br>
<input type="text" id="inputid3" class='strangeInputs' name="inputid3">
<br>
<input type="text" id="inputid4" class='strangeInputs' name="inputid4">
<br>
<span id="myplace"></span>
</form>
JavaScript:
/**
* scenario is simple, bind keyup event, when it fires once,
* execute desired code and remove keyup listener finally
*/
$(function(){
$('.strangeInputs').keyup(function(){
$('.strangeInputs').not(this).prop('disabled', true);
fn_test_inputs();
// $('.strangeInputs').off('keyup');
// in the case you send request at once keyup event occurs,
// you should not remove listener
});
});
function fn_test_inputs()
{
setTimeout(function(){
$.ajax
(
{
url: 'test_mm16.php',
type: 'POST',
data: $('#form-id').serialize(),
cache: false,
success: function (data) {
// here enable inputs again
$('.strangeInputs').prop('disabled', false);
$('#myplace').show();
$('#myplace').html(data);
}
}
)
}, 2000);
}
Simple input thing you can see here: http://jsfiddle.net/gttv53fg/

Upload files Using Ajax, Jquery and Struts2

Hi can any one please tell me how to upload files using ajax, jquery and Struts2. I have gone through the lot of tutorials in the net but i didn't get any possible solution. The requirement is when ever we click on the button the javascript function need to be called.The javascript(jquery) initiate the Ajax engine and ajax need to call the struts action to get the response. Here the request and response is without refresh the page and without using the IFrames.
I use iframe to submit my data without refresh.
i) My html is as follows :
1) Add form tag. // You can just copy paste my form tag just change the action
2) Add target="my_iframe" // The iframe name.. it can be anything
<div class="bp_up_input">
<form name="banner_image_uploads" id="banner_image_uploads" method="post" action="" target="my_iframe" enctype="multipart/form-data">
<span>
<input type="file" name="banner_image" class="my_vld" lang="Image_path" />
<input type="button" id="banner_image_upload" value="Upload" class="bp_button_style" />
</span>
<input type="hidden" name="slt_store_id" value="" />
<input type="hidden" name="sld_location" value="" />
</form>
</div>
ii) My javascript code is a follows :
$('#banner_image_upload').live('click',function(){
if($.trim($('input[name="banner_image"]').val()) != '' && $.trim($('select[name="bp_location"]').val()) != '' && $.trim($('#store_names').val()) != ''){
$("iframe").remove(); //Remove previous iframe if present
$("body").append('<iframe id="my_iframe" name="my_iframe" src="" style="display:none;"></iframe>'); //Append iframe to body with id my_iframe
$('#banner_image_uploads').submit();//submit the form with id banner_image_uploads
$("#my_iframe").load(function(){
var val = $("iframe")[0].contentDocument.body.innerHTML; // I use php so I just echo the response which I want to send e.g 250:new and save it in var val.
var data = val.split(':'); // I split the variable by :
var html = '<tr><td><img width="800" height="60" border="0" src="/assets/store_banners/live/'+$.trim($('input[name="sld_location"]').val())+'/'+data[1]+'" id="'+data[0]+'"><img src="/images/delete_trash.png" width="9" height="12" class="image_delete" style="padding-left:37%;"/></td></tr>'; // In my case I wanted to upload an image so on success I had to show the image which was uploaded. You can skip this and the below code if you want.
$('.bp_table tbody').append(html); //Append the uploaded image to the container I wanted.
$('input[name="banner_image"]').val(''); //On success I clear the file name
});
}else{
alert('Please Select filters');
}
Hi the below code is working for me. I hope it will help you.
JSP Code:
<div id="uploadImg">
<s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
<s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
<s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
</s:form>
<div>
JQuery:
$("#uploadImgSubmitBtn").click(function(e){
// Get form
var form = $('#uploadImgForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "strutsaction.action",
data : data,
cache: false,
processData: false,
contentType: false,
success: function(data){
$('#uploadImg').html(data);
}
});
});

Looping through an ajax script to process forms on a page

I have a page with lots of small one line forms, each of which has 5 items. The forms have the id form1, form2, form3, etc, and the id of the items and the submit button follows the same pattern. I have written out the following ajax script for processing the forms one at a time, where the variable $n corresponds to the form and item number. What I am not sure about is how to loop through this script for each form on the page. Do I need to somehow count the number of forms on the page first and then create a loop, and if so how do I do this?
$(".submit$n").click(function() {
var action = $("#form$n").attr('action');
var form_data = {
name: $j("#name$n").val(),
date: $j("#date$n").val(),
attended: $j("#attended$n").val(),
paid: $j("#paid$n").val(),
method: $j("#method$n").val(),
is_ajax: 1
};
$j.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success')
$j("#form$n").fadeOut(800);
console.log(response);
}
});
return false;
});
});
I'm sorry but I don't think this is being set up correctly, and neither is the accepted answer...it's just very messy. I'm not sure if your original code is replicated for every form you have (because the whole $n variable thing confuses me and makes me think you have it several times), but it isn't needed if so. Here's what I would use:
$(document).ready(function () {
$(".submit").click(function () {
var $this = $(this);
var $form = $this.closest("form");
var action = $form.attr('action');
var form_data = {
name: $form.find("[id^=name]").val(),
date: $form.find("[id^=date]").val(),
attended: $form.find("[id^=attended]").val(),
paid: $form.find("[id^=paid]").val(),
method: $form.find("[id^=method]").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function (response) {
if (response == 'success') {
$form.fadeOut(800);
}
console.log(response);
}
});
return false;
});
});
Just give all the submit buttons a class of "submit", and this should work fine. Just to make sure, your HTML would have the format of this:
<form id="form1" action="page1.php">
<input type="text" id="name1" name="name1" /><br />
<input type="text" id="date1" name="date1" /><br />
<input type="text" id="attended1" name="attended1" /><br />
<input type="text" id="paid1" name="paid1" /><br />
<input type="text" id="method1" name="method1" /><br />
<input type="submit" class="submit" value="Submit" />
</form>
Just so you understand what's happening, the Javascript finds the submit button's parent form when it's clicked. Then, with that form, it finds all descendents that have an id attribute that starts with "name", "date", etc. You can do this because you have clearly separated controls into their own forms. So with this code, you can be assured that when you click a submit button, you're grabbing all of the controls' values from the form that it's in.
Add a common class to all your submit buttons, like: <input type="submit" id="submit1" name="submit1" class="submit" />
And then change your code to:
$('.submit').on('click', function() {
var n = this.id.substr(6);
// n is the number of the form. 6 because the word submit has 6 characters.
// You might want to do this some other way.
// you can get the rest of the values by doing
$('#name' + n).val()
// and so on
});

Categories

Resources