Send Ajax message setTimeOut m delay between actions - javascript

Hi i have been trying to add even delay() or setTimeOut to this simple send message, but i think i do not understand quite well how does this works, i have been "wrapping" the functions but everytime i got a lots of syntax erros, if i "fix" them i got nothing but all actions done one after other, even if i set delay(8000) no delay is reflected actually
this is the script for send message
$.ajax({
type: "POST",
url: "sendtofriend.php",
data: dataString,
success: function() {
$('#message').css("display", "none");
$('#messagein').css("display", "block");
$('#messagein').html("<div id='messageinin'></div>");
$('#messageinin').html("<h2><%= t('generales.thankks') %></h2>")
.append("<p><%= t('generales.msgsent') %>.</p>")
.fadeIn(1500, function() {
$('#messagein').append("<img id='checkmark' src='images/check.png' />");
});
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
}
});
return false;
});
});
i have tried a lot of stuff, something like this for example
$.ajax({
type: "POST",
url: "sendtofriend.php",
data: dataString,
success: function() {
$('#message').css("display", "none");
$('#messagein').css("display", "block");
$('#messagein').html("<div id='messageinin'></div>");
$('#messageinin').html("<h2><%= t('generales.thankks') %></h2>")
.append("<p><%= t('generales.msgsent') %>.</p>")
.delay(8000)
.fadeIn(1500, function() {
$('#messagein').append("<img id='checkmark' src='images/check.png' />");
});
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
}
});
return false;
});
});
My goal is #message to dissapear when confirmation div '#messagein' is visble, and then dissapear the confirmation and reapper the form to submit another message.
this is the HTML
<div id='messagein'></div>
<div id='message'>
<form action="" method="post" id="sendfriendd">
<div id="inpumail" >
<!-- <input type="text" name="" id="youremailaddress" size="40" value="<%= t('generales.tucorreoo') %>" class="text-input" /> -->
<input type="text" name="youremailaddress" id="youremailaddress" size="40" value="<%= t('generales.tucorreoo') %>" class="text-input" onblur="if(this.value == '') { this.style.color='#ccc'; this.value='<%= t('generales.tucorreoo') %>'}" onfocus="if (this.value == '<%= t('generales.tucorreoo') %>') {this.style.color='#000'; this.style.fontStyle='normal'; this.value=''}" style="color: rgb(120, 120, 120); font-style: normal;"/>
<label class="error" for="youremailaddress" id="youremailaddress_error">This field is required.</label>
</div>
<br>
<div id="inpumail2" >
<input type="text" name="friendsemailaddress" id="friendsemailaddress" size="40" value="<%= t('generales.amigcorreoo') %>" class="text-input" onblur="if(this.value == '') { this.style.color='#ccc'; this.value='<%= t('generales.amigcorreoo') %>'}" onfocus="if (this.value == '<%= t('generales.amigcorreoo') %>') {this.style.color='#000'; this.style.fontStyle='normal'; this.value=''}" style="color: rgb(120, 120, 120); font-style: normal;"/>
<label class="error" for="friendsemailaddress" id="friendsemailaddress_error">This field is required.</label>
</div>
<br>
<input type="submit" name="Submit" value=" <%= t('generales.enviarcorreoo') %> " class="enterrenvi">
</form>

The function delay doesn't work in this example (after append) since it only affects jquery animations. setTimeout should do the job when used properly.
try removing the delay and changing:
$('#message').fadeIn(1500, function() {
$('#messagein').css("display", "none");
$('#message').css("display", "block");
});
into:
setTimeout(function() {
$('#message').fadeIn(1000);
$('#messagein').fadeOut(1000); //animate display none
},5000); //timeout 5 secs

Related

Modal window.Jquery is not showing on fadeIn()

I am trying to create a feedback form. All inputs and textareas are not empty and the user has clicked on the checkbox which says I am not a robot, then the button Send (отправить) becomes active and I want to say Thank you,we will contact with you soon! in a popup window after form submission.
But..what is wrong?
$(document).on('change', '.main-pc input:checkbox', function() {
if($(this).is(':checked')){
$(".main-pc input[type=submit]").removeAttr('disabled');
$('.main-pc input[type=hidden].valTrFal').val('valTrFal_true');
}
else {
$(".main-pc input[type=submit]").attr('disabled','disabled');
$('.main-pc input[type=hidden].valTrFal').val('valTrFal_disabled');
}
});
$(".main-pc").ready(function() {
$('.main-pc').submit(function() { // проверка на пустоту заполненных полей. Атрибут html5 — required не подходит (не поддерживается Safari)
if (document.form.input.value == '') {
valid = false;
return valid;
}
$.ajax({
type: "POST",
url: "/app.mail.php",
data: $(this).serialize()
}).done(function() {
$('.js-overlay-thank-you').fadeIn();
$(this).find('input').val('');
$('.main-pc').trigger('reset');
});
return false;
});
});
$('.js-close-thank-you').click(function() { // по клику на крестик
$('.js-overlay-thank-you').fadeOut();
});
$(document).mouseup(function (e) { // по клику вне попапа
var popup = $('.popup');
if (e.target!=popup[0]&&popup.has(e.target).length === 0){
$('.js-overlay-thank-you').fadeOut();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-writetous">
<form class="main-pc" id="form" >
<input type="text" required="" placeholder="Имя" name="txtname" required>
<input type="email" placeholder="Email" name="txtemail" required>
<textarea name="txtmessage" placeholder="Введите сообщение.." rows="5" required></textarea>
<label><input type="checkbox">Я не робот</label>
<input type="hidden" name="valTrFal" class="valTrFal" value="valTrFal_disabled">
<input type="submit" class="button" value="Отправить" disabled="disabled" name="btnsend">
</form>
</div>
<div class="overlay js-overlay-thank-you">
<div class="popup js-thank-you">
<h5>Сообщение отправлено!</h5>
<p><strong>Наши администраторы свяжутся с вами в ближайшее время!</strong></p>
<hr>
<div class="close-popup js-close-thank-you">x</div>
</div>
</div>
document.form.input.value
Above line is creating issue in your code As you wrote in your question that you are using this for safari browser, May be it will work on safari but will not work on chrome or Mozilla so check browser like this
var is_safari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
and then put your code in if conditon
if(is_safari){
if (document.form.input.value == '') {
valid = false;
return valid;
}
}
And you can also check other example for form validation in safari.
Required Attribute Not work in Safari Browser

casperjs fill form doesn't work

I have a problem with casperjs.
I want to fill a form but casperjs says the form is not found... In the code I can't see a form name so I tried to use the formid without success
Here is the source code of the website where I want to fill the form
<tr class="wcontent" valign="top">
<td></td>
<td id="wcontent_login" class="widgetMiddleMiddle" style="display: block; height: 213px;">
<iframe frameborder="no" src="/WebInt.nsf/loginWidget.xsp?widgetUniqueId=anonymous-login-default" scrolling="no">
<!DOCTYPE html>
<html lang="de">
<head>
<body class="xspView tundra">
<form id="view:_id1" class="xspForm" enctype="multipart/form-data" action="/GI7/WebInt.nsf/loginWidget.xsp?widgetUniqueId=anonymous-login-default" method="post">
<div id="inactive_loginWidget">
<div class="inactive_loginLeft">Anmeldung</div>
<div class="inactive_loginRight">
<div style="height:27px;background-color:#004178;color:white;padding:10px; width:227px;margin-bottom:5px;text-align:center;">
<div>
<input id="username" type="text" placeholder="Benutzername" onkeypress="return handleKeyPressed(event)" onfocus="var elem = document.getElementById(''); if(elem != null) {hideLabel(elem, 'username');}" onblur="var elem = document.getElementById(''); if(elem != null) {if(document.getElementById('username').value == '') { showLabel(elem); } else { hideLabel(elem); }}" name="username" autocomplete="off" vk_19ae7="subscribed">
</div>
<div class="cleaner3px"></div>
<div>
<div class="cleaner3px"></div>
<div title="Anzahl der Spalten für die Darstellungsbreite des Browsers einstellen.">
<div class="cleaner10px"></div>
<div class="button" style="margin-left: -5px; cursor: default;" onmouseover="setHoverEffectButton(this, '');" onmouseout="resetHoverEffectButton(this, '');" onmousedown="setPressedButtonEffect(this, '');" onclick="handleKeyPressed(event, true)">
</div>
</div>
<script type="text/javascript">
<input id="view:_id1__VUID" type="hidden" value="!1k37604fezbng88zt78ksqv5x!" name="$$viewid">
<input type="hidden" name="$$xspsubmitid">
<input type="hidden" name="$$xspexecid">
<input type="hidden" name="$$xspsubmitvalue">
<input type="hidden" name="$$xspsubmitscroll">
<input type="hidden" value="view:_id1" name="view:_id1">
</form>
</body>
</html>
</iframe>
My casperjs Code
var casper = require("casper").create({
verbose: true,
logLevel: "debug"
});
function wait5seconds() {
casper.wait(5000, function() {
this.echo('2');
});
}
// casper.options.waitTimeout = 40000;
casper.start("https://Testseite.de/WebInt.nsf/loginWidget.xsp", function() {
this.echo("Page title: " + (this.getTitle()));
wait5seconds();
});
casper.then(function(){
this.fillSelector('Formname ????', {
'username': 'Hans',
'password': 'Wurst'
}, true);
});
casper.then(function() {
casper.capture('Test2.png');
});
casper.then(function() {
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});
casper.then(function() {
casper.capture('Test3.png');
});
casper.run();
I also tried to solve my problem with queryselector but still no success :(
I think you are missing 'form; from the selector.
Something along the lines of:
this.fillSelectors('form#view:_id1', {
casper.then(function(){
this.fillSelector('Formname ????', {
'username': 'Hans',
'password': 'Wurst'
}, true);
});
This question might help: How to use fillSelectors in casperjs
Yes but every time i start the Test it breaks in step 4 :
casper.then(function(){
this.echo("Formstart");
this.fillSelector('form#view:_id1', {
'username': 'XX',
'password': 'XX'
},true);
this.echo("Formend");
});
Formstart works but Formend does not get printed so the mistake must be there ....
I changed it now to :
casper.then(function(){
this.echo("Formstart");
this.fillSelector('form#view:_id1', {
'input[name="username"]': 'XX',
'input[name="password"]': 'Xx'
},true);
this.echo("Formend");
});
but still no success :(
Finally i solved it with an debugger and Post request:
casper.open('https://XXX/WebInt.nsf',
{
method: 'post',
data: {'username':'XX','password':'XX'}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
:)

Adding 1 to div onsubmit

i have a form that i submit to a database using ajax, there a div on the page which has a database binding which counts the total number of records submit on page refresh. now what i want to do is onsubmit of the form, i should add 1 to the binding in the div which counts the total number of records submitted
<div id="count_div"></div>
<form id="form2" name="form2" method="POST" action="<%=MM_editAction%>">
<input name="comment" type="text" id="comment" size="50" />
<input name="imageField3" type="image" id="imageField3" src="imgs/buttons/comment.png" align="bottom" />
<input name="wardrobe" type="hidden" id="wardrobe" value="1" />
<input name="comme" type="hidden" id="comme" value="2" />
<input name="comfn" type="hidden" id="comfn" value="3" />
<input name="photo_id" type="hidden" id="photo_id" value="4" />
<input name="ctype" type="hidden" id="ctype" value="picture" />
<input name="resp_email" type="hidden" id="resp_email" value="4" />
<input type="hidden" name="MM_insert" value="form2" />
</form>
AJAX
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>
if what I understood is correct: you want to increment th value of the "count_div" div then try this:
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("#count_div").html(parseFloat($("#count_div").html())+1);
$("input[type=text]").val("");
});
});
});
UPDATED:
<script>
$(document).ready(function(){
$("#form2").on('submit',function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "int_p_cmt.asp",
data: data
}).success(function() {
window.counter=parseInt($('#count_div').html());
window.counter++;
$('#count_div').html(window.counter);
$("#msg_div").append("<div class='messages' style='border:1px purple solid; padding:2px; margin:5px;'>Your comment has been saved </div>");
setTimeout(function() {
$(".messages").fadeOut(function(){
$(".messages").remove();
});
}, 1000);
$("input[type=text]").val("");
});
});
});
</script>

jQuery function problems

I can't execute this jquery function properly. When I click on submit's form, only shows the two first alerts and then the page reloads. So I click again on the form's submit with the page reloaded and then shows the rest of the alerts (beginning by the third one) and then the function works fine.
In conclusion: I need to click on the form's submit two times instead of one to execute the function.
Any idea? Thank you.
JS Code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
alert("enters script");
$(function () {
alert("enters jquery function");
$(".submit").click(function () {
alert("enters click submit function");
var name = $("#name").val();
var date = $("#date").val();
var dataString = 'name=' + name + '&date=' + date;
alert("saved variables");
if (name == '' || date == '') {
alert("enters if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
alert("enters else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function () {
alert("enters success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresh();
}
});
}
return false;
});
});
</script>
HTML Code:
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
use the event.preventdefault to stop the submission of the page
http://api.jquery.com/event.preventdefault/
Your problem is using submit buttons, they have some default behaviors other than what you add as a event to it.
replaced this:
<input type="submit" value="Submit" class="submit" />
with:
<input type="button" value="Submit" class="submit" />
this you working DEMO
other than changing the submit button to a regular button, you can fix your code by disabling that default behaviors, adding onsubmit to your form node:
<form method="post" name="form" onsubmit="return false;">
<!--your stuff-->
</form>
Try this:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function(){
alert("entra en la funcion del clic del submit");
var nombre = $("#nombre").val();
var fecha = $("#fecha").val();
var dataString = 'nombre='+ nombre + '&fecha=' + fecha;
alert("variables guardadas");
if(nombre=='' || fecha=='')
{
alert("entra en el if");
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
alert("entra en el else");
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
alert("entra en el success");
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
refresca();
}
});
}
return false;
});
});
First of all, thank you to everybody for your help.
Finally the main problem comes from other part of the code. I was using pjax (https://github.com/thybag/PJAX-Standalone) to replace the form with other html document (in this case page1.html) after doing the mysql insert through "join.php". And I'm not calling the jquery function properly.
Explanation: You begin in page1.html, then click on "Go To Page 2" (This replace the div "content" with the body of page2.html). Then complete the form and submit it. When you click on submit, activates the jquery function (join.php mysql insert inside) and finally replace again the div "content".
Solution (this works):
page1.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="pjax-standalone.js"></script>
<script type="text/javascript">
pjax.connect({
'container': 'content',
'beforeSend': function(){console.log("before send");},
'complete': function(){console.log("done!");
if($("#button_pg_2").length)
{
$( document ).ready(function()
{
$(".submit").click(function()
{
var nombre = $("#name").val();
var fecha = $("#date").val();
var dataString = 'name='+ name + '&date=' + date;
if(name=='' || date=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax(
{
type: "POST",
url: "join.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
replace();
}
});
}
return false;
});
});
}
}
});
</script>
<script type="text/javascript">
function replace()
{
pjax.invoke('page1.html', 'content');
}
</script>
</head>
<body>
<div id="header">
This div never changes
</div>
<div id="content">
Go To Page 2
</div>
</body>
</html>
page2.html
<html>
<body>
<form method="post" name="form">
<ul>
<li>
Name <input id="name" name="name" type="text" />
</li>
<li>
Date <input id="date" name="date" type="date" />
</li>
</ul>
<div >
<input type="button" id="button_pg_2" value="submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
</body>
</html>

Submit form data both on clicking enter and hitting the submit button

Here's a form that I have:
<form class="form-horizontal" id="login-form">
<input name="email" id="email" type="email" size="30" class="span4" placeholder="Email" style="margin-top:20px; margin-left:20px; width: 270px;"/>
<br>
<input name="passwd" id="passwd" type="password" class="span4" placeholder="Password" style="margin-top:10px; margin-left:20px; width: 270px;"/>
<br><br>
<input type="button" id="login" name="login" value="Go" class="btn btn-custom" style="width:30%; margin-left:30px; margin-top:20px"/>
<br>
<br>
</form>
Here a ajax call I make using JavaScript to submit the data on clicking the button:
$('#login').click(function(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
});
How can I submit the data both by pressing the enter key and clicking on the submit button?
I have updated code. Create a function and call it on both textbox keypress event and identify submit button then call function and on click event of button.
function submitLogin() {
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
$('#email').keypress(function(e) {
if (e.which == '13') {
submitLogin();
}
});
$('#passwd').keypress(function(e) {
if (e.which == '13') {
submitLogin();
}
});
$('#login').click(function(){
submitLogin();
});
How about to change input type to "submit" and input click event into form submit?
<input type="submit" id="login" name="login" value="Go" class="btn btn-custom" style="width:30%; margin-left:30px; margin-top:20px"/>
JQuery
$('#login-form').submit(function(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
});
You should be able to add keypress function on both email and password fields.
$('#email').keypress(function(e){
if (e.keyCode == 13) {
$('#login-form').submit(/*...*/);
}
}
I gave you example for one field.
Use On method to work on Entering and clicking
$('#element').on('click keypress', function(event) {
var check = 1; // Default for Click
if (e.keyCode == 13) //When Enter Key is pressed
{
var check = 1;
}
else
{
var check = 0; // other keys pressed
}
if (check == 1)
{
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
});
this is the idea:
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
runAjax();
// or
// runSubmit();
}
});
$('#login').click(function(){
runAjax();
//or
//runSubmit();
});
function runAjax(){
$.ajax({
url:"script.php",
type:'POST',
dataType:"json",
data: $("#login-form").serialize()
}).done(function(data){
//do domething
});
}
function runSubmit(){
$("form").submit();
}

Categories