I have a form that I am intercepting through Ajax / jQuery.
The problem here is in case some fields are not filled I show errors from textStatus into an error div.
My function then removes the div completely and reinserts a new empty one after removal of the original one (to have the div again for error showing).
What happens is that if I submit the form multiple times the new error div will be inserted multiple times in the dom, and the errors will be presented three times immediately in the original error div. I of course only need one error div and one set of errors to be shown.
My script is as follows:
jQuery(function ($) {
$(document).ready(function () {
$("#AddModel").on("submit", function (e) {
var SubmitButton = $("#AddBtn");
SubmitButton.blur();
var form = $(this);
var postData = new FormData($("#AddModel")[0]);
var errors = $('#errors');
var theForm = $('#theForm');
var divAlert = "<div id=\"errors\">AAA<\/div>";
$.ajax({
type: 'POST',
url: form.prop('action'),
processData: false,
contentType: false,
data: postData,
success: function (data) {
console.log(data);
},
error: function (textStatus) {
var json = JSON.parse(textStatus.responseText);
$.each(json, function (key, value) {
var errorVar = "";
errorVar += "<div id=\"error\" class=\"col-lg-6 alert alert-danger\">";
errorVar += "" + value + "";
errorVar += "<a class=\"close\" data-dismiss=\"alert\">×<\/a>";
errorVar += "<\/div>";
errors.append(errorVar);
});
if (errors.is(":visible")) {
errors.not('.alert-important').delay(7000).fadeOut(350).promise().done(function () {
errors.remove().promise().done(function () {
$(divAlert).insertAfter(theForm);
})
});
}
}
});
e.preventDefault();
});
});
});
for example at initial stage I will have this situation in the page:
<div id="errors"></div>
If I press submit button 3 times in a row at the end, after showing the errors and removing the div I will get this situation in the page:
<div id="errors"></div>
<div id="errors"></div>
<div id="errors"></div>
What happens right before the insertion of those three elements is:
<div id="errors" style="display: none;">
I guess this is during the fadeOut(350) part of the script.
What I would like to achieve is if the button is pressed then wait for the script to finish and then be able to submit again.
I don't like the timeout option as I don't know exactly how much time the browser will take to display the errors and then removing and reinserting the error div. So how can I disabled subsequent submission until this part of the script has ended? ->
if (errors.is(":visible")) {
errors.not('.alert-important').delay(7000).fadeOut(350).promise().done(function () {
errors.remove().promise().done(function () {
$(divAlert).insertAfter(theForm);
})
});
}
You can trace your script progression by declaring a variable right before your on('submit') function and use it to limit submissions:
jQuery(function ($) {
$(document).ready(function () {
var isEnded=true;
$("#AddModel").on("submit", function (e) {
if(isEnded){
isEnded=false;
.... YOUR CODE
}
});
});
});
When your specific portion of code is over, just add :
isEnded=true;
Related
On first.php
I use jquery location.href ="www.localhost.com/second.php?text="+param to pass the input parameter to second.php (on hitting enter).
code for first.php:
$(document).ready(function() {
$("#txt").keypress(function() {
var name = $("#txt").val();
if (event.keyCode == 13) {
location.href = "http://www.localhost.com/second.php?text="+param;
}
});
});
On second.php
I get the value using $("#").val(decodeURIComponent($.urlParam("text")));
However I cannot get it to load automatically after the second page loads. So I am force to let the input value and data load when the input field is click.
here is the jquery:
$("#txt").one("mouseup", function() {
$("#txt").val(decodeURIComponent($.urlParam("text")));
var variable = $("#txt").val();
$.post("xxxx.php", {
text: variable
}, function(data, status) {
$("#show").html(data);
return;
});
});
I finally figure it out the answer to the question. To load the data immediately on second page(second.php) the Jquery script I added was:
$(document).ready(function() {
$(function() {
$("#txt").val(decodeURIComponent($.urlParam("text")));
var variable = $("#txt").val();
$.post("xxxx.php", {
text: variable
}, function(data, status) {
$("#show").html(data);
return;
});
});
});
There wasn't any need to add a listener for the window to load. The listener is already in the library.
so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!
The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.
I have this scenario:
I have a simple php file with only few html elemnts: a div called switch, another called lamp and a couple of buttons.
The two buttons are labeled On and Off.
The lamp div is empty.
The switch div is empty too, but is updated using jQuery and Ajax with the content of a txt file, that only contains one word: it could be On or Off.
What i'm traying to achieve is this: whenever the file is updated with the word On or Off i would like the On or Off button to be triggered correspondingly and the lamp div to change the background color. Is it possible?
UPDATE:
Example:
(function($){
$(document).ready(function() {
$.ajax({
url : "testfile.txt",
dataType: "text",
success : function (data) {
$("#switch").html(data);
// this doesn't seems to work...
var word = data.toLowerCase();
$('#' + word).trigger('click');
// this works
$(document).ajaxStop(function(e){
var response = $("#switch").html();
$("#" + response.toLowerCase()).trigger("click");
});
var $container = $("#switch");
var refreshId = setInterval(function()
{
$container.load('testfile.txt').html();
}, 2000);
}
});
});
})(jQuery);
<div id="switch"></div>
<div id="on" class="button">On</div>
<div id="off" class="button">Off</div>
<div id="lamp"></div>
Since the response is only one word. Why not try
var word = data.toLowerCase();
$('#' + word).trigger('click');
in the success callback.
If you have only one ajax request, you can do like this:
$(document).ajaxStop(function(e){
var response = $("#switch").text();
// do what you want with variable response here
$("#" + response.toLowerCase()).trigger("click");
});
Maybe this can help for what you need:
(function($){
$(document).ready(function() {
var $container = $("#switch");
$container.load("testfile.txt", function() {
setInterval(function() {
$container.load("testfile.txt");
}, 2000);
});
});
})(jQuery);
Use clearInterval() to stop the timer when needed.
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
I make div which refresh when file is updated. But it continuously refresh (fade out and fade in every second).I't source test2.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js>
</script>
<script>
$(document).ready(function() {
$('#loaddiv').load('check.chat.php');
});
var auto_refresh = setInterval( function() {
$.ajax(
{
type: 'POST',
data:"id=100",
url: "check.chat.php",
success: function(result)
{
if($("#loaddiv").html() != result)
{
$("#loaddiv").fadeOut("fast")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
}
}
});
}, 1000);
</script>
<div id="loaddiv"></div>
And file on site: **
Who knows what's the problem?
This part:
$("#loaddiv").fadeOut("fast")
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
Should be:
$("#loaddiv").fadeOut("fast", function(){
$("#loaddiv").html(result);
$("#loaddiv").fadeIn("slow");
});
In your case, both fades are called at the same time, making an animation queue, causing it to go from one phase to another in about the same time the interval triggers again.
UPDATE
To see logs, do this: console.log("html: ", $("#loaddiv").html(), "result: ", result);