I'm pretty strong with PHP, but javascript is totally new to me.
I need to add various ajax functionality to my projects, for example for form validation etc.
I've done some searching, watched some tutorials, and come up with a basic working example as follows:
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax form test</title>
<style>
form input, form textarea {
display:block;
margin:1em;
}
form label {
display:inline;
}
form button {
padding:1em;
}
</style>
</head>
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js:
$('form.ajax').on('submit', function() {
console.log('trigger');
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#form_content').load('server.php', data);
}
});
return false;
});
and finally, server.php:
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='')
{
?>
<h4>Your data was submitted as follows</h4>
<br />name: <?=$_POST['name']?>
<br />email: <?=$_POST['email']?>
<br />message: <?=$_POST['message']?>
<?php
} else {
?>
<h3>please fill in all form data correctly:</h3>
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
<?php
}
This all works fine, in that if I enter all form data and click submit, the ajax magic happens and I get a confirmation of the data. Also if not all data is loaded, the form is re-presented on the page. The problem is that in such a case, continuing to fill out the form data and then submit it loads the server.php page instead of repeating the ajax call until the form data is valid..
I'm sure there's a better way to do this as it's my first attempt, but I haven't been able to find any solution by searching either here or on google, but that's probably mostly because I don't really know what to search for. how can I make the behaviour in the first instance repeatable until the form is submitted correctly ?
This happens because you are removing your form element during your load() call and overwrite it with a new version of the form. Therefore all attached event handlers will vanish along with it.
You will need to use a delegate on an element that does not change:
$('#form_content').on('submit', 'form.ajax', function() {...});
Explanation:
In the above example, you attach the event listener to the #form_content element. However, it only listens to events that bubble up from the form.ajax submit event. Now, if you replace the form with a new version, the existing handler is attached higher up in the chain (on an element that doesn't get replaced) and continues to listen to events from lower elements, no matter if they change or not... therefore it will continue to work.
Your primary problem is that you are validating the form on the PHP side, when you should really validate it on the client side - THEN, instead of returning an appropriate response and continuing processing on the client side, you are finishing processing on the PHP side. Steve's answer (above) applies to what you are seeing.
As to the approach you have taken, it might be better to not use a <form> construction at all, because with AJAX you often don't need to. In my opinion, <form> is an archaic structure, not often needed in the age of AJAX. Notice how you had to add return false following the AJAX block to abort the default form functionality -- to stop it from sending the user over to server.php? That should tell you something.
Here is another way to structure it:
HTML:
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="button" id="mybutt" value="send">
</div>
<div id="responseDiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
JAVASCRIPT/JQUERY:
$(document).ready(function() {
//Next line's construction only necessary if button is injected HTML
//$(document).on('click', '#mybutt', function() {
//Otherwise, use this one:
$('#mybutt').click(function() {
console.log('trigger');
var valid = "yes";
var that = $(this),
url = "server.php",
type = "POST",
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (value=="") valid = "no";
data[name] = value;
});
if (valid == "yes") {
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#responseDiv').html(response);
/* OPTIONALLY, depending on what you make the PHP side echo out, something like:
if (response == "allgood") {
window.location.href = "http://www.google.com";
}else{
//this is how you would handle server-side validation
alert('Please complete all fields');
}
*/
}
}); //END AJAX
}else{
alert('Please complete all fields');
}
}); //END button.click
}); //END document.ready
PHP Side: server.php
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='') {
$r = '';
$r .= "<h4>Your data was submitted as follows</h4>";
$r .= "<br />name: " . $_POST['name'];
$r .= "<br />name: " . $_POST['email'];
$r .= "<br />name: " . $_POST['message'];
} else {
$r = "Please complete all form fields";
}
echo $r;
Related
I have a form. That form having some field as like Name, Phone No., Email and submit button
I have an AWS hosted server. have a database also. So I want to know one thing when user will type his name, and phone no. then pass the data to my database without user pressing submit.
Please help me to implement it.
What you are looking for is AJAX. I recommend you to use a library such as JQuery, which will make it a lot easier for you.
What you are looking for is most likely an onBlur method on your inputs. If your are typing in a textfield then it is focused, then when you change textfield it is Blurred. So you'd want something like, .
EDIT
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<form action="" method="post" id="ajaxForm">
<input type="text" id="name" name="name" placeholder="name">
<input type="text" id="phone" name="phone" placeholder="phone">
<input type="email" id="email" name="email" placeholder="email" onfocus="validateAndSubmit()">
<input type="submit" value="Send form">
</form>
<p><label id="result"></label></p>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
<!--
var validateAndSubmit = function()
{
var nameValue = $("#name").val();
var phoneValue = $("#phone").val();
//Validate the data - Do your custom validation here
if (nameValue.length > 3 && phoneValue.length > 5){
//Validation complete
$.post(
"your_save_file.php",
{ name: nameValue, phone:phoneValue },
function(data) {
alert("Data saved");
}
);
document.getElementById("result").innerHTML = "Validation completed";
} else {
//Not validated, do nothing
document.getElementById("result").innerHTML = "Validation failed";
}
};
-->
</script>
</body>
</html>
This will do what you requested. However, I would not recommend you to do this. Because if a user accidently submitted the wrong data then the data will already have been sent. I would recommend you to have a submit button that will activate the function.
Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});
How would I go about showing the response from a submitted contact form (on the same page underneath the form) rather than sending the user to a new page after the submission?
I have seen some people creating a div element, and then putting the received response into it. Is that a recommended approach?
Here is what I have so far:
PHP:
<?php
$name =$_GET['name'];
$email =$_GET['name'];
$message =$_GET['name'];
$to = "support#loaidesign.co.uk";
$subject = "";
$message = "";
$headers = "From: $email";
if(mail($to,$subject,$message,$headers))
{
echo "<h2>Thank you for your comment</h2>";
}
else{
echo "<h2>Sorry, there has been an error</2>";
}
?>
and here is the HTML:
<div class="wrapperB">
<div class="content">
<form id="contactForm" action="assets/email.php" method="get">
<label for="name">Your Name</label>
<input name="name" id="name" type="text" required placeholder="Please enter your name">
<label for="email">Email Address</label>
<input name="email" id="email" type="email" required placeholder="Please enter your email address here">
<label for="message">Message</label>
<textarea name="message" id="message" required></textarea>
<button id="submit" type="submit">Send</button>
</form>
</div>
</div>
</div>
This is a working example using the suggested example from the JQuery site and pajaja's answer.
Solution:
Place this in the <head> of your webpage.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
OR
Download JQuery and include it the same way.
Form:
Your contact form remains un-changed.
<form id="contactForm" action="assets/email.php" Method="POST">
<label for="name">Your Name</label>
<input name="name" type="text" required placeholder="Please enter your name">
<label for="email">Email Address</label>
<input name="email" type="email" required placeholder="Please enter your email address here">
<label for="message">Message</label>
<textarea name="message" required></textarea>
<button type="submit">Send</button>
</form>
Returned Data:
Add your response element where you want in the body.
<div id="contactResponse"></div>
Javascript:
Now place (preferably just before </body>) the javascript code:
<script>
$("#contactForm").submit(function(event)
{
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
$submit = $form.find( 'button[type="submit"]' ),
name_value = $form.find( 'input[name="name"]' ).val(),
email_value = $form.find( 'input[name="email"]' ).val(),
message_value = $form.find( 'textarea[name="message"]' ).val(),
url = $form.attr('action');
/* Send the data using post */
var posting = $.post( url, {
name: name_value,
email: email_value,
message: message_value
});
posting.done(function( data )
{
/* Put the results in a div */
$( "#contactResponse" ).html(data);
/* Change the button text. */
$submit.text('Sent, Thank you');
/* Disable the button. */
$submit.attr("disabled", true);
});
});
</script>
Action Script:
Your contact (PHP) file remains the same but change $_GET to $_POST:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "xxx#xxx.xxx";
$subject = "";
$message = "";
$headers = "From: $email";
if( mail($to,$subject,$message,$headers) )
{
echo "<h2>Thank you for your comment</h2>";
}
else
{
echo "<h2>Sorry, there has been an error</h2>";
}
?>
Result:
This should now send the data from the form on submit and then display the returned data in the #contactResponse element. The button will also set the text to "Sent, Thank you" while also disabling the button.
You will need to use ajax for that. The simplest solution is to get jQuery javascript library an use it's .post function for which you can find documentation and examples here. In your case it will look something like this:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name_value = $("#name").val();
var email_value = $("#email").val();
var message_value = $("#message").val();
$.post("assets/email.php", { name: name_value, email: email_value, message: message_value }).done(function(data) {
$("#response").html(data);
});
});
})
</script>
Also your PHP code is wrong:
$name =$_GET['name'];
$email =$_GET['name'];
$message =$_GET['name']
You are getting $_GET['name'] for all 3 variables.
edit:
I added a complete example but it is not tested it's just so you can have an idea how to do what you want. Also since this is using HTTP POST request, you will need to edit your PHP so it gets values $_POST array, not $_GET. Also you will need to add a <div id="response"></div> where you want to display the response.
You can just keep it on the same page. For example, if your form is on contact.php, just echo your code like so:
<form action='' method='post'>
<input type='test' name='name' placeholder='Your name here' required='required' /><br />
<input type='submit' value='submit' name='contact' />
</form>
<?php
if(isset($_POST['contact']) && !empty($_POST['name'])){
echo "You submitted this form with value ".$_POST['name'].".";
}
?>
Of course this will reload that page. If you don't want the page to be reloaded, you need to use ajax.
I did this with the Jquery Form Plugin. There's another here.
My use case was a lot more involved. It included uploading a file along with some user entered fields and basic auth credentials in the header as well. The Form plugin handled them all using the normal $.ajax fields.
I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']
Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);