Get ajax result in different divs if success or error - javascript

I currently have my jQuery outputting the result in the same div as per error or success:
HTML
<div id="error-message").html(res);
JQUERY
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
});
});
PHP
$error = '';
$uname = trim( $_POST['username'] );
$email = trim( $_POST['mail_id'] );
$fname = trim( $_POST['firname'] );
$lname = trim( $_POST['lasname'] );
$pswrd = $_POST['passwrd'];
if( empty( $_POST['username'] ) )
$error .= '<p class="error">Enter Username</p>';
if( empty( $_POST['mail_id'] ) )
$error .= '<p class="error">Enter Email Id</p>';
elseif( !filter_var($email, FILTER_VALIDATE_EMAIL) )
$error .= '<p class="error">Enter Valid Email</p>';
if( empty( $_POST['passwrd'] ) )
$error .= '<p class="error">Password should not be blank</p>';
if( empty( $_POST['firname'] ) )
$error .= '<p class="error">Enter First Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) )
$error .= '<p class="error">Enter Valid First Name</p>';
if( empty( $_POST['lasname'] ) )
$error .= '<p class="error">Enter Last Name</p>';
elseif( !preg_match("/^[a-zA-Z'-]+$/",$lname) )
$error .= '<p class="error">Enter Valid Last Name</p>';
if( empty( $error ) ){
$status = wp_create_user( $uname, $pswrd ,$email );
if( is_wp_error($status) ){
$msg = '';
foreach( $status->errors as $key=>$val ){
foreach( $val as $k=>$v ){
$msg = '<p class="error">'.$v.'</p>';
}
}
echo $msg;
} else {
$msg = '<p class="success">Registration Successful</p>';
echo $msg;
}
} else {
echo $error;
}
die(1);
}
}
I'm getting confused on how to get the results in 2 different places.
1: Error = display errors and show the form, ideally errors should be displayed below each form field, at the moment is a div on top of the form
2: Success = hide the form, display only the success msg

METHOD 1
If you would like to have an error message per validated field then:
You have a form input, for example:
<input name="myfield" id="myfield" type="text">
Next to it, you can add a div or span with your alert/error message and appropriate id, something like:
<input name="myfield" id="myfield" type="text">
<span id="myfield_Error" class="none">Please fill this field</span>
Where class="none" in your css, is used to hide the error container. Something like:
.none {display:none;}
Now for your jquery part:
var myfield= $("#myfield").val();
if (myfield=='') { $("#myfield_error").show(); }
The trick here is to named your error containers in a similar way as your target form element you validate. So for id="fieldA" you will have the error id="fieldA_error".
EDIT1:
If you need to use classes, you need to modify a little the code.
You need to form an array of element to check.
Loop through the array.
And use somethign like:
var fieldName = $(this).attr('name');
var fieldVallue = $(this).val();
if (fieldVallue=='')
{
$("#"+fieldName+"_error").show();
}
else
{
$("#"+fieldName+"_error").hide;
}
Method 2
If you just like to have 2 different containers, one for success and one for error/failed validation, then you need to output something different from your php file.
So your php file can output someting like:
$report['status'] = 'error'
$report['message'] = 'error in xxxx field - please use a proper email'
echo json_encode($report);
Then in your ajax success you can check what response you got. You parse your json response and based on your 'status', you put your 'message' in different containers
I hope this is what you look for.

Alternatively you can assign an error handler as follow
var jqxhr = jQuery.post(
ajaxurl,
ajaxdata,
function(res){
$('#loadingmessage').hide();
$("#myform").show();
jQuery("#error-message").html(res);
}
).fail(function() {
alert("error");
});
and send a non-2xx code from your php code (with http_response_code) if it doesn't validate.

It would be easier for you to return (for example) JSON to the front end instead of one string. The JSON would containt key/value pairs in the form of ID => Message.
For example:
$errors = array();
if( empty( $_POST['passwrd'] ) ) {
$errors['st-psw'] = "Password should not be blank";
}
if( empty( $_POST['firname'] ) ) {
$errors['st-fname'] = 'Enter First Name';
} elseif( !preg_match("/^[a-zA-Z'-]+$/",$fname) ) {
$errors['st-fname'] = 'Enter Valid First Name';
}
...
...
if( empty( $errors ) ){
$response['success'] = true;
} else {
$response['success'] = false;
$response['errors'] = $errors;
}
echo json_encode($response);
Then you will loop the JSON object in your javascript and insert the error messages after each target.

Encode result array in JSON format and return the response.
<?php
if ($validation==false)
{
$result = array ('response'=>'error','message'=>'Some validation error');
}
else
{
$result = array ('response'=>'success','message'=>'Success');
}
echo json_encode($result);
?>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
dataType: "json",
success: function (data) {
if (data.response == 'error') {
alert('error');
} else if (data.response == 'success') {
alert('success');
} else {
alert('sorry there was an error');
}
}
});
</script>

Related

PHP/Ajax Form Sumission

I have designed a Sidebar Floating Form with PhP/Ajax which is working and sending submission to my targeted email. Here is the Link: http://logohour.com/form.html but when a visitor fill and submit the form successfully it routes him to another page for the confirmation.
This shouldn't be like this and must be stick to the homepage with popup Message as per my coding:
<div id="sendingMMessage" class="statusMessage"> <p>Sending your message. Please wait...</p> </div>
<div id="successMMessage" class="statusMessage"> <p>Thanks for sending your message! We'll get back to you shortly.</p> </div>
Below you may find my Ajax & PHP for reference:
<?php
// Define some constants
define( "RECIPIENT_NAME", "John Smith" );
define( "RECIPIENT_EMAIL", "example#gmail.com" );
define( "EMAIL_SUBJECT", "SiderBar Visitor Message" );
// Read the form values
$ssuccess = false;
$Name = isset( $_POST['Name'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['Name'] ) : "";
$Email = isset( $_POST['Email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Email'] ) : "";
$Phone = isset( $_POST['Phone'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Phone'] ) : "";
$Country = isset( $_POST['Country'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Country'] ) : "";
$Select = isset( $_POST['Select'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['Select'] ) : "";
$Message = isset( $_POST['Message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['Message'] ) : "";
// If all values exist, send the email
if ( $Name && $Email && $Phone && $Country && $Select && $Message ) {
$msgToSend = "Name: $Name\n";
$msgToSend .= "Email: $Email\n";
$msgToSend .= "Phone: $Phone\n";
$msgToSend .= "Sender Country: $Country\n";
$msgToSend .= "Sender Select: $Select\n";
$msgToSend .= "Message: $Message";
$recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";
$headers = "From: " . $Name . " <" . $Email . ">";
$ssuccess = mail( $recipient, EMAIL_SUBJECT, $msgToSend, $headers );
}
// Return an appropriate response to the browser
if ( isset($_GET["ajax"]) ) {
echo $ssuccess ? "ssuccess" : "error";
} else {
?>
<html>
<head>
<title>Thanks!</title>
</head>
<body>
<?php if ( $ssuccess ) echo "<p>Thanks for sending your message! We'll get back to you shortly.</p>" ?>
<?php if ( !$ssuccess ) echo "<p>There was a problem sending your message. Please try again.</p>" ?>
<p>Click your browser's Back button to return to the page.</p>
</body>
</html>
<?php
}
?>
var messageDDelay = 2000; // How long to display status messages (in milliseconds)
// Init the form once the document is ready
$(init);
// Initialize the form
function init() {
// Hide the form initially.
// Make submitForm() the form's submit handler.
// Position the form so it sits in the centre of the browser window.
// When the "Send us an email" link is clicked:
// 1. Fade the content out
// 2. Display the form
// 3. Move focus to the first field
// 4. Prevent the link being followed
$('a[href="#contact_form"]').click(function() {
$('#content').fadeTo('slow', .2);
$('#contact_form').fadeIn('slow', function() {
$('#Name').focus();
})
return false; });
// When the "Cancel" button is clicked, close the form
$('#cancel').click(function() {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);
});
// When the "Escape" key is pressed, close the form
$('#contact_form').keydown(function(event) {
if (event.which == 27) {
$('#contact_form').fadeOut();
$('#content').fadeTo('slow', 1);}});}
// Submit the form via Ajax
function submitFForm() {
var contact_form = $(this);
// Are all the fields filled in?
if (!$('#Name').val() || !$('#Email').val() || !$('#Phone').val() || !$('#Country').val() || !$('#Select').val() || !$('#Message').val()) {
// No; display a warning message and return to the form
$('#incompleteMMessage').fadeIn().delay(messageDDelay).fadeOut();
contact_form.fadeOut().delay(messageDDelay).fadeIn();
} else {
// Yes; submit the form to the PHP script via Ajax
$('#sendingMMessage').fadeIn();
contact_form.fadeOut();
$.ajax({
url: contact_form.attr('action') + "?ajax=true",
type: contact_form.attr('method'),
data: contact_form.serialize(),
ssuccess: submitFFinished }); }
// Prevent the default form submission occurring
return false; }
// Handle the Ajax response
function submitFFinished(response) {
response = $.trim(response);
$('#sendingMMessage').fadeOut();
if (response == "ssuccess") {
// Form submitted ssuccessfully:
// 1. Display the ssuccess message
// 2. Clear the form fields
// 3. Fade the content back in
$('#successMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#Name').val("");
$('#Email').val("");
$('#Phone').val("");
$('#Country').val("");
$('#Selct').val("");
$('#Message').val("");
$('#content').delay(messageDDelay + 500).fadeTo('slow', 1);
} else {
// Form submission failed: Display the failure message,
// then redisplay the form
$('#failureMMessage').fadeIn().delay(messageDDelay).fadeOut();
$('#contact_form').delay(messageDDelay + 500).fadeIn(); } }
Below the simple ajax form submission. Hope it will help your need.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script>
$(function () {
$('form#consultationForm').on('submit', function(e) {
$.ajax({
type: 'post',
url: 'receivedConfirmation.php',
data: $(this).serialize(),
success: function (result) {
console.log(result);
$('#receivedStatus').attr('style','display:block');
$('#receivedStatus').html(result);
}
});
e.preventDefault();
});
});
</script>
<form id="consultationForm" method="post">
Firstname: <input name="fname" />
Lastname: <input name="lname" />
<div style='clear:both;'></div>
<input type="submit" name="submit" value="save"/>
<input type="reset" name="cancel" value="cancel"/>
</form>
<div id='receivedStatus' style='display:none;'></div>
receivedConfirmation.php
<?php
echo "<PRE>";
print_r($_POST);
echo "</PRE><br>";
//do your DB stuffs here and finally echo your response based on success or failure
echo "Thanks for sending your message! We'll get back to you shortly.";
echo "<br>Click your browser's Back button to return to the page."
?>
First you have to avoid the normal form submission for this form and you can do this by using normal button instead of submit button.
<input type="button" id="sendMMessage" name="sendMMessage" value="Submit">
Execute a javascript ajax submit code onclick of sendMMessage id.
and this will solve your problem.
Updated answer :
$( "#target" ).click(function() {
// put your ajax form submit code here
$.ajax({
type: "POST",
url: 'http://logohour.com/sidebar-form.php',
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data); // show response from the php script.
}
});
});
If you are still unclear about this I will explain you more detail.
thanks.

PHP form handler with jQuery script duplicating emails

I have a php function handling the results of a form delivered from a jQuery script, as the form content is also delivered to a Workbooks CRM url to be added to records there.
All works fine, except the email is sent 3 times. The button clicked is not inside the form, and the 'send' value for isset($_POST) is delivered from a hidden form field in the form.
I've tried:
Adding flags, both in PHP and in the jQuery.
Adding alerts in the jQuery.
Adding exit("sent"); after the mail() function.
The alert() experiment appeared to indicate the jQuery wasn't the issue, but flags seemed to indicate the same in the PHP!
Here's the jQuery:
$(document).ready(function () {
$("#test-vf-button1").click(function (event) {
event.preventDefault();
// Field values as array
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var formData = $("#wb_form").serialize();
var url = $(location).attr('hostname');
var pathname = $(location).attr('pathname');
var pageUrl = url + pathname;
console.log(pageUrl);
$("#validate-message").empty();
$("#confirm-message").empty();
if (name == '' || email == '' || message == '') {
$("#validate-message").append(" Fill in required fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: 'POST',
url: "http://visual-factory.co.uk/",
data: formData,
success: function () {
$.ajax({
type: 'POST',
url: "https://secure.workbooks.com/crm/web_leads",
crossDomain: true,
data: formData,
dataType: 'text',
success: function () {
PHP handling function:
function vf_deliver_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST['send'] ) ) {
// sanitize form values
$title = sanitize_text_field( $_POST['person_lead_party']['person_personal_title'] );
$name = sanitize_text_field( $_POST['person_lead_party']['name'] );
$jobrole = sanitize_text_field( $_POST['person_lead_party']['person_job_role'] );
$email = sanitize_text_field( $_POST['org_lead_party']['main_location']['email']);
$phone = sanitize_text_field( $_POST['org_lead_party']['main_location']['telephone'] );
$company = sanitize_text_field( $_POST['org_lead_party']['name'] );
$country = sanitize_text_field( $_POST['org_lead_party']['main_location']['country'] );
$messagecontent = esc_textarea( $_POST['vf-message'] );
$message = "<p>Title: ".$title."</p>";
$message .= "<p>Name of lead is: ".$name."</p>";
$message .= "<p>Job Role: ".$jobrole."</p>";
$message .= "<p>Email is: ".$email."</p>";
$message .= "<p>Phone is: ".$phone."</p>";
$message .= "<p>Company is: ".$company."</p>";
$message .= "<p>Country is: ".$country."</p>";
$message .= "<p>Message: ".$messagecontent.".</p>";
// get the blog administrator's email address
$to = get_option( 'admin_email' );
$subject = "Form response";
$headers = "From: $name <$email>" . "\r\n";
mail( $to, $subject, $message, $headers ) ;
}
}

Passing variables from PHP to AJAX success function

My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},

How to use OnComplete?

I'm trying to use a Javascript/AJAX function that send an email (using a PHP page).
The function is:
new Request({
method: "post",
data: this,
onRequest: function() {
$('amCallMeBackForm').empty().addClass('amCallMeBackWait');
$('callback').setStyle('background', 'url(\'http://www.mysite.it/modules/mod_amcallmeback/assets/sfondo_callback.png\') no-repeat transparent');
$('callback').setStyle('height', '73px');
},
onComplete: function(response) {
$('amCallMeBackForm').removeClass('amCallMeBackWait');
$('amCallMeBackForm').addClass('amCallMeBackSent');
alert(response);
}
}).send();
});
It works fine, but i cannot manage the response from PHP page, where i've this code:
<?php
class modAmCallMeBackHelper
{
function send($params) {
// Check for request forgeries
JRequest::checkToken() or die( 'Invalid Token' );
// get data
$name = JRequest::getVar('name', '');
$rif = JRequest::getVar('rif', '');
$phone = JRequest::getVar('phone', '');
$uri = JRequest::getVar('uri', '');
// get module params
$subject = $params->get('mail_subject');
$reciptient = explode(',', $params->get('receipt_email'));
$app = JFactory::getApplication();
$sender = array($app->getCfg('mailfrom'), $app->getCfg('fromname'));
// make email
$Body = '<strong>Azienda:</strong> '.$name."<br />";
$Body .= '<strong>Riferimento:</strong> '.$rif."<br />";
$Body .= '<strong>Numero di telefono:</strong> '.$phone."<br />";
$Body .= '<strong>Pagina da cui รจ stato richiesto il contatto:</strong> <a href='.$uri.'>'.$uri."</a>";
$mailer =& JFactory::getMailer();
$mailer->setSender($sender);
$mailer->addRecipient($reciptient);
$mailer->setSubject($subject);
$mailer->isHTML(true);
$mailer->Encoding = 'base64';
$mailer->setBody($Body);
if ($name == '' || $rif == '' || $phone == '' || $name == 'Azienda' || $rif == 'Riferimento' || $phone == 'Telefono') {
} else {
$send =& $mailer->Send();
}
if ($send != true) {
return 'no';
} else {
return 'ok';
}
}
}
?>
When alert(response) is displayed i can see the whole html code ( included) from the page, but I'm not able to show only the "return" from the PHP page.
What am I doing wrong?
You can check an example of my problem here: http://www.sevenit.it (check at the top right of the page after 3 seconds)
Thanks
alert(response.responseText);
would be the way to go i believe.
EDIT:
Or what you might be wanting to do is:
$('#amCallMeBackForm').html(response.responseText)
Not 100% sure what you're asking.

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