can we use "window.setTimeout" on button click event? - javascript

I am writing code for page reload after getting response from button click event in javascript. But its not working page is not getting reload after button click event.
My form
<div class="form-group">
<label>My Label Name</label>
<select class="form-control my_select2_id" id="my_select2_id" name="my_select2_id" tabindex="-1">
<option></option>
<?php if($table_rows != '') {
foreach($table_rows as $each_row) {?>
<option value="<?=$each_row['id']; ?>"><?=$each_row['my_column']; ?></option>
<?php } }?>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control second_field" id="second_field_id" name="second_field_id" placeholder="Enter second field ID">
</div>
<div class="form-group">
<input type="text" class="form-control my_third_field" id="my_third_field" name="my_third_field" placeholder="Enter Third Field">
</div>
<button type="button" id="my-button-id" class="btn btn-success float_left">Add Test Case</button>
My Select2 dropdown select box is:
$("#my_select2_id").select2({
placeholder: "Select One ID",
allowClear: true,
initSelection: function(element, callback) { }
});
My Ajax call is:
$('#my-button-id').click(function(){
---------
---------
---------
var data = $('#my_form').serialize();
$.ajax({
type:"POST",
url:"ajax/my_ajax_file.php",
data:data,
success:function(response)
{
if(response == 'error')
{
$('.failure-msg').text('Some problem occurred, please try again.');
$('.form_error').show();
}
else
{
$('.form_error').hide();
$('#my_form')[0].reset();
$("#my_select2_id").select2('data', null);
//$("#my_select2_id").val('').trigger('change');
$('.myData').html(response);
$('.success-msg').text('Data has been added.');
$('.my_form_success').show();
window.setTimeout(function(){location.reload()},1000)
}
}
});
})
My requirement here is I just want to reset the select2 box, for this I am following 2 ways that is I have to either reset select2 box which is not getting reset or reload the page so that select2 also will be reset. It is neither refreshed by window.setTimeout(function(){location.reload()},1000) nor the select2 box is getting reset by $("#my_select2_id").select2('data', null); Can anyone please help me in this. Thanks in advance.

As mentioned in the comments to your question there is no obvious syntactical error in your code but you lack to check for errors on your AJAX call by only checking the success() portion of the code. I would recommend to either add the complete() or error() functions to make sure you are also able to react to errors that may occur while submitting the data.
$.ajax({
type:"POST",
url:"ajax/my_ajax_file.php",
data:data,
success:function(response) {
},
error: function (jqXHR, status, message)
{
alert ("Submitting data failed with message: " + message);
}
});
On a page refresh all form elements will be reset to their original values, you therefor don't have to clear the SELECT field prior to reloading the data.

You can try with:
setTimeout(function(){ location.reload(); }, 1000);

Related

Cant detect input box when nothing is entered

I have the following form and input box. However, when there is nothing in the input box, the javascript doesn't execute. I need to detect if someone clicked "submit" without filling in the form. I have tried many things I've found on SO and none have worked. When there is an input value, everything works perfectly to execute the js. However, when there is nothing, the console.log(bidz) doesn't produce anything and it appears as if the script quits. From what I've read, I understand that the input box doesn't exist without a value in it. But then I tried to say if it doesn't exist, then something, but that also didn't work.
Perhaps this has to do with the fact that I give it a placeholder value of "enter something?"
<form action="" method="post">
<div id="<?php echo $this->item['id']; ?>">
<div class="ab">
<label for="ab_input"><?php echo $this->translate('To get the auction started, you must enter a starting bid.'); ?></label>
<span class="auction_bid_container">
<input id="ab_input" type="text" maxlength="12"
class="middle nmr event-clear-focus"
name="bidz" value="Enter something" />
<input id="updateBidButton" type="submit"
class="button grey-button num-items-button"
name="bidz"
value="<?php echo $this->translate('submit'); ?>"/>
</span>
</div>
</div>
</form>
<div class="clear mb20"></div>
and here is my js function. I have tried all kinds of things but it appears "this.value" results in an error if there is no value:
$('input[name="bid_amount"]').live('change', function () {
var bidz = this.value;
console.log(bidz);
$.ajax({
type: 'post',
url: "?module=is&controller=index&action=syy",
dataType: "text",
data: 'bid=' + bid_amount + '&id=' + id,
beforeSend: function () {
$('.ab').animate({
'backgroundColor': '#ffdead'
}, 400);
},
success: function (result) {
if (result == 'ok') {
console.log(bid_amount);
$('.ab').animate({
'backgroundColor': '#A3D1A3'
}, 300);
} else {
$('.ab').animate({
'backgroundColor': '#FFBFBF'
}, 300);
}
}
});
});
You are submitting the form either way, that's why! So, what you have to do is to stop the form from being submitted. How?
You can add onsubmit=" return false; " to your form
<form action="" method="post" onsubmit=" return false; ">
</form>
submit.addEventListener("submit", form, function(){
e.preventDefault(); /* This will prevent the form from being sent until you explicitly send it. */
});
If you are sending the form through ajax there is no need to submit the actual form (meaning form.submit() )

php $POST[] empty after Ajax call from jquery

Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly

Posting data from webpage using JavaScript PHP jQuery to Google Sheet

Before you say this is a duplicate, hear me out. I followed this answer (jQuery Ajax POST example with PHP), but I am trying to send the data to a Google Sheet. I have already got the code working on the Google Sheet, as I can add data to it by running my code directly from the sheet.
However, getting it to work with my webpage is apparently the problem. Even though I have followed the answer to the question I posted above, I think there is something more at play here that has to do with my lack of experience working in this area.
The code below is to a floating footer and is contained within the code of the whole webpage (where jquery-1.11.0.min.js and jquery-migrate-1.2.1.min.js have already been called). When I click on the submit button, the page looks like it processes the request, but nothing ever appears on the Google Sheet, Sheet1 (https://docs.google.com/spreadsheets/d/19l2kSHdBKEWtIFX44FxLBdvCoKjy7VqPF4IW6C1xAZc/edit?usp=sharing).
#document
<html>
<body>
<div class="floater-footer" id="the-floater-footer">
<span id="myTestSpan"></span>
<div class="row">
<div class="col-md-1 col-sm-2 col-xs-3"><p>Newsletter</p></div>
<div class="col-md-8 col-sm-7 col-xs-9">
<form id="floater_footer" class="validate subscribe_form">
<div id="subscrive_group wow fadeInUp">
<!-- <input type="email" value="" name="EMAIL" class="form-control subscribe_mail" id="mce-EMAIL" placeholder="email address" required /> -->
<input type="text" class="form-control subscribe_mail" id="bar" name="bar" value="" placeholder="email address" required />
<!-- <input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="subscr_btn subscribe_btn"> -->
<input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />
</div>
</form>
</div>
<div class="col-md-3 col-sm-3 hidden-xs">
<div class="pull-right">
<!-- social media icons here -->
</div>
</div>
</div>
</div>
<script type="text/javascipt">
jQuery( document ).ready(function( $ ) {
// variable to hold request
var request;
// bind to the submit event of our form
$("#floater_footer").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
//$('#result').text('Sending data...');
// fire off the request to /form.php
request = $.ajax({
url: "https://script.google.com/macros/s/AKfycbyQIDmSInumcrNmU4zxIa4pV8tIlN3A9zx5L5o1hH4qNdP9nDw/exec",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
//$('#result').html('Success - see Google Sheet');
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
</script>
</body>
</html>
Any suggestions on what could be going wrong? I am quite inexperienced when it comes to web development, as compared to most on this site. So I'm sure it's something simple I am missing!
I don't completely understand why it worked, but taking out the script and putting it in the head of the page HTML seemed to work! Perhaps this was because having the script come after the elements was an issue, or perhaps having a $(document).ready() inside of an HTML that was inside the page's main HTML caused issue, or perhaps it was something else! No matter which one it is, the following solved the problem.
Up at the top of the code in the head of the page's HTML (but after the jQuery.js files were declared), I placed the script you saw already, but with some cosmetic changes. I'll put it here in the event I did indeed change something important that I didn't realize. I will also show the two jQuery files I included before the script:
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
//this is for writing the newsletter signup out to a spreadsheet for the floating footer
$( document ).ready(function( $ ) {
// variable to hold request
var request;
// bind to the submit event of our form
$("#floater_footer").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
//$('#result').text('Sending data...');
if( $('#email1').val() == "Email Received!" ) {
//do nothing
//basically, they pressed the button again on accident
} else {
// fire off the request to the Google Sheet script
request = $.ajax({
url: "https://script.google.com/macros/s/AKfycbyQIDmSInumcrNmU4zxIa4pV8tIlN3A9zx5L5o1hH4qNdP9nDw/exec",
type: "post",
data: serializedData
});
}
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
//$('#result').html('Success - see Google Sheet');
$('#email1').val('Email Received!');
console.log("Newsletter signup complete!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
</script>
Further down into the body of the HTML was this code where my footer was to be placed:
#document
<html>
<body>
<div class="floater-footer" id="the-floater-footer">
<span id="myTestSpan"></span>
<div class="row">
<div class="col-md-1 col-sm-2 col-xs-3"><p>Newsletter</p></div>
<div class="col-md-8 col-sm-7 col-xs-9">
<form id="floater_footer" class="validate subscribe_form">
<div id="subscrive_group wow fadeInUp">
<input type="text" class="form-control subscribe_mail" id="email1" name="emailSignup" value="" placeholder="email address" required />
<input type="submit" value="Subscribe" class="subscr_btn subscribe_btn" />
</div>
</form>
</div>
<div class="col-md-3 col-sm-3 hidden-xs">
<div class="pull-right">
<!-- bunch of social media links/icons -->
</div>
</div>
</div>
</div>
</body>
</html>
Hopefully that will help somebody that has this problem in the future. You may see a reason this worked that I do not.
Big thanks to Jay Blanchard for making me question if my script was even triggering at all, which inspired me to pull the script out and put it somewhere else! The script almost certainly wasn't firing at all, and was the root of the problem. But WHY that was, I don't know. But I hope this helps someone else!

javascript ajax post form function and validation

This is my code so far:
$(function () {
$('.contact-form').submit(function (event) {
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label").removeClass("error");
self.removeClass("error");
});
}
});
});
});
What it does:
It prevents the form from redirecting to the php script, it turns all fields red (the error class) if they are not filled, and gives the labels an error class.
What I need help with:
Fix so if one field is getting filled remove the error class as it doesn't right now.
Fix so that the label error class gets removed on the specific field when filled (right now it removes the class on all labels over all fields)
And run this code when every field / textarea is validated to be filled:
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function () {
// Optionally alert the user of success here...
console.log("jag lyckades!");
}).fail(function () {
// Optionally alert the user of an error here...
console.log("jag lyckades INTE");
});
event.preventDefault(); // Prevent the form from submitting via the browser.
My html:
<form class="contact-form" action="<?= path(" postform.php "); ?>" method="post" validate>
<div class="row">
<div class="col-sm-6">
<label for="firstname">Förnamn*</label>
<input type="text" class="required" name="firstname" />
</div>
<div class="col-sm-6">
<label for="lastname">Efternamn</label>
<input type="text" name="lastname" />
</div>
</div>
<div class="row">
<div class="col-sm-6">
<label for="email">E-post*</label>
<input type="text" name="email" />
</div>
<div class="col-sm-6">
<label for="number">Telefon*</label>
<input type="text" name="number" />
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label for="message">Meddelande*</label>
<textarea name="message"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<p>Fält markerade med * är obligatoriska</p>
<input class="btn-form" type="submit" value="Skicka">
</div>
</div>
</form>
Thanks... I really appreciate your time guys
EDIT:
This is my code at the moment:
http://jsfiddle.net/dmyhd90d/
My problems now:
Having the ajax call run when there's no more form errors ( it runs even if none is filled now )
The label error class is getting the error class removed now instantly when you fill the fields, but the fields stay error classed till I hit the send button, then it revalidates.
Lets post it all in one place because comments are not the place for this anymore
First:
with form submissions, you can often let the error field just clear when you re-validate so by adding
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
you can clear the errors out and re-validate the whole form from scratch.
second, you're trying to bind an event so that when you edit the input it clear the error from that input and it's label but right now you're clearing all labels errors so you can change it like this
if (input.val() == "") {
event.preventDefault();
$("label, p").addClass("error");
input.addClass("error").one("keydown", function () {
// $("label").removeClass("error");
$("label[for='" + $(this).attr('name') + "']").removeClass("error"); // becomes this
self.removeClass("error");
});
}
To associate the input you're looking at, with it's label. BTW just so you know it's good to put input id="something" and label for="something" as that'll link the label to the input in html, when you click the label. Remember to keep your names for submitting though.
Additionally I think that
$("label, p").addClass("error");
will add an error to all your labels at once. You might want to change it also to add errors only to the fields that have errors
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
Edit to answer the comment
$('.contact-form').submit(function (event) {
$('.error').removeClass("error"); // This
$(this).find("input , textarea").each(function () {
var input = $(this);
if (input.val() == "") {
event.preventDefault();
$("label[for='" + $(this).attr('name') + "'], p").addClass("error");
input.addClass("error").one("keydown", function () {
$("label[for='" + $(this).attr('name') + "']").removeClass("error");
self.removeClass("error");
});
}
});
if ($(".errors").length <= 0) { // If there are no more error classes
// Do $.ajax() here
// http://api.jquery.com/jquery.ajax/ <- you need to read this and other similar SO posts about ajax
}
});

How to add before send function to current return ajax function?

i have a main form on my main page, the form get an email address from the user and check if the email exist.
My target is to show the results on the same page with bootstrap collapse.
I am using this code in the javascript side:
$(".emailCheckForm").bind("submit", function () {
return $.ajax({
type: "POST",
width: "auto",
height: "auto",
padding: 10,
cache: !1,
url: "_/php/checkemail.php",
data: $(this).serializeArray(),
success: function (t) {
$(".res").append(t).collapse();
},beforeSend: function(){
$( "#message" ).empty();
}
}), !1
}),
my html code:
<form action="" method="post" class="col-md-8 centered emailCheckForm">
<div class="input-group">
<input type="email" name="email" class="form-control checkFrame" placeholder="you#youremail.com">
<div class="input-group-btn">
<input type="submit" value="answer me!" class="btn btn-default checkFrame" tabindex="-1" />
</div>
</div><!-- /.input-group -->
</form>
<div class="res"></div>
Now this working but the problem is that if i want to check another email i get the same results until i will refresh the page.
So i want to implement a before send function that will remove\empty the div results.
I cant make this happen because that every time that i insert the beforsesend function the post not working, any suggestions to make proccess like that in the right way?
How about this one. On every successful callback it will clean up results from previous request and re-populate latest:
...
success: function (t) {
$(".res").empty().append(t).collapse();
}
...

Categories