Ajax Not Receiving Response From My "Working PHP Script" - javascript

I'm currently making a Contact page using a mixture of Ajax, PHP and MySQL.
A Few Quick Notes:
All of the PHP and AJAX code is working. The only thing that I can't get to work is the response coming from the PHP to the AJAX.
This Contact page has been optimized so that, in the case that JavaScript is disabled on a browser. The page will use a simple POST method to complete the action.
I have a few custom functions (e.g. n()) that have been declared earlier in the files that I'm providing clips from. Please just disregard these as they don't effect anything related to the issue.
A break down of each file can be found underneath each block of code.
contact_page.php (where the magic happens)
header('Content-type: application/json');
if(isset($_POST['l'])) {
if($_POST['l'] == 'php') { //This is related to the PHP version of the form validation. The code that handles the AJAX is farther down
$fd = $_POST['fd'];
$i = 0;
while ($i < count($fd)) { //Used to make sure all fields have been filled. Otherwise, return null.
$fd[$i] = n($fd[$i],false);
if(empty($fd[$i])) { $fd[$i] = null; }
$i++;
}
if(isset($fd[0],$fd[1],$fd[2],$fd[3])) {
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL) && strlen($fd[1]) > 6) {
$q1 = "INSERT INTO contact_msg VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
$h = 'From: Jewl Photography Notifications <contact#jewl-photography.net>' . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-type: text/html; charset=utf-8' . "\r\n" .
'Reply-To: contact#jewl-photography.net' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('nathan#lmartin.net','New Message From: '.$fd[0],$m,$h);
header('Location: https://jewl-photography.net/Contact?w=SNT');
} else {
header('Location: https://jewl-photography.net/Contact?w=INT_ERR');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=FLS_EMAIL');
}
} else {
header('Location: https://jewl-photography.net/Contact?w=MISS_ALL');
}
}
//Below is the code that handles the AJAX
if($_POST['l'] == 'ajax') {
if(isset($_POST['name'],$_POST['email'],$_POST['subject'],$_POST['message'])) {
$fd = array(n($_POST['name'],true),
n($_POST['email'],false),
n($_POST['subject'],false),
n($_POST['message'],false));
if(filter_var($fd[1], FILTER_VALIDATE_EMAIL)) {
$q1 = "INSERT INTO example_table VALUES ('".$fd[0]."','".$fd[1]."','".$fd[2]."','".$fd[3]."',NOW(),'$date-$id');";
$r1 = mysqli_query($dbc1,$q1);
if($r1) {
echo json_encode('SENT');
$h = '
**Header Info**
';
$m = m($fd[0],$fd[2],$fd[3],"$date-$id");
mail('example#example.net','New Message From: '.$fd[0],$m,$h);
} else {
echo json_encode('ERROR_ADD');
}
} else { echo json_encode('FALSE_EMAIL'); }
} else { echo json_encode('NOT_ALL'); }
}
}
The contact_page.php is pretty simple.
It takes the POST info from the Ajax(shown below).
Runs it through a number of encoding functions (e.g. htmlspecialchars() and the like, represented by n() ).
Also tests for if certain requirements are met. If not, it should send a response back to the AJAX (see Step 6)
Adds it to a SQL table.
Sends an email to the moderator to let them know that a new message has been sent.
Then send's a response back to the Contact page using a json object: echo json_encode('Response Text Here');
Everything works except for step 6. For some reason, the AJAX refuses to receive the response. I'm not getting any PHP, SQL or JavaScript errors or warnings, and my Ajax (as you will see below) is using dataType JSON.
Contact.php (the user-side contact page)
<script>
//This first half isn't ajax, skip down a few lines
//The very bottom of tis block of code is the form's html
$(function() {
$('#fglk').submit(function() {
var e = [];
e[0] = $('#name').val();
e[1] = $('#emal').val();
e[2] = $('#subj').val();
e[3] = $('#mesg').val();
if(e[1].length > 6 && e[1].length < 255) {
$('.err-span').removeClass('error');
$('.err-span').html('');
} else {
$('.err-span').addClass('error');
$('.err-span').html('Provide valid Email!');
e[1] = null;
}
/**AJAX Related code \/ **/
if(e[0] && e[1] && e[2] && e[3]) {
var data = new Object();
data.l = 'ajax';
data.name = e[0];
data.email = e[1];
data.subject = e[2];
data.message = e[3];
var options = new Object();
options.data = data;
options.dataType = 'json';
options.type = 'post';
options.success = function (response) {
if(response == 'SENT') {
$('.err-span').html('Sent!');
$('.err-span').addClass('sent');
$('.err-span').addClass('error');
} else if(response == 'ERROR_ADD') {
$('.err-span').html('An internal error prevented your message from being sent!');
$('.err-span').addClass('error');
} else if(response == 'NOT_ALL') {
$('.err-span').html('Please fill out all fields!');
$('.err-span').addClass('error');
} else if(response == 'FALSE_EMAIL') {
$('.err-span').html('You must provide a valid email!');
$('.err-span').addClass('error');
}
};
options.url = 'https://example.net/php/contact_page.php';
$.ajax(options);
} else {
}
return false;
});
});
</script>
<p style='color: red;'>
<? //These $_GET parameters are for if raw PHP is used to send the message
if($_GET['w'] == 'INT_ERR') {
echo '**Some Text**';
}
if($_GET['w'] == 'FLS_EMAIL') {
echo '**Some Text**';
}
if($_GET['w'] == 'MISS_ALL') {
echo '**Some Text**';
}
if($_GET['w'] == 'SNT') {
echo '**Some Text**';
}
?>
</p>
<form action='https://example.net/php/contact_page.php?l=php' id='fglk' method='post'>
<label>Full Name:</label><br><input type='text' id='name' name='fd[]' required><br>
<label>Email:</label><br><input type='email' id='emal' name='fd[]' required><br>
<label>Subject:</label><br><input type='text' id='subj' name='fd[]'><br>
<label>Message:</label><br><textarea id='mesg' name='fd[]' required></textarea><br>
<span class='err-span'></span>
<input type='submit' name='fd[]' value='Send'>
</form>
Contact.php is pretty self explanatory.
It takes the info from the form.
Runs the email through a basic email validation
Passes it to a few JSON objects.
Runs those objects through the $.ajax() function.
Issues the return false; to prevent the form from sending and reloading the page.
After the PHP runs, the AJAX should then take the response and send a message that is written accordingly.
It doesn't throw any errors in my console. It will show an error if I provide an email that is under 6 chars long (this isn't related to the PHP code at all though). But won't show any of the responses.
I've used the same AJAX code before and it's worked fine, the main difference is the PHP backend.
If you have any questions about the code please let me know!
Thanks for your help!

Related

PHPMailer return to AJAX

Currently I' am setting up a email verification system for my personal site. I (try) to handle this with jQuery and AJAX (code follows). But the problem is that it does not return to the echo 2; in my signup.inc.php so that I can continue working in the AJAX call.
As I understand it the compiler should return to/continue from the point where it was redirected, in this case the send_ver_email($user_email) below and echo 2. What did I get wrong? This is pretty new to me and I don't have so much experience , but I don't not what else to try. Tried moving and merging documents, but nothing works.
The AJAX call in JS:
$.ajax({
type: 'POST',
url: 'include/signup.inc.php',
data: 'user_name=' + user_name +
'&user_email=' + user_email +
'&user_pw=' + user_pw,
dataType: 'html',
success: function (data) {
if (data == 0) { // invalid email
... do something
} else if (data == 1) { // account already exists
... do something
} else if (data == 2) {
**This is where it should land after the successful sign up**
return false;
}
}
});
signup.inc.php works great and stores the data in database, so this is not the problem:
include_once "dbc.inc.php";
include_once "verification.inc.php";
if (isset($_POST)) {
//get posted data;
//select $statement
// error handlers
if (filter_var($user_email, FILTER_VALIDATE_EMAIL) === false) {
echo 0;
exit();
} else if ($statement->rowCount() > 0) {
echo 1;
exit();
} else {
// db entry (works great no problems there)
send_ver_email($user_email);
echo 2;
exit();
}
}
the AJAX receives the 2 and reacts as intended if send_ver_email($user_email) is disabled, so I'am very sure that it has something to do with the structure or the way send() handles things. This function is included in verification.inc.php which includes the whole PHPMailer package. And the Email works too! I get every single mail
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
include_once "../PHPMailer/src/Exception.php";
include_once "../PHPMailer/src/PHPMailer.php";
include_once "../PHPMailer/src/SMTP.php";
function generate_ver_code() {
// ...
}
function send_ver_email ($user_mail) {
$verCode = generate_ver_code();
$mail = new PHPMailer;
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->SMTPAuth = true;
$mail->Username = '.......';
$mail->Password = '........';
$mail->setFrom('........', '.......');
$mail->addAddress('.........', '..........');
$mail->Subject = '...........';
$mail->Body = "......................";
$mail->isHTML(true);
$mail->AltBody = '.........';
$mail->send()
}
I am also very grateful for tips about code style and layout :)
EDIT 1: A different approach:
if($mail->send()) {
echo 2;
exit();
} else {
// some error handling
}
This does not crash, I logged everywhere around it, but the ajax still does not register the echo 2
And another try showed:
if($mail->send()) {
} else {
// some error handling
}
and in signup.inc.php:
send_ver_email($user_email);
--------LOGGED HERE---------
echo 2;
exit();
}
This works fine too... this weirds me out the most. Either I got a really dumb typo somewhere or another newbie mistake (hopefully) or ajax handles this echo calls in a very confusing way.
dataType - delete this one.
Add console.log and open console in Your browser
success: function (data) {
console.log( data );
show Your console, and then You will see why. Maybe an unwanted char or php error
Second thing - there should be if stament like this (I supposed)
if (data == "1") // it is returning string, not integer.
You can also try to use switch case in success.

ReCaptcha 2.0 With AJAX

I have managed to get ReCaptcha 2.0 working in my website. However, it's only working when I don't use AJAX and I let the form submit "naturally".
I want to submit the form with the captcha and alert the user with a success note without refreshing the page.
I tried the following code, but it seems like the server doesn't get the user response:
HTML:
<form class="form" action="javascript:void(0)" novalidate>
<!-- all the inputs... -->
<!-- captcha -->
<div class="input-group">
<div class="g-recaptcha" data-sitekey="6LdOPgYTAAAAAE3ltWQGar80KUavaR-JblgPZjDI"></div>
</div>
<div class="errors" id="errors" style="display: none"></div>
<div class="input-group">
<input type="button" value="Send" class="btn-default right" id="submit">
<div class="clear"></div>
</div>
</form>
JS:
$('#submit').click(function(e) {
console.log('clicked submit'); // --> works
var $errors = $('#errors'),
$status = $('#status'),
name = $('#name').val().replace(/<|>/g, ""), // prevent xss
email = $('#email').val().replace(/<|>/g, ""),
msg = $('#message').val().replace(/<|>/g, "");
if (name == '' || email == '' || msg == '') {
valid = false;
errors = "All fields are required.";
}
// pretty sure the problem is here
console.log('captcha response: ' + grecaptcha.getResponse()); // --> captcha response:
if (!errors) {
// hide the errors
$errors.slideUp();
// ajax to the php file to send the mail
$.ajax({
type: "POST",
url: "http://orenurbach.com/assets/sendmail.php",
data: "email=" + email + "&name=" + name + "&msg=" + msg + "&g-recaptcha-response=" + grecaptcha.getResponse()
}).done(function(status) {
if (status == "ok") {
// slide down the "ok" message to the user
$status.text('Thanks! Your message has been sent, and I will contact you soon.');
$status.slideDown();
// clear the form fields
$('#name').val('');
$('#email').val('');
$('#message').val('');
}
});
} else {
$errors.text(errors);
$errors.slideDown();
}
});
PHP:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = '';
if (isset($_POST['g-recaptcha-response']))
$captcha = $_POST['g-recaptcha-response'];
echo 'captcha: '.$captcha;
if (!$captcha)
echo 'The captcha has not been checked.';
// handling the captcha and checking if it's ok
$secret = 'MY_SECRET';
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
var_dump($response);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response['success'] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo 'ok';
} else {
echo 'not ok';
}
?>
The result in the PHP page:
captcha: The captcha has not been checked.array(2) { ["success"]=> bool(false) ["error-codes"]=> array(1) { [0]=> string(22) "missing-input-response" } } not ok
Bottom line is, how can I get the input response manually without it automatically going with the rest of the POST data?
Ok, this was pretty silly.
I have done a couple of things wrong:
In the PHP file, all the strings had single quotes on them, and that caused problems.
Throughout the testing, I added multiple printings of things in the PHP file, thus the if (status == "ok") was never working. I did get the emails but did not get any conformation that I did and now I see why.
When I wanted to check what the PHP file was omitting, I simply went to it's address in the URL and always got an error. Even when the mails were sent. Now I understand that that is not the correct way of checking the logs.
Thanks to #Samurai who helped my figure out things.
Final PHP code:
<?php
// assemble the message from the POST fields
// getting the captcha
$captcha = "";
if (isset($_POST["g-recaptcha-response"]))
$captcha = $_POST["g-recaptcha-response"];
if (!$captcha)
echo "not ok";
// handling the captcha and checking if it's ok
$secret = "MY_SECRET";
$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$captcha."&remoteip=".$_SERVER["REMOTE_ADDR"]), true);
// if the captcha is cleared with google, send the mail and echo ok.
if ($response["success"] != false) {
// send the actual mail
#mail($email_to, $subject, $finalMsg);
// the echo goes back to the ajax, so the user can know if everything is ok
echo "ok";
} else {
echo "not ok";
}
?>

ajax not sending data to specified page

I have been following a tutorial and the person who does it provide the code for you to use, so ive tried using the code and going through it line by line but as i hardly know anything about ajax, i cant seem to understand why it is not passing data through to the page that is specified,and since the data isnt being passed through the process of mysqli queries and all other things, they wont begin to happen as the data isnt being passed over.
The data is part of a form and it is to check usernames against the database to check availability, so the code for the data in the form is ...
<form name="signupform" id="signupform" onsubmit="return false;">
<div>Username: </div>
<input id="username" type="text" onblur="checkusername()" onkeyup="restrict('username')" maxlength="16">
<span id="unamestatus"></span>
<div>Email Address:</div>
<input id="email" type="text" onfocus="emptyElement('status')" onkeyup="restrict('email')" maxlength="88">...
And so on... the js provided is ..
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "email"){
rx = /[' "]/gi;
} else if(elem == "username"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "signupfunc.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("unamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+u);
}
So as far as i understand, var u= _("username").value is the value of the input with the id=username, and if username is not blank then it firstly brings up the checking... before starting the var that is called ajax, it begins the process of POSTing to the page, signupfunc.php, then im not exactly sure the next bit but i think it means something like if something returns from the var ajax then it puts the response return in the unamestatus div ?? then the last bit does as it says? the var ajax sends the value of usernamecheck as the username... but it is not sending the data to the specified page ... can someone point out what im doing wrong advise how to solve this problem ??
and just incase it is needed here is the code that is on the specified page signupfunc.php that is related to the code above..
//Ajax calls this NAME CHECK code to execute
if(isset($_POST["usernamecheck"])){
$username = preg_replace('#[^a-z0-9]#i', '', $_POST['usernamecheck']);
$sql = "SELECT id FROM users WHERE username='$username' LIMIT 1";
$query = mysqli_query($db, $sql);
$uname_check = mysqli_num_rows($query);
if (strlen($username) < 3 || strlen($username) > 16) {
echo '<strong style="color:#F00;">3 - 16 characters please</strong>';
exit();
}
if (is_numeric($username[0])) {
echo '<strong style="color:#F00;">Usernames must begin with a letter</strong>';
exit();
}
if ($uname_check < 1) {
echo '<strong style="color:#009900;">' . $username . ' is OK</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $username . ' is taken</strong>';
exit();
}
}
maybe you can try change you code with below jquery ajax code :
function checkusername(){
var u = _("username").value;
if(u != ""){
_("unamestatus").innerHTML = 'checking ...';
$.ajax({
url : "signupfunc.php",
type : "POST",
data : "usernamecheck="+u,
dataType : 'text',
success: function(data,textStatus,jqXHR){
alert(data);
}
})
}

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Different function for form success and for the form validation messages

I've just been helped with some functions and callbacks to get this animation on my form once submitted:
$("#message").show().delay(5000).fadeOut('fast', function(){
$("#slide_panel").slideToggle("slow");
});
Though, the problem I have now is, if someone had to submit the form without entering the correct details, the error message will also pop up (pops up in the same div "message" as the thank you message), delays for 5 seconds and then closes the form.
Of course, I don't want it to close the form, instead show the error message for 5 seconds and then fadeout the error message.
Anything I need to add here:
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('fast',function()
{$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
$('#name').val( "" );
$('#email').val( "" );
$('#phone').val( "" );
$('#dayin').val( "" );
$('#dayout').val( "" );
$('#comments').val( "" );
$('#verify').val( "" );
$("#message").show().delay(5000).fadeOut('fast',
function(){
$("#slide_panel").slideToggle("slow");
});
}
);
});
return false;
});
});
I'm assuming I need to do something similar to this code:
if(data.match('success') != null);
In my contact.php form.... I have this:
if (isset($_POST['verify'])) :
$posted_verify = $_POST['verify'];
$posted_verify = md5($posted_verify);
else :
$posted_verify = '';
endif;
// Important Variables
$session_verify = $_SESSION['verify'];
if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
$error = '';
if(trim($name) == '') {
$error .= '<li>Your name is required.</li>';
}
if(trim($email) == '') {
$error .= '<li>Your e-mail address is required.</li>';
} elseif(!isEmail($email)) {
$error .= '<li>You have entered an invalid e-mail address.</li>';
}
if(trim($phone) == '') {
$error .= '<li>Your phone number is required.</li>';
} elseif(!is_numeric($phone)) {
$error .= '<li>Your phone number can only contain digits.</li>';
}
if(trim($comments) == '') {
$error .= '<li>You must enter a message to send.</li>';
}
if($session_verify != $posted_verify) {
$error .= '<li>The verification code you entered is incorrect.
</li>';
}
if($error != '') {
echo '<div class="error_message">Attention! Please correct the
errors below and try again.';
echo '<ul class="error_messages">' . $error . '</ul>';
echo '</div>';
} else {
if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); }
Anything I need to do here? Or do I only need to edit the javascript file?
if you use JSON to call a function somewhere in the code behind you will be able to return a status property.
I used it aswell in my current project and here is an example of how I used it:
var link = '/brainbattleJSON/MarkAssignmentAsInProgress';
$(this).hide();
$.getJSON(link, { questionId: qId }, function (json) {
if(json.status == "ok"){
//do this
}else{
//do this
}
});
Code behind:
// your function with validation
// if the form is valid make status "ok" otherwise put anything else
Return Json(New With {.status = "ok"});
I hope this can help you a bit :)
Edit:
You will need to change the value of var link to the path of your function where you check the form.
Then where you now say if your error!='' you will send back the json.
in this you will say:
return json(new with{.status = 'error', .errors = 'yourErrors'})
So for errors it might be useful to send an array just in case if you get more than 1 error on the form.
All the messages will no longer be shown in php with echo but you will have to put the errors there with javascript.
I have a uploaded register and login pages(zip file) at following link:
http://www.4shared.com/folder/uanQHCAg/_online.html
It uses same div to display success and error messages. You can try and implement what you are looking for, with an addition of fadeout effect.

Categories

Resources