AJAX returns data twice on submit - javascript

Instead of redirecting the user to a new page, I want to add an overlay over the form. Somehow, the following code returns the overlay twice.
AJAX
$(document).ready(function ()
{
$('#form_informations').submit(function ()
{
$.get('php/formulaires.php', $(this).serialize(), function (data)
{
$('#form_informations').append('<div id="conf_informations" class="confirm"><p><img src="img/check.png" /><br /><?=FORMULAIRE_SAUVEGARDE;?></p></div>');
});
return false;
});
});
The id #form_informations is only used once.
For now, the second overlay is not created in php/formulaires.php because the file is empty as I have not started parsing the data.
Why is this happening? I don't see where this second overlay is coming from.
This is the HTML form:
HTML Form
<form id="form_informations" method="post" enctype="multipart/form-data">
<!-- form here -->
<input type="submit" name="submit_general" value="Save" />
</form>

May be you can add some code like this in the submit function
if(!$("#conf_informations").size()) {
$.get... //your get request here
}
Final solution
if(!$("#conf_informations").length()) {
$.get... //your get request here
}

Related

How to redirect to another page after click on submit button in form with required inputs

I need to redirect to index.html after clicking on button in a form. I tried this:
$("#btn").on("click", function() {
window.location.replace("index.html");
localeStorage.clear();
})
However in the form I have required inputs, so when I had some empty required input, it redirected, but at the same time it said that I must write something to input.
I need to redirect to index.html after successful form submission. Like on a eshop after submitting an order
Firstly, if you want the form to be validated first before the redirection you need to place the event on the submit of the form, not the click of the button.
Secondly, performing a redirect in JS when the form is submit is redundant; just set the action of the form to where you want the user to be sent.
With the above in mind, try this:
<form id="yourForm" action="index.html">
<input type="text" name="foo" required />
<!-- Some more 'required' form controls... -->
<button type="submit">Submit</button>
</form>
$("#yourForm").on("submit", function() {
localeStorage.clear();
});
what you could do is to verify that the inputs are present before the redirect:
$("#btn").on("click", function() {
// do some checks
//if checks ok call redirect, if ko returns
window.location.replace("index.html");
localeStorage.clear();
})
You can verify the values, use fetch to send the form and then redirect.
( You can add some gestion of server response before redirect. Like "Login already in database ... )
$("#btn").on("click", function() {
const verif = *verifAndFormat(...)* // function that return json like {valid:true , data:... }
if( verif.valid ){
fetch( URL , {method:'POST', body: verif.data} )
.then( resp =>{
/*some operations*/
localeStorage.clear();
window.location.replace("index.html");
})
.catch( err => /*error gestion*/
}else{
/*Invalid value gestion*/
}
})
$(function(){
$('#btn').On('click', function() {
window.location.href="../index.html";
}
}
And also you can call it form html coding on click event to call function submit and redirect from that..
html coding
<input type="button" id="btn" onclick="submit()"/>
Javascript coding
function submit(){
window.location.replace("http://webpagename.index.html");
}

jQuery validate is not working when the button is outside the form

I have a problem where jQuery validate is not working when the submit button is placed outside the form tags (which is required form my Cordova mobile app). As soon as .validate is called, the execution stops.
My HTML is set-up this way:
<form id="form-cart" >
// All form fields here
</form>
<ons-bottom-toolbar>
<button class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
And the function is then called as:
function addToBasket()
{
$.validate({
form : '#form-cart',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
// Run ajax on success
}
};
sNavigator.pushPage("confirmation.html", options);
return false;
}
});
}
How can I get this working so that it validates and calls ajax even if the button is outside of the form tags?
According to jQuery validation plugin documentation there are two different methods:
validate() – Validates the selected form.
valid() – Checks whether the selected form or selected elements are valid.
So you should set up the form validation with .validate method outside your function and check if form is valid inside your function (see code example below):
$('#form-cart').validate({
});
function addToBasket() {
if ($('#form-cart).valid())
//do you onSuccess stuff
}
}
Try this :
<form id="form-cart" >
// All form fields here
// Don't give <input type="submit"> here
</form>
<ons-bottom-toolbar>
<button type="submit" id="submitBtn" class="button" onclick="addToBasket();" data-trn-key="add_to_basket">
Add to Basket
</button>
</ons-bottom-toolbar>
and
$(document).ready(function () {
$("#submitBtn").click(function () {
$("#form-cart").submit();
});
});

jquery form plugin and show content of div

I use jquery form plugin and i try show the result when i submit my form in one div but no get result
<script>
jQuery(document).ready(function()
{
jQuery('#base64').ajaxForm(
{
dataType:'json',
success:edit64,
target: '#htmloutput'
});
});
function edit64(datasend64)
{
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
</script>
I donñt know if i put all well or no , i try mant times and no get the result of form inside div , only show nothing
<div id="htmloutput" style="display:none;"></div>
<form action="admin_db_edit.php" name="base64" id="base64" method="post">
<input type="text" name="value_base64" value="" class="db_edit_fields" />
<input type="hidden" name="send64" value="ok" />
<input type="submit" name="send" value="send" class="db_edit_submit" />
</form>
Thank´s for the help , regards
First... you have no url specified for the form. second, try adding a function to handle the error case. This can help you understand if the issue is happening on the client or the server.
jQuery(document).ready(function() {
jQuery('#base64').ajaxForm({
url: ????
dataType: 'json',
success: edit64,
error: onError,
target: '#htmloutput'
});
});
function edit64(datasend64) {
if (datasend64.edit_result64 == "ok") {
jQuery('#htmloutput').fadeIn('slow');
}
}
function onError(response, error, reqObj){
alert(response);
}
if you are trying to send the data somewhere, you are probably missing the url attribute(as shown in the offical docs: http://malsup.com/jquery/form/#options-object)
however, trying to log the datasend64 value will help to determind if the function have been called or not. so... in your code:
function edit64(datasend64)
{
console.log(datasend64);
if (datasend64.edit_result64=="ok")
{
jQuery('#htmloutput').fadeIn('slow');
}
}
if a result is shown in the developer console - you can watch the object and seek for your values (if there are any at all). if you don't see anything - the success event havn't occoured (again, i think you are missing the url parameter)

jQuery Form: Ajax response is displayed, but does not show up in source code

I use Jquery Form for an Ajax image upload.
My relevant HTML:
<div class="input_con imageupload_con">
<form action="processupload.php" method="post" enctype="multipart/form-data" id="MyUploadForm">
<a class="button">BROWSE</a>
<input name="ImageFile" id="imageInput" type="file" style="display:none" />
<input type="submit" id="submit-btn" value="Upload" style="display:none" />
<img src="assets/img/ajax-loader.gif" id="loading-img" style="display:none;" alt="Please Wait"/>
</form>
<div id="output"></div>
My relevant JS:
$(document).ready(function() {
// Simulate a click on the file input button to show the file browser dialog ...
$('#MyUploadForm .button').click(function() {
$('#imageInput').click();
});
// ... and after having selected a image, trigger the form action
$('#imageInput').change(function() {
$('#MyUploadForm').submit();
});
var options = {
target : '#output', // target element(s) to be updated with server response
beforeSubmit : beforeSubmit, // pre-submit callback
success : afterSuccess, // post-submit callback
resetForm : true // reset the form after successful submit
};
$('#MyUploadForm').submit(function() {
$(this).ajaxSubmit(options);
// always return false to prevent standard browser submit and page navigation
return false;
});
$('.dismiss').click(function(e) {
e.preventDefault(e);
$('#output').empty();
$('#MyUploadForm .button').show();
});
}); /* end of document ready */
function afterSuccess() {
// ....
}
function beforeSubmit() {
// ...
}
//function to format bites bit.ly/19yoIPO
function bytesToSize(bytes) {
// ...
}
</script>
The output part of my PHP file "processupload.php":
//...
echo '<img src="uploads/'.$NewImageName.'" alt="Thumbnail" width="100%" height="auto">';
echo 'dismiss';
echo '<input type="hidden" id="path_thumbnail" value="uploads/'.$ThumbPrefix.$NewImageName.'">';
echo '<input type="hidden" id="path_resizedimage" value="uploads/'.$NewImageName.'">';
//...
What works fine: After having uploaded the image, everything that is stated in the echo part of my PHP file is displayed on the page.
What suprises me: The elements that are echoed DO NOT show up in the source code.
Based on the code given above, can anyone see the reason why the code does not show up in the source code but is displayed?
EDITED:
The reason why I was wondering why the echoed elements do not show up in the source code is that clicking the dismiss-button does not work.
See above:
$('.dismiss').click(function(e) {
e.preventDefault(e);
$('#output').empty();
$('#MyUploadForm .button').show();
});
When I click it, the window scrolls up to the top of the window instead of dismissing the picture....
What is happening (per comments) is that when you initialize the page, there is not yet any object of class "dismiss", so the handler does not get attached.
Then the AJAX injects the button, but at that point it's too late.
You need to use dynamic (delegated) binding:
$('body').on('click', '.dismiss', function(e) {
...
so that the BODY receives the click and dispatches it to any new dismiss'es, too.

How to submit a form with specific fieldset

I have a form like this:
<form name="paymentForm" id="paymentForm" action="/submit.jsp" method="post">
<fieldset id="ccData">
<input id="ccNumber" name="ccNumber"/>
</fieldset>
<fieldset id="otherData">
<input id="requestId" name="requestId"/>
</fieldset>
</form>
When you slick submit, I would like to submit(via ajax) only #ccData filedset to some different url (e.g. submitCC.jsp) and based on response I want to submit full form to actual url.
How can I achieve that ?
Use jQuery's serialize method
var formData = $("#ccData").serialize()​;
$.post("TheUrl",formData);
You could do that with JavaScript - e.g jQuery. You build an eventHandler like
$('#paymentForm').on('click', function () {
$(this).preventDefault();
if ($(this).hasClass('first_send')) {
$.ajax({
url: "your_url",
data: { ccData: $('#ccData').val()}
}).done(function ( data ) {
$('#paymentForm').addClass('first_send')
// examin the data, insert stuff you need and send the form again
// with ajax
})
} else {
$(this).removeClass('first_send')
// this is the second send - so do stuff here - show a result or so
}
})
With the class first_send you can check if it is the first send or the second. This is just an untested, incomplete idea how you could do it. I guess you get the big picture ...

Categories

Resources