In my mail sending script powering my contact form, the mail sending action can take some time, during this time the user doesn't know what happens. So, I wanted to add a "Mail Sending..." notification. The "Mail Sending..." notification appears when the submit button is clicked, but the script processing stalls at this point infinitely, and further mail processing is not done. I shall appreciate clues on how to resolve this. Find below the AJAX script and html form code.
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("send.php", $("#contactform").serialize(),function(response) {
$('#success').html('<h4>Mail Sending...</h4>').load(url);
});
return false;
});
});
</script>
And this is the contact form html code:
<form action="" method="post" id="contactform" >
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="button" value="send" id="submit" />
<div id="success" style="color:red;"></div>
</form>
Well,
"during this time the user doesn't know what happens. So, I wanted to add a "Mail Sending..." notification."
How about ajaxStart as this is exactly what it is designed for.
"Show a loading message whenever an Ajax request starts (and none is already active)."
You can simply attach the event handler to any element:
$( document ).ajaxStart(function() {
$( "#loading" ).show();
});
Then in the case when the ajax request is started the loading div will be shown. Once the ajax is done it will be hidden again as it would with:
$( "#loading" ).hide();
You will want to make sure that the div with that id (loading) is hidden by default.
"but the script processing stalls at this point infinitely, and further mail processing is not done."
Per jQUery Post:
If a request with jQuery.post() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.post() is also available for error handling.
If your post is failing it should return an indication as to why.
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post( "test.php", $( "#testform" ).serialize() )
.done(function( data ) {
$('#success').html('<h4>Mail Sending...</h4>');
// You should not do a .load within another ajax call so placing it here is okay as it will execute AFTER the original one completes, but it will trigger the ajaxStart method again.
})
.fail(function ( data ) {
console.log(data);
});
});
});
</script>
Unfortunately I am on mobile so I can't test the above to make sure it works, but that should get you started.
Related
I am making a chat script and an hoping to code it so that when a user submits a message, the script will run chat_new.php and then refresh #cbox. I use the code below to try and accomplish this, but unfortunately it won't reload. Just to rule it out, I tested without any jQuery and chat_new.php executes without problems, so it definitely is my ajax script. In addition, getUpdates() works just fine on it's own. I only have a problem when posting new messages through ajax.
<div id="cbox" align="left">
<script>
$(document).ready(function() {
setInterval(function() {
getUpdates()
}, 2000);
});
function getUpdates() {
$("#cbox").load("/lib/chat_post.php");
}
$("#submitmsg").click(function() {
$.ajax({
type: 'POST',
url: '/lib/chat_new.php',
data: {
submitmsg: 'submitmsg',
usermsg: 'usermsg'
},
success: function() {
getUpdates()
}
});
});
</script>
</div>
<form name="message" method='post' id="cbox_input">
<input name="usermsg" id='usermsg' type="text" size="63" maxlength="255" />
<input name="submitmsg" id='submitmsg' type="submit" />
</form>
Several issues:
Your click handler exists before the element it references and is not inside document.ready. Therefore it can't find the element and never gets bound to it
Once that is fixed you need to prevent the default form submit process. Otherwise page will reload on submit
// put this inside ready()
$("#submitmsg").click(function (event) {
event.preventDefault();
//other code
})
This might be a simple as moving }); from the third line of your script, to just before </script> so that your function and your ajax call are inside $(document).ready(... and therefore only get processed once the DOM has loaded, and all HTML elements are on the page.
I have php code that echos a form that was inserted into my html by another jquery code. This all works fine. I am trying to submit this form with ajax.
echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';
The form works fine when submitted traditionally. The problem is I cant get it to be be submitted with ajax. The .submit just wont prevent the default action.
<script>
$(function(){
$('#comment_form').submit(function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
</script>
You're probably binding the submit event handler before the form is in your page. Use event delegation instead of direct binding, for example
$(document.body).on('submit', '#comment_form', function(e) {
e.preventDefault();
alert('We are in');
// and the rest, no need for return false
});
As an addendum, try not to echo out great chunks of HTML from PHP. It's much more readable and you're less likely to run into problems with quotes and concatenation if you just switch to the PHP context when required, eg
// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP
The problem seems to be from the fact that form that was inserted into my html by another jquery code. From what I understood from this, the form was dynamically created after the page was loaded.
In that case when the submit handler registration code was executed the element was not existing in the dom structure - means the handler was never registered to the form.
Try using a delegated event handler to solve this
$(function(){
$(document).on('submit', '#comment_form', function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
Demo: Problem
Demo: Solution
I'm having great issues making this contact form that can be seen on the below visual. What I want the contact form to do is display on submit a thank you message or a message of confirmation instead of redirecting to the contact.php file where there isn't any styles you can see this in action on the provided link.
I've found some information that I can do this with Jquery Ajax that I've also tried displayed below, but I still can't seem to get it to work on submit to show a message in the pop up.
Does anyone know an easier way to do this or maybe point me in the right direction as this is something that I've been trying to fix for god knows how long.
Thank you for any help
Visual:
http://madaxedesign.co.uk/dev/index.html
PHP & HTML:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form id="submit_message" class="hide_900" method="post" action="/contact.php" onsubmit="javascript: doSubmit();">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div class="submit">
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
Jquery:
function doSubmit(){
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
You can add return false; at the end of your doSubmit function or the following code to prevent the form to redirect the user to the action page.
var doSubmit = function (event) {
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
event.preventDefault();
}
$(function () {
$('#submit_message').submit(doSubmit);
});
Modified HTLM
<form id="submit_message">
...
</form>
What is this code doing ?
First, we are defining a function to submit the form data.
Notice the event argument in the function. The first variable in this function is all the form values serialized in a ajax-complient request string. The .ajax() function is sending all the datas to your server. Note that as you did not set the type argument in the .ajax() function, the data are going to be send using the GET HTTP method.
Finally, event.preventDefault() prevents the submit event to be triggered in the browser. When the browser detect a submit event, it will try to submit the form based on the action and the method parameters in the <form> html tag. Usually, this submission performs an user redirection to the action page. This event.preventDefault() will disable this redirection. Note that the event argument is going to be set automatically by jQuery.
Last part, the $(function() { ... }); part means "execute this part when the document is fully loaded." It ensures that the element with sumbit_message id exists before calling the .submit() method. This last method is an event binder. It means that when the submit event is fired on the submit_message form, the function doSubmit will be called.
I hope you have a better understanding of this script. This is a pretty basic one, but if you understand clearly the mechanics, it will help you do become a better jQuery programmer. :)
Fiddle Demo
1.<form onsubmit='confirm()'>
function confirm()
{
alert("Thank You");
}
2.in contact.php call the page that is displayed again
You need to prevent the default event of the form. To do this, add the e.preventDefault(); function to the top of your function in order to prevent this event from firing.
Also notice that we are passing the e parameter to your function. This represents the event that has been fired.
function doSubmit(e){
e.preventDefault();
var postData = jQuery('#submit_message').serialize();
jQuery.ajax({
url: '/contact.php',
data: postData
}).done(function( html ) {
alert(html);
});
}
Try this
change your form with
<form id="submit_message" class="hide_900" method="post">
and in script put it
$("#submit_message").submit(function(e){
e.preventDefault();
//call your ajax
});
I am using jquery validation 1.9.0. I have used the latest Jquery and on back to 1.6.0. with no change in result
My problem is this: When I deliberately put in the wrong values (not enough characters etc) the validation script rightfully shows the errors yet allows the script to be submitted anyways.
I have tried methods of validation including add rules, rules and the very simple form type below.
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
<script>
$(function() {
$("#comm").validate();
});
</script>
the form
<form action="comm.php" method="post" name="comm" id="comm">
Name: <input type="text" name="name" id="name" minlength="3" class="required" />
Email:<input type="email" name="email" id="email" class="required email" /> <br />
<label for="comment"> Comment </label> <br />
<textarea name="comment" id="comment" cols="80" rows="5" minlength="6" class="required" /></textarea>
<?php
date_default_timezone_set('America/New_York');
$date = date("Y-n-j h:i:s");?>
<input type="hidden" name="date" id="date" value="<?php echo $date; ?>" />
<?php $post_id = $id;?>
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>" />
<?php $ip = $_SERVER["REMOTE_ADDR"]; ?>
<input type="hidden" name="ip" id="ip" value="<?php echo $ip; ?>" />
<input type="submit" value="Post" name="post" id="post" /> <input type="reset" value="Reset Form" name="reset" id="reset" />
</form>
Very simple stuff.
Submission happens on all my forms on the net, and all of them on localhost. I can always detect errors but never stop them. What am I doing wrong?
Firebug shows me submitting properly and no script errors. Also all jquerys are connected. Firebug also shows me this After submission novalidate="novalidate" in the form html. using onsubmit=return false does not change anything
I am using ajax to submit the form, works flawlessly
$(function() {
$("#comm").submit(function() {
var data = $('#comm').serialize();
alert (data); return false;
$.ajax({
url: "comm.php",
data: data,
type: "POST",
success: function(msg){
if(msg){
$('.comme').prepend().html(msg).show();
}else{
$('.comme').text("nothing came back");
}
}
});
return false;
});
});
Thank you
Try to do your Ajax handling after clicking the submit button instead of doing with jQuery form submission perhaps you're submitting the form data through Ajax only.
$(function() {
$("#post").click(function() {
var data = $('#comm').serialize();
// TODO: validate your data - $("#comm").validate();
// TODO: submit your form though ajax
// Other operations on form data
return false;
});
});
Note: If the form submission is happening with page redirection then try with 'onsubmit=return false;'.
Update:
I seems you've to submit the FORM from the validate function's submit callback handler(submitHandler) to avoid the redirection after submission. Please try to check this demo example which is working fine with Ajax form submission, review the source code of this example page and then adjust your code accordingly.
var v = jQuery("#form").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
target: "#result"
});
}
});
If you're usig jquery to receive the form when it is submitted, then then you should specify the php file containing the jquery code as the action of the form, instead of "listening" the submit event. Another option would be letting the 'action' parameter empty. The point here is that you're sending the form twice: when you click summit, the form is automatically sent to the file specified in the 'action' parameter, (that is the submission that is taking place, because it has no validation); and, at the same time when you click submit, it also triggers the ajax request, which will perform the validation and in case of success do the submission again.
i have a "wall" on each profile, and i wish to make it smarter, so you don't need to update the page to view your inserted message you just put up.
When you insert a message, it makes a ajax call and inserts to the database, and you receive a message about it has been inserted. But right now you need to refresh the page to see your inserted message. What i want to do is if you insert a new message, it should fadein /refresh the wall with messages that is right under the form.
How can I do this?
I have worked on it alittle and tried to make a new file, inserted all coding to show comments and then i set timeout to refresh each 2 seconds
function ajax_update() {
var wrapperId = '#box';
var profileID = document.getElementById('profileID');
var postFile = 'showcomments.php?id='+ profileID.value;
_v++;
_v2++;
$.post(postFile, { v2: _v2 , v: _v},
function(data){
$(wrapperId).html(data);
});
setTimeout('ajax_update()', 2000);
}
but this isnt good, as it makes too many server calls, so hope you can help me out, since i dont know how i should do this in a cool way
Form with ajax call:
http://phpbin.net/x/838833504
And my current php code that grab from db and list in messages:
http://phpbin.net/x/2145692361
I would suggest a slight methodology change:
submit the new post to the database via AJAX
in the success callback for that AJAX post, create an element with the content that was submitted and append it to the list of posts on the page.
if you want it to look cool just use some of the built in animation effects (fadeIn, show, etc).
This way, you're not polling for changes all the time, and you only have to request things from the server upon page loads.
function DoWallInsert(){
var wrapperId = '#box';
var profileID = document.getElementById('profileID');
$("#insert_response").html("Laddar..");
$.ajax({
type: "POST",
url: "misc/insertWall.php",
data: {
value: 'y',
BuID : $('#BuID').val(),
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
// in here you will have to add the message to the top of the list of wall posts
// to do this you use prepend whatever html and the message in whatever way you
// are using to display the messages.
$(wrapperId).prepend("<div>" + $('#message').val() + "</div>");
}
});
}
html might look like this before:
<form action="javascript:DoWallInsert()" method="post">
<input name="message" type="text" id="message" value="" size="40">
<input type="hidden" name="BuID" id="BuID" value="123123">
<input type="hidden" name="uID" id="uID" value="53425">
<input name="submit" type="submit" id="submit" value="Skicka">
</form>
<div id="box">
<div id="post-1">Some stuff</div>
<div id="post-2">Some other stuff</div>
</div>
html should look like this after:
<form action="javascript:DoWallInsert()" method="post">
<input name="message" type="text" id="message" value="" size="40">
<input type="hidden" name="BuID" id="BuID" value="123123">
<input type="hidden" name="uID" id="uID" value="53425">
<input name="submit" type="submit" id="submit" value="Skicka">
</form>
<div id="box">
<div>Whatever was typed in the box</div>
<div id="post-1">Some stuff</div>
<div id="post-2">Some other stuff</div>
</div>
If the html you want to append to the list of posts has php in it then my best suggestion is to return the html for the new div in the response from the server on the on the AJAX call to this: misc/insertWall.php
insertWall.php should return "<a href='profil.php?id=".$userinfo[id]."'>".$userinfo["full_name"]."</a>". then you can process it and display it in the success part of DoWallInsert():
success: function(msg){
// in here you are receiving a response, you should display it in the page
// this assumes that you are fully formatting the message before returning it
// and you just want to insert it here.
$(wrapperId).prepend(msg);
}
One way is to return the newly updated wall listing from your .post() handler on the server. Then in the callback, repaint the wall area with that content (forget about using setTimeout()). You could also do the same thing, but working message by message, adding the latest message to the top of the "stack" in your wall content area.
So, repainting the whole wall:
$.post(postFile, { v2: _v2 , v: _v},
function(data){
// make your server return the updated wall content
// return data.whatever
// data.wallcontent
$('#wrapperId').html(data.wallcontent);
});
or message by message:
$.post(postFile, { v2: _v2 , v: _v},
function(data){
// make your server return the new message ready for insert
// return data.whatever
// data.message_you_just_posted_formatted
$('#wrapperId')
.prepend( data.message_you_just_posted_formatted );
});
That's the basic idea.