ajaxSubmit Form Validation with a pop-up "processing" div - javascript

I'm using ajaxSubmit on my web form. I also need to pop-up a div that shows "Processing the request" with a dimmed background upon user's click on the submit.
The code I'm using right now is like this:
<script type="text/javascript">
$(document).ready(function() {
$("#CustomerService").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "processor.aspx",
success : function() {window.location.replace("Thankyou.aspx")},
failure : function() {}
})
});
</script>
<script type="text/javascript">
function DimScreen()
{
document.getElementById("DimBlackScreen").style.visibility = "visible";
}
</script>
And my HTML part for the submit button:
<input type="submit" value="Submit" id="Send" name="Send" style="cursor:pointer;" onclick="DimScreen();" />
Well the problem here is: whether the form passes the validation or not, the pop-up div will always show up, which is not the case I want.
Is there any way to make it detect if the form validation has passed and then display the div?
Many thanks for your help.

If you are using jquery version 1.4 or above try this:
$(document).ajaxStart(function() {
$("#DimBlackScreen").show();
}).ajaxStop(function() {
$("#DimBlackScreen").hide();
});
or if you are using less version of jquery 1.4 try this
$().ajaxStart(function() {
$("#DimBlackScreen").show();
}).ajaxStop(function() {
$("#DimBlackScreen").hide();
});
Remember put all these stuff in document.ready

$(document).ready(function() {
$("input#Send").click(function(e){
e.preventDefault(); //prevent default submit action,, use ajax instead
$('#DimBlackScreen').show();
$("#CustomerService").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "processor.aspx",
success : function() {
$('#DimBlackScreen').hide();
window.location.replace("Thankyou.aspx"); //or $('body').html('Thank you!');
},
failure : function() {}
});// end validationEngine
}); //end click
});//end document.ready
<input type="submit" value="Submit" id="Send" name="Send" style="cursor:pointer;" />

Ok, inspired by the other two answers from alsahin and Kundan, I figured it out myself:
The only thing needs to be changed is how ajax handles the failure of validation. So I changed
failure : function() {}
to
failure : function() {document.getElementById("DimBlackScreen").style.visibility = "hidden";}
So that the pop-up "processing" div actually shows every time user clicks on the Submit button, but resets to hidden if the form doesn't pass validation.
I'm happy with my current code, but if you have any better ideas, please let me know.

Related

Make the click-button code not disappear instantly? [duplicate]

I have a button (<input type="submit">). When it is clicked the page reloads. Since I have some jQuery hide() functions that are called on page load, this causes these elements to be hidden again. How do I make the button do nothing, so I can still add some action that occurs when the button is clicked but not reload the page.
There is no need to use JS or jQuery.
to stop the page to reload, just specify the button type as 'button'.
If you don't specify the button type, the browser will automatically set it to 'reset' or 'submit' which causes the page to reload.
<button type='button'>submit</button>
Use either the <button> element or use an <input type="button"/>.
In HTML:
<form onsubmit="return false">
</form>
in order to avoid refresh at all "buttons", even with onclick assigned.
You could add a click handler on the button with jQuery and do return false.
$("input[type='submit']").click(function() { return false; });
or
$("form").submit(function() { return false; });
In HTML:
<input type="submit" onclick="return false">
With jQuery, some similar variant, already mentioned.
You can use a form that includes a submit button. Then use jQuery to prevent the default behavior of a form:
$(document).ready(function($) {
$(document).on('submit', '#submit-form', function(event) {
event.preventDefault();
alert('page did not reload');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id='submit-form'>
<button type='submit'>submit</button>
</form>
You could also use JavaScript for that:
let input = document.querySelector("input");
input.addEventListener("submit", (event) => {
event.preventDefault();
})
As stated in one of the comments (burried) above, this can be fixed by not placing the button tag inside the form tag. When the button is outside the form, the page does not refresh itself.
I can't comment yet, so I'm posting this as an answer.
Best way to avoid reload is how #user2868288 said: using the onsubmit on the form tag.
From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page.
For example:
<form id="frmData" onsubmit="return false">
<input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
<input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
<input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#btnSubmit').click(function() {
var tel = $("#txtTel").val();
var email = $("#txtEmail").val();
$.post("scripts/contact.php", {
tel1: tel,
email1: email
})
.done(function(data) {
$('#lblEstatus').append(data); // Appends status
if (data == "Received") {
$("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
}
})
.fail(function(xhr, textStatus, errorThrown) {
$('#lblEstatus').append("Error. Try later.");
});
});
});
</script>
Use event.preventDefault() in the first line of your event function.
Buttons must be of the type button and contain type="submit" in the button html.

Jquery form submit event don't work if i trigger manually

So, i have this simple script where i try to stop form submision for make some ajax call and after i want to submit form manually, but this doesn't work, I try over 20 solutions. I try event to stop form submit with prevent default and fire latter in callback as i see in some example but for me give recursion
<script type="text/javascript">
$(function() {
$('#my-form-submit').click(function(e) {
e.preventDefault();
$('#my-form').submit(function() {
alert('test');
});
});
});
</script>
<form method="post" id="my-form" action='#'>
<input type="submit" name="my-submit" value="Submit this form!" id="my-form-submit">
</form>
You attached a event listener for when the form will submited.
To submit the form, just pass the method submit() without any parameter, or like so:
$('#my-form').submit(function() {
alert('test');
}).submit();
If u want to capture event before send a form, you only need to use .submit()
$(function() {
$('#my-form').submit(function() {
alert('Check it is showed before submit test');
});
});

How to show loading-div after submitting a form with jQuery?

I am new at Javascript and jQuery. I want to show a "loading-gif" after the user submitted a form but can't figure out why my code is not working. That's the situation:
the form has the id="form"
the loading-div has the id="loading" and the style="display:none" (and some others of course)
the submit-button has the class="formtrigger" (and no type="submit")
That's my javascript (initialized after jquery at the bottom of the html-page):
$('.formtrigger').click(function() {
$('#loading').show();
$('#form').submit();
});
When I click the button, the form is submitted, but the loading-div doesn't appear. I tried the line "$('#loading').show();" without binding it on the click-event and it worked. I also tried this code:
$('.formtrigger').click(function() {
alert('blablabla');
$('#form').submit();
});
and both statements worked! First the alert is shown and then the form is submitted. Why does the other code not work?
Thanks in advance.
EDIT: I've also tried the following variations without success
$('.formtrigger').click(function() {
$('#form').submit();
});
$('#form').submit(function() {
$('#loading').show();
});
and
$('.formtrigger').click(function() {
$('#loading').show();
window.setTimeout($('#form').submit(), 5000);
});
and
//HTML
<button type="submit">...</button>
//JS
$('#form').submit(function() {
$('#loading').show();
});
In your .submit(), show your loading spinner:
$("#loading").show();
And after your .submit() is done, hide it:
$("#loading").hide();
And make your spinner display: none; by default since the jQuery above simply changes the css properties for your specified element.
I provided you with a simple demo where I have an AJAX function echoing your message from the text input. It will show a loading spinner until it reaches success.
Fiddle Demo
In the Head put...
<script type="text/javascript">
<!--
function showHide(){
//create an object reference to the div containing images
var oimageDiv=document.getElementById('searchingimageDiv')
//set display to inline if currently none, otherwise to none
oimageDiv.style.display=(oimageDiv.style.display=='none')?'inline':'none'
}
//-->
Put this where you want the spinner to appear... (of course you'll need to find an animated gif for a spinner)
<div id="searchingimageDiv" style="display:none"> <img id="searchingimage1" src="http://www.pathtoyourimage/images/searching.gif" alt="" /> </div>
Your submit button text should be...
<input type='submit' value='Next' name='submit' onclick='showHide()'>

Strange issue with jQuery.get()

I'm having a strange behaviour with this code:
<script type="text/javascript">
function get()
{
alert("gggg");
jQuery.get (
"http://localhost:8080/c/portal/json_service",
{
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : document.getElementById("nombre")
}
);
}
</script>
<div>
<form>
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="button" value="Submit" onClick="javascript:get()"/>
</form>
</div>
Liferay portal gets blocked when the button "Submit" is pressed. The pop-up with the message "gggg" is showed, but after click ok on it, the page becomes blocked.
If I remove the line 'param : document.getElementById("nombre")', it doesn't block.
Can anyone explain me where is the error, or the reason of this behaviour?
Thanks in advance,
Rafa
The problem is that you're trying to pass an entire DOM element as the value for param, which jQuery isn't going to like. What type of element has ID nombre, and what property from that element do you want? If it's some kind of input, you likely want the value property, so you'd do:
param : document.getElementById("nombre").value
Updated Answer:
Thinking this through a little more, you should probably do this in a different way altogether. You're sending the data when the user clicks on the submit button, but remember if a user hits enter while typing in the input text box the form will submit but your code will not catch that.
A more robust solution would be to do it this way instead:
<div>
<form id="nombre_search">
<input type="text" id="nombre" value="<%=searching%>"/>
<input type="submit" value="Submit"/>
</form>
</div>​
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("#nombre_search").submit(function(){
$.get("http://localhost:8080/c/portal/json_service", {
serviceClassName: "com.liferay.test.service.TrabajadorServiceUtil",
serviceMethodName: "findByName",
servletContextName: "TrabajadorPlugin-portlet",
serviceParameters: "[param]",
param : $("#nombre").val()
});
return false;
});
});
</script>
Changes to your code:
Added an id to the form.
Made the submit button a submit button instead of just a button.
Placed code inside $(document).ready block.
Code runs when form is submitted not when button is clicked.
Hope this helps,
Sandro

Try to combine javascript confirm box with php post method?

Here is the Javascript code, just for test:
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Are you sure?");
if (r==true)
{
}
else
{
}
}
</script>
And this is the php code:
<form action="Test.php" method="post">
<input type="text" name="test"/>
<input type="submit" value="submit" onclick="show_confirm()"/>
</form>
So if the submit button is clicked, a confirm box will pop out. And if "OK" button is clicked, the page will be redirected to Test.php and post method will be executed, like a normal php page submit operation. Or else, if the "cancel" button is clicked, i want it stay the same page and post method won't be executed. Is this function can be implemented and how to modify the code? I know PHP is for server and JS is for client. I'm not sure if I can mix them like this. Or I should use Ajax? Thanks for help!
The best way to do this is as follows:
<script>
function show_confirm(){
return confirm("Are you sure?");
}
</script>
<input type="submit" onclick="return show_confirm();">
The reason I use show_confirm instead of the built-in function directly is because if you want to change the functionality of the confirm popup, it is much harder if you are using the builtin function everywhere in your code.
Abstracting out this kind of functionality and writing clear, simple code like this will make you a better programmer :)
warning: as indicated in my comments below, this will only work if the user explicitly clicks the submit button. If the user submits the form by some other method, the confirm box will not show. See http://www.w3schools.com/jsref/event_form_onsubmit.asp if you want to show a confirm regardless of how the form was submitted.
You can do this directly from the button. return false will cancel the submission ... so....
<input type="submit" onclick="javascript:return confirm('Are you sure?');">
if the user clicks 'ok' the dialog will return true, otherwise false.
to be complete here it is in function form.
function show_confirm()
{
var r = confirm("Are you sure?");
if(r == true)
{
// do something
return true;
} else {
// do something
return false;
}
}
edit: reading this almost 4 years later I'm compelled to change it.
function show_confirm()
{
var r = confirm("Are you sure?");
if(r)
{
// do something for true
} else {
// do something for false
}
return r;
}
call it with <input type="submit" onclick="javascript:return show_confirm();">
I believe this will also handle the case where nothing is selected but the dialog is closed.
note: inline event listeners should be avoided. attach an event listener with Javascript.
<script type="text/javascript">
function show_confirm()
{
var r=confirm("Are you sure?");
if (r==true)
{
document.location.href= 'page.php';
}
else
{
return false;
}
}
</script>
Simplifying rlemon's answer even further (no need for the javascript:return, also fixed the inner double quotes):
<input type="submit" onclick="return confirm('Are you sure?')" />

Categories

Resources