...Some form gets submitted...
$.("form").submit(function() {
saveFormValues($(this), "./../..";
}
function saveFormValues(form, path) {
var inputs = getFormData(form);
var params = createAction("saveFormData", inputs);
var url = path + "/scripts/sessions.php";
$.post(url, params);
}
The weird thing is that if i add a function to the
$.post(url, params, function(data) {
alert(data);
}
I get a blank alert statement.
Within scripts/sessions.php i have a function to save whatever the $_POST information is to a file, and the sessions.php never saves this saveFormValues call. It never shows up to the file. But if i keep trying to get it to save, about once every 15 will actually allow it to be saved. This leads me to believe that the forms POST is somehow blocking this value saving post. Any help?
add a return false; to the submit function to prevent the form from submitting:
$.("form").submit(function() {
saveFormValues($(this), "./../.."); return false });
UPDATE:
if you want to later submit the form, keep a variable to indicate if it can be submitted:
var canSubmit = false;
$.("form").submit(function() {
if(!canSubmit)
{
saveFormValues($(this), "./../..");
return false;
}
});
and later:
$.post(url, params, function(data) {
alert(data);
canSubmit = true;
$.("form").submit();
}
So instead of doing a $.post i tried doing a $.ajax with asynch set to false. It saves the form values every ... like 3/5 times... any new suggestions?
You need to cancel the original submit by returning false from the handler. Update: If you want the original form submission to continue, then you can remove the handler and re-submit the form from the post callback.
$.("form").submit(function() {
saveFormValues($(this), "./../..");
return false; // cancels original submit and allows AJAX post to complete
});
function saveFormValues(form, path) {
var inputs = getFormData(form);
var params = createAction("saveFormData", inputs);
var url = path + "/scripts/sessions.php";
$.post(url, params, function() {
$('form').unbind('submit').trigger('submit');
});
}
So i decided to create an associative list of items that will not be saved from a form.
$nosave = array("password" => true, "confirmPassword" => true,
"descriptionCount" => true, "detailedDescriptionCount" => true,
"submit" => true, "action" => true, "p" => true);
//Then i decided to go through the $_POST information and save it to the SESSION info.
foreach ($_POST as $key => $value) {
if ($key != $id && !array_key_exists($key, $nosave)) {
//saves the value to the form.
$_SESSION[$id][$key] = $value;
}
}
//The $id is a hidden input.. name="formId" value="someUniqueId" That way whenever
//the form info is saved, its saved under a unique area and can be easily unset.
Instead of doing it through jQuery, i just called a function that roughly does all of that in my sessions.php file.
Related
Prevent a submission of a form via POST and submit once conditions are met.
Form is being submitted, I am not sure how to check if the function (which passes an HTML input into Python that checks a database if the user exists (Returns in JSON format true if it doesn't and false if it exists).
I have tried checking if the function is true, which for most cases work, I wonder if it is the $.get is an odd case?
document.getElementById("register").addEventListener("click", function(event) {
event.preventDefault();
let input = document.getElementsByName("username");
function(check) {
$.get('/check?username=' + input.value, function(data) {
document.querySelector('ul').innerHTML = data;
})
if (check()) {
this.submit();
}
else {
alert ("username is taken!");
return false;
}
#app.route("/check", methods=["GET"])
def check():
# Check the http parameter for username.
username = request.args.get("username")
check = db.execute("SELECT username FROM users WHERE username = :username", username=username)
if not check:
return jsonify(True)
else:
return jsonify(False)
I want the alert to flash and prevent form submission of the function runs and returns json(False) - which would indicate the username is taken
But right now it is submitting the form.
$.get() is asynchronous so you can't return a value from check()
Instead do the submit inside $.get() callback if response is true
document.getElementById("register").addEventListener("click", function(event) {
event.preventDefault();
let input = document.getElementsByName("username")[0];
$.getJSON('/check?username=' + input.value, function(data) {
if (data) {
document.querySelector('**formSelector**').submit()
} else {
// notify user
}
});
})
How to prevent form from submit when I am using ajax to validate it. The problem is that the ajax is asynchronous and the real result ( which is false in my case ) comming later. Is making Ajax to sync is the right way? This is my piece of code:
$('#w0').on('beforeSubmit', function(e){
let loadDate = $('#dstrequest-load_date').val()
let shippingDate = $('#dstrequest-shipping_date').val()
let requestId = '".($model->isNewRecord ? 0 : $model->id)."'
let trucks = $('.container-items_truck').find('.truck-item')
let ids = []
let result = true
$.each(trucks, function(){
let id = $(this).find('select').first().val()
if(ids.indexOf(id) === -1)
ids.push(id)
})
$.ajax({
method: 'post',
url: '/erp/distribution/dst-vehicle/check-truck-engage-date',
data: {
load_date: loadDate,
shipping_date: shippingDate,
trucks: ids,
request_id: requestId
}
})
.done(function(data){
let selects = $('select[name$=\"[truck_id]\"]')
$.each(selects, function(){
let val = $(this).val()
if(data.indexOf(val) !== -1){
$('#w0').yiiActiveForm('updateAttribute', $(this).attr('id'), ['".Yii::t('distribution', 'distributionCore.busy_truck')."'])
result = false
}
})
})
.always(function(data){
let transfer_wrapper = $('.transfer-wrapper')
$.each(transfer_wrapper, function(){
if($(this).is(':visible')){
let fields = $(this).find('input, select')
$.each(fields, function(){
if($(this).val() == ''){
let id = $(this).attr('id')
$('#w0').yiiActiveForm('updateAttribute', id, ['" . Yii::t('distribution', 'distributionCore.please_fill_the_field') . "'])
result = false
}
})
}
})
})
// HERE THE RESULT SHOULD BE FALSE BECAUSE OF THE AJAX VALIDATION BUT IT'S TRUE BECAUSE OF THE ASYNC BEHAVIOUR.
return result
})
Is making Ajax to sync is the right way?
No. Synchronous HTTP requests from JS are deprecated. Never use them.
You need to either:
Always halt
Always prevent normal form submission.
After you have validated the input, using Ajax, use JS to resubmit the form (without repeating validation).
Validate in advance
Do the validation as the data is entered, field by field.
Hopefully, the Ajax will be finished by the time the last field is completed and the form submitted.
That at that point, if the Ajax isn't finished, you either have to risk submitting the form without knowing the result of the Ajax validation or fall back to the first option I suggested.
I have 10 form in a page & there data is submitted through ajax, Now i don't want to create ajax script for each form. So here is what i tried
var form_id = $(this).closest("form").attr('id');
$(document).on("submit", "#"+form_id, function(e){
e.preventDefault();
var postData = $("#"form_id).serialize()
var send = true;
var ptel = 1;
$("#"+form_id).find("input").each(function () {
if ($(this).val() === '') { send = false; ptel = 0; }
});
if(ptel == 0) { bootbox.alert('Please Fill All fields'); }
if(send){
$('form_id').trigger("reset");
$.ajax({
type: "POST",
url: "/ajax/X-Profile",
data: postData,
cache: false,
success: function(msg)
{
bootbox.alert('Your Profile has been updated.');
}
});
}
return false;
});
var form_id results in undefined because when page loads no attribute was defined to it
Above codes are just to make you understand,
So my question is how can i make 10 forms submit through single ajax function
You can create a function such as SendForm() and attach it to the forms onsubmit attribute
<form id="yourid" onsubmit="SendForm(this);return false;">
inside the SendForm() function place your script
for instance:
function SendForm(form) {
var postData = form.serialize();
// .......etc
}
To know which form was submitted in PHP, you can place a hidden input inside the form or have a second parameter on SendForm which gets sent through, such as SendForm(node,formtype)
if the form isn't submitting or page reloads, remove the onsubmit attribute and add this to your JS instead
$(document).on("submit","form", function(e){
e.preventDefault();
SendForm($(this));
return false;
});
Have javascript function like below
<script type="text/javascript">
function submitForm(formID) {
data = $('#'+formID).serialize();
//your ajax code
}
</script>
Now use input button with onclick like below, and pass form Id as a parameter
<input type="button" value="Submit" onclick="submitForm({formID})">
This will work without refreshing the page. And on success you can trigger reset() function to form that particular form values.
I have two ajax calls on a page. There are text inputs for searching or for returning a result.
The page has several non ajax inputs and the ajax text input is within this . Whenever I hit enter -- to return the ajax call the form submits and refreshes the page prematurely. How do I prevent the ajax from submitting the form when enter is pressed on these inputs? It should just get the results.
However, I cannot do the jquery key press because it needs to run the ajax even if the user tabs to another field. Basically I need this to not submit the full form on the page before the user can even get the ajax results. I read return false would fix this but it has not.
Here is the javascript:
<script type="text/javascript">
$(function() {
$("[id^='product-search']").change(function() {
var myClass = $(this).attr("class");
// getting the value that user typed
var searchString = $("#product-search" + myClass).val();
// forming the queryString
var data = 'productSearch='+ searchString + '&formID=' + myClass;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/product_search.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results" + myClass).html('');
$("#searchresults" + myClass).show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results" + myClass).show();
$("#results" + myClass).append(html);
}
});
}
return false;
});
$("[id^='inventory-ESN-']").change(function() {
var arr = [<?php
$j = 1;
foreach($checkESNArray as $value){
echo "'$value'";
if(count($checkESNArray) != $j)
echo ", ";
$j++;
}
?>];
var carrier = $(this).attr("class");
var idVersion = $(this).attr("id");
if($.inArray(carrier,arr) > -1) {
// getting the value that user typed
var checkESN = $("#inventory-ESN-" + idVersion).val();
// forming the queryString
var data = 'checkESN='+ checkESN + '&carrier=' + carrier;
// if checkESN is not empty
if(checkESN) {
// ajax call
$.ajax({
type: "POST",
url: "<?php echo $path ?>ajax/checkESN.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#esnResults" + idVersion).html('');
},
success: function(html){ // this happens after we get results
$("#esnResults" + idVersion).show();
$("#esnResults" + idVersion).append(html);
}
});
}
}
return false;
});
});
</script>
I would suggest you to bind that ajax call to the submit event of the form and return false at the end, this will prevent triggering default submit function by the browser and only your ajax call will be executed.
UPDATE
I don't know the structure of your HTML, so I will add just a dummy example to make it clear. Let's say we have some form (I guess you have such a form, which submission you tries to prevent)
HTML:
<form id="myForm">
<input id="searchQuery" name="search" />
</form>
JavaScript:
$("#myForm").submit({
// this will preform necessary ajax call and other stuff
productSearch(); // I would suggest also to remove that functionality from
// change event listener and make a separate function to avoid duplicating code
return false;
});
this code will run every time when the form is trying to be submitted (especially when user hits Enter key in the input), will perform necessary ajax call and will return false preventing in that way the for submission.
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}