AJAX subscription form not working - php

I'm working on a subscription form. It takes a users email, on click it should check if the email is in the database, if it is return false, if not it should add it and then return true.
I'd like all this done using ajax to improver user experience.
The function no longer seems to be getting called, I'm very new to AJAX so not sure where the problem might be. Any help appreciated.
HTML:
<section>
<h4>Stay Updated</h4>
<p>Sign up for our newsletter. We won't share your email address.</p>
<form name="newsletterForm" id="newsletterForm" action="" method="post">
<div class="input-append row-fluid">
<input type="email" placeholder="Email Address" class="span6" name="newsletterEmail" id="newsletterEmail"/>
<input type="submit" id="newsletterSubmit" name="newsletterSubmit" value="newsletterSubmit" onclick="newsletterSignup(); return false">
<p id="status"></p>
</div>
<!--close input-append-->
</form>
</section>
PHP:
Ive removed the test to chec if the email is present to simplify things.
<?php require(dirname(__FILE__).'../core/init.php');
if($_POST){
$email = $_POST['newsletterEmail'];
if($newsletter->addEmail($email) == true){
$data['message'] = "Signed up";
$data['success'] = true;
}
echo json_encode($data);
}
the php function:
public function addEmail($email){
$query = $this->db->prepare("INSERT INTO `newsletter` (`email`, `signupDate`)
VALUES (?, ?)");
$mysqltime = date ("Y-m-d H:i:s", time());
$query->bindValue(1, $email);
$query->bindValue(2, $mysqltime);
try{
$query->execute();
return true;
}catch(PDOException $e){
die($e->getMessage());
}
}//end add email function
AJAX:
function newsletterSignup(){
var email = $('#newsletterEmail').val();
if(email == ""){
$('input#newsletterEmail').focus();
return false;
}
var params = {email: email};
var url = "newsletterSignup.php";
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function(){
alert("ASD");
document.getElementById("status").innerHTML='<img src="sending.gif"/>sending...';
},
success: function(data){
alert("success");
if(data.success == true){
document.getElementById("status").innerHTML= '<p>Sent!</p>' ;
}else{
document.getElementById("status").innerHTML= '<p>Error!</p>' ;
}
},
error: function(error){
alert("Gets ERRORA");
console.log(error);
}
});
}
It's worth noting that the sign up form is in the footer which is an include. not sure if that's relevant or not.
EDIT: The alert in beforeSend is being shown so I know it's calling the function etc. The alert in error doesn't get called though. There are no XHR messages in the log.

three problems it seems
it couldn't find the php file
when it could it wasn't happy with my require statement at the top
then the POST variable wis named incorrectly.
Now working.

Related

Return success/failure variable with ajax from php script

I'm a really new coder and struggling with a task I'm now working on and trying out for days.
I searched Google and Stack Overflow but can't find a (for me understandable) solution to my problem:
I created a Twitter Bootstrap landing page and there a modal shows up when clicked. In this modal I have a form with a newsletter subscription:
<form id="newsletter" method="post">
<label for="email">Email:</label><br/>
<input type="text" name="email" id="email"/><br/>
<button type="submit" id="sub">Save</button>
</form>
<span id="result"></span>
Now I want to insert the data into a mySQL DB and do some basic validation that returns errors or a success message. The script works fine without ajax, but probably needs alterations on what it returns for ajax?
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
}
if($error) {
$error= "There was an error in your signup,".$error;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
}
}
}
After a lot of reading ajax seems to be the way to do it without the bootstrap modal closing after submit (to suppress default event).
The insertion into the DB works fine, also the validation.
But I can't manage to get the different error messages displayed (stored in the $error variable of the php file) or alternatively the $message in case of success.
This is the jquery script:
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
data: {email: $("#email").val()},
success: function(message) {
$("#result").html(message);
},
error: function(error) {
$("#result").html(error);
}
});
I try to display the value of the error and message variable in the php script within the #result span.
Any help is appreciated. Please formulate it very straight forward since I'm really new to this field.
Thank you a lot in advance.
Edit:
Added some to the php file to create an array and store the messages within:
$response = array();
$response['success'] = $success;
$response['error']= $errors;
exit(json_encode($response));
But have still some trouble to get the ajax to work. Tried the shorthand $.post instead of $.ajax but can't them now even to get to work posting data...
$("#sub").submit(function (){
event.preventDefault();
$.post("newsletter.php", {email: $("#email").val() });
});
Quick time is much appreciated. I'm stuck after hours of testing and can't find the error. If I submit the form regularly it works fine, so the php/mysql part isn't the problem.
I also realized that when I click the "#sub" button, it still tries to submit the form via get (URL gets values passed). So I'm not sure if the event.preventDefault(); isn't working? jQuery is installed and working.
The $.ajax error function gets called when there is a connection error or the requested page cannot be found
You have to print some text out with the php and the ajax success function gets this output. Then you parse this output to see how it went.
The best practice is this:
php part:
$response = array();
$response['success'] = $success;
$response['general_message'] = $message;
$response['errors'] = $errors;
exit(json_encode($response));
js/html part:
$.post("yourpage.php", a , function (data) {
response = JSON.parse(data);
if(response['success']){
//handle success here
}else{
//handle errors here with response["errors"] as error messages
}
});
Good luck with your project
You need to echo your messages back to your AJAX. There is no place in you PHP code where the messages are going back to the message variable in your AJAX success.
include("connection.php");
if ($_POST['email']) {
if(!empty($_POST['my_url'])) die('Have a nice day elsewhere.');
if (!$_POST['email']) {
$error.=" please enter your email address.";
echo $error; die;
} else if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.=" please enter a valid email address.";
echo $error; die;
}
if($error) {
$error= "There was an error in your signup,".$error;
echo $error; die;
} else {
$query="SELECT * FROM `email_list` WHERE email='".mysqli_real_escape_string($link, $_POST['email'])."'";
$result = mysqli_query($link, $query);
$results = mysqli_num_rows($result);
if ($results) {
$error.=" this email address is already registered.";
echo $error; die;
} else {
$query = "INSERT INTO `email_list` (`email`) VALUES('".mysqli_real_escape_string($link, $_POST['email'])."')";
mysqli_query($link, $query);
$message = "Thanks for subscribing!";
echo $message; die;
}
}
}
I basicly just had the same case. I structured my code a little bit different but it works so...
$("#sub").submit(function (){
event.preventDefault();
$.ajax( {
url: "newsletter2.php",
type: "POST",
dataType: 'json',
data: {email: $("#email").val()},
})
.success(function(message) {
$("#result").html(message);
}),
.error(function(error) {
$("#result").html(error);
})
on server side I used C#(asp.net) and just returned a Json
return Json(new { Message = "Something...", Passed = true}, JsonRequestBehavior.AllowGet);
Oukay, finally I managed to solve the problem with the great inputs here. I did the following:
PHP:
$response = array();
$response['success'] = $success;
$response['error'] = $error;
exit(json_encode($response));
JS:
$("#newsletter").submit(function(event) {
event.preventDefault();
$.ajax({
url: 'newsletter3.php',
method: 'post',
data: {email: $('#email').val()},
success: function(data) {
var response = JSON.parse(data);
console.log(response);
if (response['success']) {
$("#error").hide();
$("#success").html(response['success']);
$("#success").toggleClass("alert alert-success");
} else {
$("#error").html(response['error']);
if(!$("#error").hasClass("alert alert-danger"))
$("#error").toggleClass("alert alert-danger");
}
}
});
});
The functionality is now that you click on a button and a modal pops-up, then you can enter your email and the php script validates if its valid and if it's already in the db. Error and success messages get JSON encoded and then are displayed in a span that changes color according to bootstrap classes danger or success.
Thank you very much for helping me, I'm very happy with my first coding problem solved :)
I use this on my ajax
request.done(function (response, data) {
$('#add--response').html(response);
});
and this on the PHP
die("Success! Whatever text you want here");

Ajax returning undefined from JSON - Login system & best practice

I'm receiving an error of undefined when I try and retrieve values in the JSON. I'm new to ajax / js etc and trying to create an 'elegant' drop down login down.
I've tried various things and read a few of the posts that I've found here but I notice that the layout has changed somewhat and I also notice that I'm using success and now that deprecated.
So could I ask for help in firstly understanding what the problem is and how i solve the undefined issue and secondly what is the best way to achieve this. I'd prefer not to use deprecated code if I can help it.
I've also noticed that since changing the code so that it gets to the 'success' park of the ajax call, the drop down box no longer rolls back up or displays the error messages. -.-
Thanks in advance.
The Ajax
function validLogin(){
$('.error').hide();
var username = $('#username').val();
if(username == ""){
$('label#usernameError').show();
$('input#username').focus();
return false;
}
$('.error').hide();
var password = $('#password').val();
if(password == ""){
$('label#passwordError').show();
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../js/loginProcessAjax.php";
$("#statusLogin").show();
$("#statusLogin").fadeIn(400).html('<img src="images/loading.gif" />');
$.ajax({
type: 'POST',
url: url,
data: params,
datatype: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= 'checking...' ;
},
success: function(data) {
alert("success Area ofAjax");
$("#statusLogin").hide();
if(data.success == true){
alert("if data.success Area of Ajax");
alert(data.message);
}else{
alert("data.message... " + data.message);//undefined
$("#errorConsole").html(data.message);
}
},
error: function( error ) {
console.log(error);
}
}, 'json');
}
PHP
<?php
if($_POST){
if($users->userExists($username) === false){
$data['message'] = "User doesn't exist";
$data['success'] = false;
}else if($users->userExists($username) === false){
$data['message'] = 'That username does not exist';
$data['success'] = false;
}else if($users->emailActivated($username) === false){
$data['message'] = 'You need to activate the account, please check your email.';
$data['success'] = false;
}else{
$login = $users->login($username, $password);
if($login === false){
$data['message'] = 'Incorrect Password or username';
$data['success'] = false;
}else{
$data['success'] = true;
//destroy old session and create new - prevents session fixation attacks
session_regenerate_id(true);
//all details are correct - the method returns the id to be sotred as a session
$_SESSION['id'] = $login;
}
echo json_decode($data);
}
}
Markup:
<form method="post" action="" id="ourLoginFormID_JS">
<div class="ourContactFormElement2">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autocomplete="off" class="required" value="<?php if(isset($_POST['username'])) echo htmlentities($_POST['username']); ?>" />
</div>
<div class="ourContactFormElement2">
<label for="password">Password:</label>
<input type="password" id="password" name="password" autocomplete="off" class="required"/>
</div>
<div class="ourContactFormElement2">
<label> </label>
<input type="submit" name="loginButton" id="loginButton" value="Login!" onclick="validLogin(); return false;"/>
</div>
<div id="statusLogin"></div>
</form>
Your if/else/else/else chain only outputs json if the final else block executes. You need to move the json_encode call outside the block:
if (...) {
} else if (...) {
} else if (...) {
} else {
...
}
echo json_encode($data);
This way your code will output the encoded $data, no matter WHICH of the various if() clauses actually executed.
The problem with your undefined error is this:
datatype: 'json',
Javascript is case sensitive and the property is dataType not datatype. Because of this, jQuery is not being told to automatically parse the JSON and so you're just getting the JSON string, causing the undefined error on data.message.
Also I don't see where you access $_POST['username'] or where you instantiate the $users object, I see $username but not $_POST['username'].
A couple of things. You might want to explicitly use contentType parameter of application/json here so that it is clear that you are both sending and receiving JSON.
The main issue is that when sending POST data to PHP that is not form-encoded, $_POST will not be populated automitically. You need to read http raw input like this:
$json = file_get_contents('php://input');
if(!empty($json)) { // replace your if($_POST) with this
$object = json_decode($json);
$username = $object->username;
$password = $object->password;
// the rest of your code
}

Unable to simultaneously POST and JSON with ajax jquery

I suspect that this might be a server issue, but since I do not have access to our server, I was hoping maybe someone else had a fix or could explain to me exactly what is causing the problem.
The problem ....
Using JQuery AJAX I am unable to simultaneously POST data to a php file and receive json encoded data from the php file. If the json dataType is included I am unable to POST data from the form to the php file. If I do not specify the json dataType (i.e. comment it out) then I can POST data to the php file but cannot receive the json encoded data.
I've tried this with my own js/php code and for source code that I downloaded, in order to compare results in case it was just a mistake in my coding. Both are 'submit forms' and both exhibit the problems outlined above. In case its relevant, I include the downloaded source code below. My js/php code uses similar ajax requests.
javaScript:
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
dataString = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm_ajax.php",
data: $("#myForm").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").addClass(msg.status);
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
the PHP:
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
//if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = explode("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//$name = $_POST['name'];
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
EDIT....One Solution
Ok...so I found a hack that works. I don't specify the dataType:'json', i.e. comment that line and the contenType line out. Then I'm able to POST the data. Still have the php file echo the json_encode($response_array). Then put the following code in the success function
var obj = jQuery.parseJSON(msg);
$("#formResponse").addClass(obj.status);
$("#formResponse").html(obj.message);
This is not as nice as being able to specify the dataType:'json' in the ajax call. If anyone has a better solution or can explain why this problem is occurring, let me know.
Thanks
According to me you are doing nothing wrong... except you are specifying to many things...
For eg:
dataType: "json",
is sufficient for ajax call to work.... there is no need for
contentType: "application/json; charset=utf-8",
in your code, if you add this line it returns the empty array in return for some reason (not very sure about the actual reason)....
But moment I specify just
dataType: "json",
it works like a charm where in return I get the object, which I need not parse.
edit:
What I tried is as followring... just change the input name to fname from name and it worked very well
<form id="myForm" name="myForm" method="POST"
action="postform_ajax.php">
name: <input type="text" name="fname" /> <br /> email: <input
type="text" name="email" /> <br /> message: <input type="message"
name="message" /> <br /> <input type="submit" />
<div id="formResponse"></div>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myForm").submit(function() {
dataString = $("#myForm").serialize();
$.ajax({
type : "POST",
url : "postForm_ajax.php",
data : $("#myForm").serialize(),
dataType : "json",
success : function(msg) {
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").html(msg.status);
},
error : function() {
console.log('err', msg);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>

Trying to send data to mysql, receiving callback issue

This is a mailing list script. It works by itself without jquery but I am trying to adapt it to work with ajax. However, without success. When the $.sql part is commented out it returns the variables in the url string successfully. However, when I uncomment that part of the js file and introduce the PHP into things it simply refreshes the page with the email address still in the input box. By itself, the PHP works so I'm at a loss as to where I'm going wrong. Here's what I have... any help would be appreciated.
Form :
<form name="email_list" action="" id="maillist_form">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery :
$(function() {
$('#maillist_form').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $("#maillist_form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});
});
PHP :
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["sub"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add2.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
I won't put the include code in here because I'm assuming it is correct - unless the introduction of the jquery means this needs to be adapted as well.
Your AJAX is not catching back the result:
$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function(response) {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block').html(response); //just an example method.
//Are you sure the selector is the same?
//Can also be $(this).html(response);
}
});
And as noted by gdoron, there's no "name" variable. Maybe you meant "email" and "sub", respectively?
PHP response, also, isn't echoed back. Just put:
echo $display_block;
You don't echo an data from the server, not trying to get data in the success callback, and the fadeIn callback just have a selector,.
You check for the wrong variable:
var email = $("input#email").val();
if (name == "") { // Didn't you mean email?
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") { // Didn't you mean sub?
$("input#sub").focus();
return false;
}
How can it work!?

Ajax Form Sometimes Works, Sometime works and refreshes, Sometimes refreshes and fails ... Bwah?

I've got an ajax form that seems to be very varied in its response. Sometimes it works, sometimes it refreshes but the data is still stored and sometimes if fails all together, and I can't seem to figure out why.
The Form
<form >
<label>Name</label>
<input id="textname" type="text"/><br/>
<label>Message</label>
<textarea id="textmsg"></textarea><br/>
<label> </label>
<input type="submit" value="Send" onclick="return textin();"/><br/><br/>
<label id="textresult"></label>
</form>
Jquery
function textin() {
var name = $("input#textname").first().attr("value");
var msg = $("textarea#textmsg").first().attr("value");
if (msg==null || msg=="")
{
alert("Message cannot be Blank");
return false;
};
$.ajax({
url: '<?=BASEURL?>/le-include/textin.php',
cache: false,
type: "POST",
data: {name : name, msg : msg},
success: function (data) {
$('#textname').attr('value', '');
$('#textmsg').attr('value', '');
$('#textresult').html(data);
$('#textresult').animate({ backgroundColor: $.Color( "rgba(2,232,87,1)" ), color: $.Color( "rgba(0,0,0,1)" ) });
$('#textresult').animate({ backgroundColor: $.Color( "rgba(0,0,0,0)" ), color: $.Color( "rgba(0,0,0,0)" ) });
}
})
};
textin.php
$name = $_POST['name'];
$name = mysql_real_escape_string($name);
$msg = $_POST['msg'];
$msg = mysql_real_escape_string($msg);
$ip = $_SERVER["REMOTE_ADDR"];
databaseSelect("$database");
$sql = "SELECT `ip` FROM `spamip` WHERE ip='$ip' LIMIT 1";
$result = mysql_query($sql);
if(mysql_error()) { print mysql_error(); print '<br/>'; };
$num = mysql_num_rows($result);
if($num == 0) {
$date = date_create();
$stamp = date_format($date, 'U');
$sql = "INSERT INTO `texts` (`name`, `message`, `date`, `ip`) VALUES ('$name', '$msg', FROM_UNIXTIME('$stamp'), '$ip');";
$result = mysql_query($sql);
if(mysql_error()) {
echo "Error";
} else {
echo "Success"; }
} else {
echo "Your IP has been marked as Spam";
}
HTML should be:
<form onsubmit="return textin();">
<label>Name</label>
<input id="textname" type="text"/><br/>
<label>Message</label>
<textarea id="textmsg"></textarea><br/>
<label> </label>
<input type="submit" value="Send"/><br/><br/>
<label id="textresult"></label>
</form>
because otherwise think about what will happen when you press enter while you have focus on text box with id textname
jQuery should be:
function textin() {
var name = $("input#textname").first().attr("value");
var msg = $("textarea#textmsg").first().attr("value");
if (msg==null || msg=="")
{
alert("Message cannot be Blank");
return false;
};
$.ajax({
url: '<?=BASEURL?>/le-include/textin.php',
cache: false,
type: "POST",
data: {name : name, msg : msg},
success: function (data) {
$('#textname').attr('value', '');
$('#textmsg').attr('value', '');
$('#textresult').html(data);
$('#textresult').animate({ backgroundColor: $.Color( "rgba(2,232,87,1)" ), color: $.Color( "rgba(0,0,0,1)" ) });
$('#textresult').animate({ backgroundColor: $.Color( "rgba(0,0,0,0)" ), color: $.Color( "rgba(0,0,0,0)" ) });
}
});
return false;
};
because otherwise the form will be posted normally and not with ajax.
Additional information:
.attr("value") can be replaced in the short command .val()
and
.attr("value", "") can be replaced in the short command .val("")
Impotent! I don't know if you don't want to but you don't check if there is a name given.
You can check with error: function() {} if the internet connection is down or something else happened and give the user an error message.
Check in PHP if the data is send (isset($var)) because otherwise maybe someone is playing around with your website and go to the page and get error messages and that wouldn't be nice.
The answer was given above but let me just add the best way to do something like that is return false. When you return false you will stop the form from submitting (in case of an error).
So let's say I have a form, frmMain; we click a button, it has to do some validation and if successful retrieve some input from the server via AJAX and then post the form. In the jscript ajax function I will call AJAX server.php but also return FALSE to onsubmit (the form). This will stop the form from executing. When AJAX server.php sends back a reply, if it's the correct reply, then in jscript I put frm.submit, or in other words post the form after ajax has returned something. But note, when the form do posts, its done from jscript/after ajax has completed successfully.
Hope this was helpful.

Categories