How to display notification before form submit with jquery? - javascript

Is it possible to hold form submission to display notification for a couple of seconds?
Before a page reloads after the callback form is submitted I would like to display something along those lines: "Thank you for your callback request. We will be in touch shortly."

You can use preventDefault() to stop the form from submitting, show the information you want and submit() the form in a setTimout() after the desired delay.

if you're submitting with AJAX there is no need to refresh.
Take this as an example:
<form>
<input type="text" name="fname"/>
<input type="text" name="lname"/>
<input type="text" name="email"/>
<input type="text" name="address"/>
<input type="password" name="password"/>
<!--
Here you have two options. Use <a></a> or an input with type="submit"
since you're using AJAX, I reccomend using Submit
-->
Submit
</form>
Thank you for your callback request. We will be in touch shortly.
On javascript then:
<script>
$(document).ready(function(){
$("#submit_form").bind("click",function(){
//do a $.post();
$.post("submit/this.php",something : "content_of_something",
function(response){
if(response==1)//or whatever you want
$('#some_id').fadeIn(function() {
setTimeout(function(){
window.location.reload();
},3000);
});
else
alert("Error ocurred");
}
);
});
});
</script>
On PHP, check if the variable got to the server through $_POST(for debug purpose do var_export($_POST) on the server and on the client put a alert(response) right after function(response)). If everything went how it was supposed, echo 1(so response will match 1== response == 1), else, you can echo something else you want.

Related

AJax variable not getting send to php variable

Im very new to Ajax and Jquery and learning through SO and online tutorials so please keep in mind im a rookie should you read and be kind enough to answer my post.
I have managed to create the following which is a form that displays a message on submit. If form was successfully submitted a message is displayed without page refreshing as you can see in image below:
FORM
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
<div>
JQUERY
$(function(){
$("#contact-form").submit(function(e){
e.preventDefault();
$form = $(this);
$.post(document.location.url, $(this).serialize(), function(data){
$feedback = $("<div>").html(data).find(".form-feedback").hide();
$form.prepend($feedback)[0].reset();
$feedback.fadeIn(1500)
})
});
})
What I want to do
Retrieve the value from text field message and assign it to php variable
My problem
When I try to retrieve the value of message with the following code, nothing happens:
PHP code below form
<?php
if(isset($_POST['contact'])){
$message = $_POST['msg'];
echo $message;
}
?>
Im very new to Ajax so I guess I am doing something wrong here, unfortunately I dont know where I am going wrong so I am hoping someone can put me on the right path here.
Thanks in advance
Hanoncs suggestion will work, but keeping things only browser side (by displaying the message only from form to div), will always give the user the impression that message is send (processed) server-side, while it is not always the case, one would make php return it before displaying it with javascript. So here is another approach I suggest:
First, Make a Separation of concerns: Sending a POST HTTP Request to the same current page contardicts somehow the purpose of AJAX. The HTTP Response will contain all the page ( the HTML rendred by PHP, the embeded HTML used for templating, and maybe the script if it is not joined in a script tag). Instead, I suggest you create a small separate php file that is responsible for rendereing only the needed markup. And so, instead of using $.post(document.location.url.., one would use $.post('pathToSmallPHPFile'..
Second, let jQuery AJAX functions accept callbacks or use promises. I suggest you carefully read the following link.
The issue is that you are using ajax, which does not cause a page refresh, and then trying to echo out the posted variable, since there is no page refresh, php will not process the page again to echo the posted variable.
My solution is to use javascript to display the text entered and then database it using php.
Here is an example,
$(document).ready(function () {
$(".button").click(function () {
$('p').text($('#msg').val());
});
});
http://jsfiddle.net/r4nanmof/ you dont need ajax if all you want to do is display it on the page. If you plan on saving in the database then ajax is required.
Jquery Code for posting the message value to the php file is given below:
$('#contact_btn').click(function(event){
event.preventDefault();
var url = "url/of/the/php/page/where/to/process/data";
var data = $("#msg_box").val();
var wrapper = $('#wrapper');
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
wrapper.html("The reponse from the page is " + response);
},
error: function(xhr,status,msg){
//Handle error here
}
});
});
<code>
<div id="wrapper">
<form name="message-form" action="" id="contact-form" method"post">
Message<br /> <input type="text" name="msg" id="msg_box" value="" /><br />
<input type="submit" id="contact_btn" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none">
Thank You We will Get Back to you
</div>
<div class="form-feedback" style="display:none">
Ooops....Something Went Wrong
</div>
</div>
</code>
Message
Thank You We will Get Back to you
Ooops....Something Went Wrong
Its not necessary in your case but change method"post"> to method="post">
And change your Form
<form name="message-form" action="" id="contact-form" method="""post">
Message<br /> <input type="text" name="msg" value="" /><br />
<input type="submit" value="Contact Us" name="contact" class="buttono" />
</form>
<div class="form-feedback" style="display:none"> </div>
And use the following jQuery code to post your data
$(function () {
$("#contact-form").submit(function (e) {
e.preventDefault();
$form = $(this);
$.post(
document.location.url,
$(this).serialize(),
function (data) {
$(".form-feedback").html("Your msge " + data + " is recieved and we will get back soon");
$(".form-feedback").show();
})
});
});

ajax post refreshes the page when it shouldn't

I have a uses jquery post answers to a grader.php script, which works perfectly. Depending on the results, it brings a form so they can send message with contact info. When I try to post to the second script to process the mailer, the whole page refreshes without posting the data or returning the appropriate message. It turns out the call is not being made at all. If you want to see the staging site you're welcome to look. It's kind of a cheesy way for me to get my feet wet with jquery. However, I believe the suspect script is here.
I added an alert to the click event to see if it even triggers the click on the score button. No alert triggers and all I get is a page refresh.
Alternatively, is there any way log posts and console data to see exactly what's happening?
HTML:
<div id="result">
<form id="info" method="post" action="">
<input name="phone_number" placeholder="phone number" type="text" size="20" value="">
<input name="email_address" placeholder="email address" type="text" size="30" value="">
<textarea cols="50" rows="10" placeholder="Questions? Comments?" name="comments"></textarea>
<input type="submit" id="score" name="score" value="Send">
</form>';
</div>
Jquery:
$("#score").click(function(event){
alert("clicked");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var info = $("#info").serialize();
$('#result').fadeOut().html("");
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
alert(status);
});
});
I think there are 2 problems here.
Problem 1:
As the form resides inside #result, setting #result's html to "" effectively empties the form before serialization? Have you tried?
$("#score").click(function(event){
var info = $("#info").serialize();
$('#result').fadeOut().html("");
event.preventDefault ? event.preventDefault() : event.returnValue = false;
$.post('paider.php', info, function(data , status){
$('#result').fadeIn().html(data);
});
});
Problem 2:
Okay so I took a look at your staging site and think I've found the issue. You begin by having a form similar to the one in the question on this topic, but you then "replace" that form with a new form containing now a "#score" element (input type='submit').
You are applying your jquery event handler on document load but at that time the #score element does not yet exist in the DOM because you have not loaded it yet.
You believe you are running the script inside $("#score").click but in fact the page is simply using default behavior of a form with no action and a submit button.
To correct this issue you need to apply the event handler at either a higher level in the DOM tree OR you can do some easier way just to test if this is the problem
Please try this in your first #submitbuttonclick handler
$("#submitButton").click(function(event){
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var formdata = $('form').serialize();
$.post('grader.php', formdata, function(data , status){
$('ul').css('display', 'none');
$('#result').fadeIn().html(data);
//Here add the handler for #score click
$("#score").off("click").on("click", function(event){
//Insert code snippet shared above here
});
});
});
What this will do is bind the click event on the #score submit button after it has been written into the DOM. In case the script executes more than once we do not want the handler to fire multiple times, which is why we first call "off".
Hope this helps.

Change page after submitting the form using javascript

I have a form that after submitting goes to page "http://qwertyasdfgh.rozblog.com/New_Post" ( the action value )
I don't want to change the action but I want to redirect to another page after submitting.
I tried to redirect to "http://qwerty.rozblog.com/page/success" after submitting but it doesn't work .
here is the code I tried :
(html)
<form method="post" action="http://qwertyasdfgh.rozblog.com/New_Post" id="f1">
<input type="text" name="title" style="width:300px"><br />
<input type="text" name="pimg" style="width:300px" maxlength="3072"><br />
<textarea dir="rtl" id="post" name="post" style="width:300px;" aria-hidden="true"></textarea><br />
<input type="submit" name="postsubmit" value=" submit " style="background:#333;" onclick="location()">
</form>
(js)
function location() {
window.location.replace("http://qwerty.rozblog.com/page/success");
}
and here is the fiddle
You can submit the form using jquery and AJAX (or I misunderstood you):
$('#f1').submit(function(e)
{
e.preventDefault();
$.post('http://qwertyasdfgh.rozblog.com/New_Post',
formDataAsJSON, //use eg. jquery form plugin
function(data)
{
window.location = 'somewhere';
}
);
});
You have two choices.
1) Submit that form using AJAX and after recieving response from server redirect browser to your desired page. You can use for example jQuery with Ajax form plugin. The code would look like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'f1' form and provide a simple callback function
$('#f1').ajaxForm(function() {
window.location = "/page/success"
});
});
</script>
OR
2) You can leave your form and js as is, and use for example php to redirect user after doing some stuff.
New_post.php
<?php
// some stuff without printing (you cant change headers if you print something)
Header("Location: /page/success");
If possible, you can configure /New_Post to redirect to /page/success using meta refreshing in head:
<meta http-equiv="refresh" content="0; url=http://qwerty.rozblog.com/page/success">

html form button to stop multiple submissions

I have this form that submits to work.php.
What I want to do is disable the submit button when the form is submitted, then re-enable it after 5 seconds or so, so I don't get multiple posts.
How can I do this?
Also, if I press the enter key in one of the text boxes while the submit button is not clickable then it will redirect me to work.php which don't want to happen.
<form method="post" action="work.php">
<strong>Message:</strong>
<input type="text" id="message" name="message" class="message" />
<input type="submit" id="submit" onClick="this.value='Processing form';this.disabled=true;if(Submitting()){this.form.submit()}else{this.value='Submit';this.disabled=false;}" value="Submit" />
</form>
<form id="your-form">
<input type="submit" id="submit" onclick="doSubmit(this);" value="Submit" />
</form>
<script>
function doSubmit(el) {
var frm = document.getElementById('#your-form');
el.value = 'Processing...';
el.disabled = true;
frm.submit();
setTimeout(function(el) {
el.value = 'Submit';
el.disabled = false;
}, 5000);
}
</script>
This is one way to do it. There are several others.
You don't need to worry about this. If the user spams the form submit in any way (clicking submit or hitting enter), only one complete request is sent to the server - every time the submit is triggered, it resets the POST and starts again.
Do note that using JavaScript to stop this behaviour is pretty bad, considering it's incredibly easy to disable JS and spam away, which is one of the reasons why browsers only allow one POST submission at a time.
If you're using AJAX (which you haven't specified), then you should use #drrcknlsn's answer.
If your using Ajax you use the "Ajax Manager Plugin." It will prevent double requests.
That way you don't have to worry about a person hitting enter or the submit button multiple times. Only one request will go through until it is finished(but by then I would assume a success message and clearing of the form would happen)

basic html text form

I want a text form for entering a string which is later read by javascript.
<form style='margin:10px;'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
I'm noticing that when I press enter while it's selected causes the page to be reloaded. This is not what I want. How do I make it not reload the page when the form is "submitted"?
Do you need the <form> tags? They don't seem to be doing anything. If you remove them you will no longer get that submission behaviour when you hit enter.
Pressing enter is submitting the form. You can use Javascript to prevent the form from being submitted - one way of doing that is by using a submit button:
<input type="submit" onsubmit="formhandle(); return false;">
Create a formhandle() function in Javascript to do the processing you want to do. Returning false should prevent the form from being posted back to the server - however, that doesn't always work. There's more detailed information on preventing default actions in browsers here:
http://www.quirksmode.org/js/events_early.html
You have to catch the form send with JScript and send it to the server with ajax
<form style='margin:10px;' id='formID'>
Input Value: <input type="text" value="3" id="input" name="input"/>
</form>
the JQuery (you can use Prototype or pure JS if you want) code goes a litte something like this
$('#target').submit(function() {
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
});
return false;
});
The return false prevents the page from reloading. The documentation can be found here

Categories

Resources