I'm using jQuery and am preventing the submission of a form, then based on an ajax response will submit the form. The problem I'm finding is that I often have to submit the form twice. The first time, it shows the loader, but it doesn't get seem to call any actions within the ajax's success function. If I click it a second time, it submits (if it's been validated). It also seems to work the first time, after I go through this. So if I try again, it'll work the first time. So maybe it's a cache issue? Here's the javascript I have:
$('#submit_zipcode_frm').submit(function(event){
event.preventDefault();
var self = this;
$(".loader img").show();
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
} else {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
$.ajax({
url: "/ajax/save/zipcode",
type: 'GET',
async: false,
cache: false,
dataType: 'html',
data: {zipcode: $('.zipcode_field').val()},
success: function(data) {
if(data == 'false'){
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}else{
self.submit();
getList();
}
}
});
});
and here's the markup:
<form id="submit_zipcode_frm" class="submit_zipcode" method="post" action="/go" target="_blank">
<div class="zipcode_container">
<span class="loader">
<img src="/assets/img/loader.gif" style="display: none;"/>
</span>
<input type="text" class="zip_input zipcode_field ghost" id="zipcode" name="zipcode" value="Enter your Zip"/>
<div class="start_btn">
<button type="submit">Submit</button>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</form>
Any suggestions or ideas would be really appreciated. Thank you!
EDIT:
Just to clarify the steps here:
User clicks the submit button
JavaScript show's the loader and validates the length and and type of the value entered
If that passes, an ajax lookup is used to truly validate it's a valid USPS zip code
If it is, the form is submitted and a function getList() is called
If it's not, error is thrown
Related
I'm designing a web page which checks if an email specified is available is database. If it is available, then i must stop submitting the form.
I used ajax for live checking of email and update the response as a span message. If i click submit button, even though the email is already available in the db, the form is submitted and getting redirected to another page. Please do help me get out of this. Thanks in advance.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function checkemail() {
var email=document.getElementById( "UserEmail" ).value;
if(email) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email:email,
},
success: function (response) {
$( '#email_status' ).html(response);
}
});
}
}
function validateForm(){
var a=document.getElementById("email_status").innerHTML;
var b="Email Already Exist";
if(a==b)
alert('Yes');
else
alert('No');
}
</script>
</head>
<body>
<form method="POST" action="insertdata.php" onsubmit="return validateForm();">
<input type="text" name="useremail" id="UserEmail" onkeyup="checkemail();">
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit">
</form>
Expected result when i give an email which is already in db:
Yes.
Actual result:
No
You code has design problems.
1.The biggest one is that you are make an ajax call request while user is typing, that will probably cause you big overhead.
2. the same design is causing the validation not working properly.
Allow me to make a proposal.
<form method="POST" action="insertdata.php" id="form" onsubmit="return false;">
<input type="text" name="useremail" id="UserEmail" >
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit" onClick="checkemail();">
</form>
in this approach i have removed the keyup event form the input and have added the function checkemail() on button click.
var emails = [];
function checkemail() {
var email = document.getElementById('UserEmail').value;
if (email) {
if (!emails.includes(email)) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email: email,
},
success: function (response) {
$('#email_status').html(response);
if (response == 'Email Already Exist') {
console.log("email "+email+" is a spam")
emails.push(email);
} else {
document.getElementById('form').setAttribute('onsubmit', 'return true;');
document.getElementById('form').submit;
}
}
});
}else{
console.log("email "+email+" is a spam")
}
}
}
In this design approach code does
1.on button click executes checkemail function
2.checkemail function checks the emails array if contains the email from the text input, if the email is in the array then a log is written in console, if not then an ajax requset is done.
3.if the email is in the db then an other log is made, else the form is submitted.
This approach provides the ability of keeping every email that the user will possible write. I also suggest your ajax script instead of returning a text message to return a code maybe 0 or 1, that way comparison is safer.
Last but not least, although i don't know where you intend to use that code please keep in mind that a bot will probably bypass this java script code and hit directly your server side script. So you should think of a server side check also.
If you need more help or clarifications don't hesitate to ask.
In my form i am checking if there is same value in database or not when form submitted. The code below works fine and is giving the rigth result of AJAX post but the problem is when giving alert according to the wrong result, javascript alert and focus works but form still submits after these.
Button for submit:
<input type="submit" name="kaydet" class="btn btn-success form-control"
onClick="return kaynak_kontrol()" value="Kaydet">
AJAX:
<script type="text/javascript">
function kaynak_kontrol(){
Form=document.forms['depo_kayit'];
var depo_sube_no = document.getElementById('depo_sube_no').value;
var depo_firma_no = document.getElementById('depo_firma_no').value;
var depo_kodu = document.getElementById('depo_kodu').value;
var dataString ="depo_sube_no="+depo_sube_no+"&depo_firma_no="+depo_firma_no+"&depo_kodu="+depo_kodu;
$.ajax({
type: "POST",
url: "depo_kodu_kontrol.php",
data: dataString,
success: function(result){
if(result != 0){
alert("Aynı şubede aynı isimde iki depo olamaz!");
document.getElementById('depo_kodu').focus();
return false;
} else {
return true;
Form.submit();
}
}
});
}
</script>
Can you help me why i return false is not working and form still submits?
you need to prevent the form submission manually using jQuery event.preventDefault()
here is a small fix
function kaynak_kontrol(event){ // notice the new parameter !
event.preventDefault();
//the rest of your code
I've form with single input field name and with jquery i'm checking the name availability before submit and it gives either error message if didn't passed the check or gives message correct if passed the check out.
Now my question i wonder if this code can be adjusted so that it disable submit in case it didn't passed the availability check
or whatever so that it prevent clicking on submit button if didn't passed availability check.
I'm using the following
Form Code
<SCRIPT type="text/javascript">
$(document).ready(function(){
$("#name").change(function() {
var usr = $("#name").val();
if(usr.length >= 4){
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "name="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK'){
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' correct');
}else{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}else{
$("#status").html('<font color="red">The name should have at least 4 characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
});
});
</SCRIPT>
<div id='myform'>
Name <input type="text" name="name" id="name"><div id="status"></div>
<br />
<input id="submit" type="submit" name="Submit" value="Submit">
</div>
~ thanks for help
You can simply disable the submit input element:
$("#submit").prop('disabled', true);
Example
I have a list of results that are shown on a particular page and these are updated at regular intervals using a simple AJAX request. An input form allows me to filter these results, but as the data is updated every few seconds, the input form doesn't work properly as it refreshes all the data. Is there any way for the AJAX to not update when there is a value in the form input field?
Below is the HTML code:
<div id="my-query-results" class="visible">
<div>
<form class="searchboxInput" action="#">
<input id="kwd-my-query-results" type="text" value="">
</form>
</div>
<div id="my_recent_queries">
<span class="loading_placeholder">Loading ...</span><br />
<img src="../img/ajax-loader.gif" />
</div>
</div> <!-- my query results -->
Below is the AJAX request that I was using:
if( $("#kwd-my-query-results").val() != "") {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 600000);
}
updateMyQueries();
} else {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 4000);
}
updateMyQueries();
}
The above if else statement just didn't seem to work. It would evaluate to the else statement once a value was present in the input box. I think I also tried length(), but that didn't seem to work either. Any other way of approaching this?
Update
I tried the following given the suggestion below, and it works to some degree. It loads the results initially, allows me to search them without reloading the data, but then it doesn't reload the results at regular intervals, even when there is no text in the input field...
$(function(){
setTimeout(updateMyQueries(), 4000);
});
function updateMyQueries(){
if ($("#kwd-my-query-results").val() == "") {
// do ajax call
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
}
}
I would start by moving the updateMyQueries function out of the if statement then maybe something like this.
$(function(){
SetInterval(updateMyQueries(), 4000):
})
function updateMyQueries(){
if($("#kwd-my-query-results").Val() == ""){
// do ajax call
}
}
EDIT - this will work
setInterval(function (){
if($("#search").val() == ""){
// Ajax call here
}
}, 4000);
Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});