how to create dynamic ajax submission form - javascript

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.

Related

Submit the form inside jquery dialog box without reloading page

I have php page with a form, I want to open it in a dialog box and submit and show the data on same dialog without reloading the page
php
<form accept-charset="UTF-8">
<button type="submit" class="addButtonClass"></button>
please advice
$('.addButtonClass').submit(function (event) {
event.preventDefault();
....
.. Now your usual ajax post
}
Modify this
$('#add_user1').submit(function(e){
e.preventDefault(); //** prevent normal form submission and page reload
$.ajax({
type: "POST",
cache: false,
url: $link,
data: $('#add_user1').serializeArray(),
success: function (data) {
var json_obj = $.parseJSON(data);
var result = json_obj['result'];
var usergroup = json_obj['usergroup'];
var success = json_obj['success'];
var errorAry = {
}
}
});
return false;
});

Is it posiible to use onClick function on my form submit button?

I store multiple data in a table for enquiry basis.. which is successfully stored in my table. but now i also want to store those same data in Booking basis.
So i used onClick function for storing enquiry data. and now i want to store booking data in table from form submit button.
here is my form submit button code:
<button type="submit" class="booking-btn" onclick="btn_booking_hour();" id="btn_booking_hour">Book Now</button>
Here is my form action:
<?php echo form_open('booking/'.$product->id); ?>
And here my function:
function btn_booking_hour()
{
var date = $('#datehour').val();
var renter_id = $("#ownerid").val();
var guests_quantity = $('#no_of_guests').val();
var property_id = $('#property_id').val();
var selectedIds="";
var selectedObject = document.getElementsByClassName('hour_slots_available slot_activated');
for(var i=0;i<selectedObject.length;i++)
selectedIds+=selectedObject[i].id+",";
if(selectedIds == ""){
alert("Please select Hour-Slot(s) before Booking");
}
else{
$.ajax({
type: 'POST',
dataType:'json',
url:baseURL+'site/rentals/ajaxhourshow',
data:{'selectedHours':selectedIds,'property_id':property_id,'date':date,'guests_quantity':guests_quantity,'renter_id':renter_id},
success: function(responce){
var myJSON = JSON.stringify(responce);
var packet = $.parseJSON(myJSON);
var prd_id=packet.property_id;
var hour_slots=packet.hour_slots;
window.location.href = baseURL+'booking/'+prd_id;
}
});
}
}
Please suggest me how can i submit a form with data within their onClick function. Thanks..
Not sure if you are using a form, if you are using it you can can use onsubmit handler and return the action. In that case you wont need onclick handler in the button
<form onsubmit = "return btn_booking_hour()">
// Rest of code
</form>
You can also do like this
$('#form').on('submit',function(e){
e.preventDefault();
// rest of the code
})
you can use this code
function btn_booking_hour(){
// your other code
document.getElementById('formid').submit();
// formid = form id
}
or also use jquery
function btn_booking_hour(){
// your other code
$('#formid').submit();
// formid = form id
}
i got your point so you can also use it
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
rest of your code
});
});

Forms with Ajax send with multi-parameter and A href

within the form element I send data with a href. Using the JavaScript (as defined below), it works perfectly.
I want to send the forms now with Ajax, unfortunately it does not work. Do you have a solution for me. jQuery is included on the page.
Thank You!
function sendData(sFm, sID, sFn, sCl) {
var form = document.getElementById(sFm);
form.sid.value = sID;
form.fnc.value = sFn;
form.cl.value = sCl;
form.submit();
}
Send Data
My new Code:
function sendData(sFm, sID, sFn, sCl) {
var form = $("#"+sFm);
form.submit( function() {
var sid = $('input[name="sid"]').val(sID);
var fnc = $('input[name="fnc"]').val(sFn);
var cl = $('input[name="cl"]').val(sCl);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: {sid: sid, fnc: fnc, cl: cl}
}).done(function( e ) {
});
});
form.submit();
}
$("form").submit(function() { // for all forms, if you want specially one then use id or class selector
var url = $(this).attr('action'); // the script where you handle the form input.
var method = $(this).attr('method');
$.ajax({
type: method,
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // handle response here
}
});
return false; // avoid to execute the actual submit of the form.
});
:) , Thanks
Just because we don't want to submit all form by ajax so we can set a data-attribute to form tag to indicate, will it should be submit by ajax or normally ,, so ,,
$("form").submit(function() { ...
if($(this).attr('data-ajax') != "true") return true; // default hanlder
...
so If form is written like this :-
<form action="/dosomething" method="post" data-ajax="true"> </form> // will be sumit by ajax
<form action="/dosomething" method="post" data-ajax="false"> </form>
// will be sumit by default method

How to reset event.preventDefault() of a form submit event?

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();
}

Jquery and the plug-in Validate, testing for no errors

I have obviously done something stupid or failed to understand some fundamental process. Very early days playing with this.
I am trying to check for a form being validated, when the Submit Button is clicked with the onClick method.
<input class="submit" type="submit" value="Submit" onClick="submitForm()" />
I am using Jquery and the plug-in Validate. The problem I have is validating on each field is occurring, but if I click on submit with no data or not every field has been tested, I would need to validate the whole form, before submitting, I should get a return of false from validate().form(). This is not occurring as the else statement in submitForm() is never being executed.
On an empty form, after clicking submit the field error messages are shown, but my testing of a return for false, does not seem to work.
$(document).ready(function() {
$('#formEnquiry').validate();
});
function submitForm() {
$('#msgid').append('<h1>Submitting Form (External Routine)</h1>');
if ($('#formEnquiry').validate().form()) {
$("#msgid").append("<h1>(Outside Ready) VALIDATED send to PHP</h1>");
}
else {
$('#msgid').append('<h1>(Outside Ready) NOT VALIDATED</h1>');
}
};
An example of Ajax
$(function() {
$("#ipenter").submit(function() {
var ip = $("#ip").val();
var date = $("#date").val();
var spammer = $("#spammer").val();
var country = $("#country").val();
var total = $("#total").val();
var dataString = $('#ipenter').serialize();
$.ajax({
url: "/test/process",
data: dataString,
type: "POST",
success: function(msg) {
$('#ipenter').append('<h3 class="gotin">Post succesfull!');
$('h3.gotin').delay(8000).fadeOut(500);
},
error: function(data){
$('#ipenter').prepend('<h3 class="didnt">Post sucked!');
$('h3.didnt').delay(8000).fadeOut(500);
}
});
return false;
});
});
You dont really even need the val() part
You can also throw some validation into this script before the ajax
if (spammer == "") {
$("#spammer_error").show();
$("input#image").focus();
return false;
This is a basic example of ajax(I'm using codeigniter so you may need to use a valid URL for the url)

Categories