How to allow ajax form submit on each click? - ajax

I noticed that my ajax form can submit twice at the most, meaning once I submit and retrieve data and want to submit the form again to refine search(it's a search form) it can do it. More than twice it cannot submit, the submit button also becomes disabled. Is there any restriction on ajax form to get submitted multiple times?
My form submission is trigered by
$("form").on("submit", function () ...
ajax:
var getData;
$("form").on("submit", function () {
//$(this).find(':submit').attr('disabled','disabled');
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "ajax2.php",
data: data,
success: function (data) {
getData=data;
//$("#main_content").slideUp("normal",function(){
$(".the-return").show();
if(data!=""){
console.log(data.length);
for (i = 0; i < data.length; i++) {
//availability
if(data[i].weekM==0)
{
var avail="Not available";
}
else
{
avail="Available";
}
if(data[i].endA==0)
{
var avail2="Not available";
}
else
{
avail2="Available";
}
if(data[i].weekE==0)
{
var avail3="Not available";
}
else
{
avail3="Available";
}
$(".the-inner-return").append("<div class='inside_return'><section class='row'><div class='small-10 medium-10 large-8 small-centered medium-centered large-centered columns d_result'><div class='text-center post_id'>" + data[i].id +"</div><div class='small-12 medium-12 large-9 columns subject'>"+ data[i].subject+" Instructor</div><div class='small-12 meidum-12 large-3 columns rate'>" + data[i].rate +"</div><span class='hourly'>hourly</span><div class='small-12 medium-12 large-12 text-center name'>" + data[i].name +"</div><div class='small-12 medium-12 large-4 columns plusneg'><img src='img/happy.png'>" + data[i].plus+"<br/><img src='img/sad.png'>"+ data[i].neg+"</div><div class='small-12 medium-12 large-4 columns gender text-center'>Male<br/>Availabiliy:<br/>Mornings:<span class='avail'>" + avail+"</span><br/>Afternoons:<br/><span class='avail'>"+ avail2+"</span><br/>Evening:<span class='avail'>"+ avail3+"</span></div><div class='small-12 medium-12 large-4 columns score text-center'><h6>Reputation score</h6>"+ data[i].reputation+"</div><div class='row'><div class='small-12 medium-12 large-5 columns shortlist text-center'>Add to Shorlist</div><div class='small-12 medium-12 large-5 columns gettutor text-center'>Get Tutor</div></div><div class='small-12 medium-12 large-12 columns text-center date'>Posted on:<span class='elec'>"+ data[i].postDate+"</span></div></div></section></div>");
//alert(data[i].name)
}
}else{
$(".the-return").hide();
$("#the-return-fail").show();
}
//});//closes #main_content
}
});
return false;
});

There is no counter that prevents multiple ajax submissions. However, if you are attempting to submit before the previous request is complete then you probably are going to have problems if you use global variables.
Here's an example that does multiple submissions.
<form action="" method="post">
<input name="foo" id="foo" type="text" />
<button>Send It</button>
</form>
<div id="output">
</div>
The data here is formatted for JSFiddle's echo service
$("form").on("submit", function(event) {
event.preventDefault();
// prevent next submission before request is complete
$("button").prop("disabled", true);
var dt = new Date();
$.ajax({
url: "/echo/json/",
method: "post",
data: {
json: JSON.stringify({
date: new Date(),
foo: $("#foo").val()
}),
delay: 3
},
success: function(result) {
$("#output").append($("<div>").html(result.foo + " " + result.date));
$("button").prop("disabled", false);
}
});
});

Related

Django - AJAX - how to submit multiple forms?

Here are my two ajax codes for two forms. These two codes are exactly the same, except for button ID
$("#form_1_submit").on('click', function (e) {
e.preventDefault();
var form = $(this).closest("form");
var data = form.serializeArray();
$.ajax({
url: "",
dataType:"json",
type: "POST",
data: data,
success: function() {
alert('ajax request')
},
error: function() {
alert("error")
}
});
console.log(form.html())
});
$("#form_1_submit").on('click', function (e) {
e.preventDefault();
var form = $(this).closest("form");
var data = form.serializeArray();
$.ajax({
url: "",
dataType:"json",
type: "POST",
data: data,
success: function() {
alert('ajax request')
},
error: function() {
alert("error")
}
});
console.log(form.html())
});
And here is my views.py:
class BHA_UpdateView(UpdateView):
model = Different_Model
fields = '__all__'
def post(self, request, **kwargs):
if self.request.is_ajax():
print(self.request.POST)
form_1 = Form_2(request.POST, instance=Model_1.objects.filter(#some_filtering...)
form_2 = Form_1(request.POST, instance=Model_2.objects.filter(#some_filtering...)
if form_1.is_valid():
form_1.save()
return super().post(request, **kwargs)
if form_2.is_valid():
form_1.save()
return super().post(request, **kwargs)
return super().post(request, **kwargs)
There are two problems:
First: $.axax({...}) gives error, instead of success, and I don't know why. But it still saves to DB.
Second: Submitting one form results in the other form's values not saving to DB. This is my current page:
Ideally, clicking one of the Save button should result in saving data to each respective tables in DB. But if I click Save for Overall BHA, it saves
{'bha_name': 'form_1', 'depth_in' : 'form_1', 'depth_out': 'form_1'},
but at the same time saves this to my DB's table for Drill Bit:
{'bit_type': '', 'size': '', 'bit_model': ''}
emptying out the stored values for the table.
why this is happening, and how do I fix it?
++ form_1.is_valid() always returns True. I think this is why form_2's values are empty.
You could render several forms inside a single HTML form element and submit them all together without ajax
<form method="post">{% csrf_token %}
<div class="form-row">
<div class="col-sm">{{ form_a.as_p }}</div>
</div>
<div class="form-row">
<div class="col-sm">{{ form_b.as_p }}</div>
</div>
<div class="form-row">
<div class="col-sm">{{ form_c.as_p }}</div>
</div>
<button type="submit" class="save btn btn-default">Save</button>
</form>

hide bootstrap modal after select redirect instead

I would like to close my modalbox, so I return to the same page, after I click the "Select" button.
I am on shuffle.php. I open the modalbox and call the code in updaterecords.php. When I click Select I should return to shuffle.php. The problem is right now that I am redirected to updaterecords.php.
I try to solve that with adding this code to my AJAX call:
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
But I am still redirected. Is the code I added in the wrong place?
shuffle.php
<div class="modal-footer msg">
<form action="updaterecords.php" method="post">
<input type="hidden" id="fantasy-id" value="" name="id" />
<button type="submit" name="selectStore" >Select</button>
<button type="button" data-dismiss="modal">Close</button>
</form>
</div>
updaterecords.php
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});
Please try to use $('.modal').modal('hide'); on updaterecords.php.
$(document).ready(function() {
$(".btn-open-modal").click(function() {
var id = $(this).data("id");
$('.modal').modal('hide');
$.ajax({
type: 'post',
url: 'getdata.php',
data: {
post_id: id
},
success: function(data) {
console.log(data);
var jdata = JSON.parse(data);
if (jdata) {
console.log("is json");
$("#editBox").modal().show();
$('#id').val(jdata.id);
$("#editBox .modal-title").html(jdata.headline);
$("#editBox .modal-body").html("Weekday: " + jdata.weekday + "<br><br>Description: " + jdata.description); // + " " + $query $query => query
$('#editBox').on('hide.bs.modal', function (data) {
$('#editBox').modal('hide')
})
} else {
console.log("not valid json: " + data);
}
}
});
});
});

ajax not append data on div?

I dont know what the problem is here, I try to append the content, but its not.
var InPro = false;
$(document).ready(function(){
var form = $('#form32');
var submit = $('#submit');
form.on('submit', function(e) {
if(InPro) return;
InPro = true;
// prevent default action
e.preventDefault();
// send ajax request
$.ajax({
url: 'post.php',
type: 'POST',
cache: false,
data: form.serialize(),
success: function(data){
InPro = false;
var item = $(data).hide().fadeIn(800);
$('#post-show').append(data);
$("#form32")[0].reset();
},
});
});
});
and here the post.php:
<?php
include_once("config.php");
include_once("verifica.php");
// No direct access to this file
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!IS_AJAX) {die('Restricted access');}
session_start();
$user = $_SESSION['user'];
$comment = $_POST['comment'];
if($comment==""){
die();
}
$ip = getenv("REMOTE_ADDR");
$data = date ("ymdHis");
$i=mysql_query("INSERT INTO posts (id, foto, user, titulo, youtube, button, data, ip) VALUES ('','0','$user','$comment','$youtube','$button','$data','$ip')");
$idpostfeed = mysql_insert_id();
echo"$comment";
?>
and my form:
<form id="form32" method="post"> <textarea name="comment" id="comment" class="comment" placeholder=""></textarea> <input type="submit" id="submit" class="button" value="Submit Comment"> </form> <div id=post-show></div>
so, I want to show result in #post-show div, but it is not working. what is wrong?
thank you!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Kendo Mobile Appended form elements from treeview not being noticed

I am trying to figure out why appended form elements are not being notice by kendo mobile --- i have tried 10 different fixes but those items just dont get noticed:
This is in the view:
<li>
<div id="currentMovements">
<ul id="curMoves" data-role="listview" ></ul>
</div>
Add Movements:
<div id="routineMovements"></div>
</li>
And this is my script:
<script>
//init move count
var move_count = 0;
function onSelect(e) {
console.log("Selected: " + this.text(e.node));
//add li to movements div
//make each field unique by li
//using move_count
$("#currentMovements ul").append('<li><input type="text" name="moves[' + move_count + ']" data-min="true" id="moves[' + move_count + ']" class="k-input small-move" value="' + this.text(e.node) + '" /><input type="text" name="id[' + move_count + ']" data-min="true" id="sets[' + move_count + ']" class="k-input small-nums" value="3" /> sets of <input type="text" name="reps[' + move_count + ']" data-min="true" id="reps[' + move_count + ']" class="k-input small-nums" value="10" /><span class="clearitem">Delete</span></li>');
//increase move count
move_count++;
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
}
function populateRoutineForm() {
$('#curMoves .clearitem').live('click', function() {
$(this).parent().remove();
});
var routineMovementsData = new kendo.data.HierarchicalDataSource({
data: [
{
text: "Chest", items: [
{ text: "Inclined Bench" },
{ text: "Decline Bench" },
{ text: "Dumbell Presses" }
]
},{
text: "Tricep", items: [
{ text: "Cable Pulldowns" },
{ text: "Skull Crushers" },
{ text: "Close Grip Benchpress" }
]
}
]
});
//todo can we use the MVVM stuf from above to do this now?
$("#routineMovements").kendoTreeView({
dataSource: routineMovementsData,
select: onSelect
});
}
function sendAddRoutine() {
var userID = window.localStorage.getItem("userID");
var routine_title = $('#routine_title').val();
var routine_share = $('#routine_share').val();
///test to see if the field is being noticed
moves = $('#moves[0]').val();
console.log(moves);
$.ajax({
url: endpoint + "app/api/add_routine.php",
dataType: "jsonp",
type: "GET",
data: { userID: userID, routine_title: routine_title, routine_share: routine_share },
success: function (data) {
$('#routineResult').html(data.results);
//app.navigate("#view-routineFeed");
}
});
}
$('#routineDoneButton').click(function () {
sendAddRoutine();
});
</script>
Im wondering if there some way to re-init the view without losing other fields that appear above the append div?

How do i fire validation message on Button click instead of Submit button

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Resources