How to call function on submit in codeigniter - javascript

I need to call to function onsubmit in codeigniter.
One for submit and one for Access some id.
I like to know that how to call two function on submit, also i need to know how to submit form by ajax if i have true condition.
My ajax controller:
$(document).ready(function(){
add = function (){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
// i need to submit my form here...
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
});

jquery you can use :
$("#formId").submit(function(e){
e.preventDefault();
//your code
});
And in javascript
<form action="" method="post" onsubmit="return yourfunction()">
</function>
function yourfunction()
{
//your code
return true;
}

It doesn't matter whether you are using codeigniter or normal php simply use Ajax, Check this link
$('input#submitbuttonid').click( function() {
$.ajax({
url: 'url to post data',
type: 'post',
dataType: 'json',
data: $('form#formid').serialize(),
success: function(data) {
...your data logic comes here
}
});
});
And simple Javascript ,
$('form#formid').submit();

you can handle you form submission by jquery. to do this you can use one of jquery plugin for this purpose. i refer JqueryForm plugin to you.
by this plugin you can do something like this:
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
var options = {
target: '#message_box_id', // target element(s) to be updated with server response
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
i don't know what exactly you want to do but maybe you can use before submit feature of this plugin to solve you issue. for example you can try this way
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: your_ajax_function,
success: showResponse // post-submit callback
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
your_ajax_function = function(){
$.ajax({
// your ajax body
});
}
});

//stop the form from submitting you can select form by adding a class or id
$('form').submit(function(e){e.preventDefault});
//when a button with id submit is clicked
//fire ajax
$('button#submit').on('click',function(){
// your ajax code
});

Related

Data disapearing after AJAX request [duplicate]

I am trying to perform an ajax call inside a form (a Drupal node edit form) , but it seems when performing the call, it submits the form for some reason. Here is a sample code:
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: {"text": jQuery("#edit-body").html()
},
success: function(result){
console.log(result);
}
});
I can replicate this just by executing it in the console, but I attach this to a button click function inside the form. Any tips on preventing the form from submitting, on a POST ajax call?
Here is the full code as requested
jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button" id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>');
jQuery("#proofread_bot-submit").click(function(event){
event.preventDefault();
jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");
jQuery.ajax({
type: "POST",
url: "proofread_bot/check",
dataType: "html",
data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
},
success: function(proofread_result){
jQuery("#proofread_bot-submit").after(proofread_result);
jQuery("#proofread_bot_throbber").remove();
}
});
});
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (isValid) {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
e.preventDefault();
return false;
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
If you are using a input type="submit" button, then you need to do a return false; at the end of the function to prevent it from submitting.
Another solution is to e.preventDefault() on the button click
$(".button").click(function(e){
e.preventDefault();
return false;
});
you can change submit button type to just a button type and add "onclick" event to that button.
input type="button" value="savebutton" onclick="return doThisOnClick();"
function doThisOnClick(){
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
I think this is most straightforward.

Issue with nested Ajax calls

I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.
This is how the code works:
(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.
(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated
(3) The form is then submitted via Ajax as well.
(4) If successfully submitted it perform another Ajax call to get the table updated.
First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?
Here it is the javascript code, server side all works just fine:
$(".edit-transaction").click(function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('updated successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Create a new transaction via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('created successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Thanks for any help
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".
You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.
// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
const $table = $(this);
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: (data) => $table.html(data.html)
});
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
// you can add some data to the response
// to differentiate between created and updated. Eg response.actionType
console.log('created or updated successfully')
// load the table with the new content updated
$("#display-transaction-list").trigger('load.table');
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})

Prevent double submits form

I have a form which has a submit button. If I click this submit button then JSON will be posted to a webservice through AJAX:
$("#msform").submit(function (e) {
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
});
The webpage will also load and go to another page.. While loading the user can click multiple times on the Submit button, if he does that then for multiple times the AJAX post will be done to the webservice.
I tried this code to fix this but it does not work:
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$(this).on('submit', function (e) {
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
$('#msform').preventDoubleSubmission();
Any idea why double posting is not prevented??
The solution is to use a variable called wasSubmitted which verify if ajax request was already sent.
var wasSubmitted = false;
$("#msform").submit(function (e) {
if(!wasSubmitted) {
wasSubmitted = true;
$.ajax({
url: 'https://example.com/webservice',
type: 'POST',
data: formData1,
crossDomain: true,
dataType: 'json',
jsonpCallback: 'callback',
success: function (data) {
console.log(data);
}
});
return wasSubmitted;
}
return false;
});
I think a simple preventDefault would be enough
$("#msform").submit(function (e) {
e.preventDefault();
$.ajax(..)
The solution, that comes to my mind first, is to disable the button onclick with JS.
document.getElementById("btn_id").setAttribute("disabled","disabled");

Pause then allow or not a post with JQuery

I work with Telerik and when I submit changes from my grid I want to check some data with an AJAX call and then, if the data is OK continue the submit.
I don't really know how the data is submitted but I get it works like a classic form. Is-it possible to "pause" and "restart" the post ?
function onSubmit(e) {
// Pause Submit
$.ajax(
{
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
async: false,
success: function (check) {
if(check)
{
// Allow Submit
}
else
{
alert('error');
// Stop Submit
}
}
});
}
Try this way:
function onSubmit(e) {
$.ajax(
{
url: '/MyController/MyAction/',
type: 'POST',
dataType: 'json',
async: false,
success: function (check) {
if(check)
{
// Allow Submit
}
else
{
alert('error');
// stop at error
e.preventDefault();
}
}
});
} // end onSubmit

Submit form if any Ajax error

How can I make ajax/jquery submit the form in case of ANY ajax error?
I want the regular submit pageload php validation to take over, in case of any ajax error
If I try and replace 'validateform.php' with 'xxxxtest.nothing', the form does not submit, and js throws console error "POST http://example.com/xxxxtest.nothing 404 (Not Found)"
$('#myform').submit(function(e) {
var $theform = $(this);
$.ajax({
url: 'validateform.php',
type: 'POST',
cache: false,
timeout: 5000,
async: false,
data: $theform.serialize(),
success: function(data) {
$('#errordiv').html('<p class="error">' + data + '</p>');
$('#errordiv').slideDown();
},
error: function(e){
return true; // form should be submitted
}
});
return false;
});
jQuery ajax function is asynchronous, so return false is always exectuted. So, instead:
error: function(e){
$('#myform').unbind('submit').submit();
}
Updated based on comments below.
JSFiddle: http://jsfiddle.net/9Q2L2/
Check if this works to you:
http://jsfiddle.net/don/9Q2L2/3/
Create a second php file to send the form and run this php file if any ajax error.
Use the unbind and the submit again.
You should try:
$('#myform').submit(function (event) {
var $theform = $(this);
$.ajax({
url: 'validateform.php',
type: 'POST',
cache: false,
timeout: 5000,
async: false,
data: $theform.serialize(),
success: function (data) {
$('#errordiv').html('<p class="error">' + data + '</p>');
$('#errordiv').slideDown();
//prevent submit
event.preventDefault();
},
error: function (event) {
//form is submitted
}
});
//None of them should be placed here, the code is always executed
//event.preventDefault();
//return false;
});
More about preventDefault()

Categories