PHP form with response on same page - php

Hi I created a PHP form - I am getting the email but the the response message opens in the same window with plain text. If someone could point me in the right direction that would be great.
This is the output once submitted:
{"status":"success","message":"Thank you for your interest in Nature's Apprentice.
A representative will be in contact with you shortly","email_sent":true}
This is the contact form code:
<form name="formContact" id="formContact" action="contact-submit.php" method="post" novalidate="novalidate">
<label for="name">Name <span class="required" >*</span></label>
<input name="name" id="name" class="form-control " placeholder="First and Last Name" type="text">
<label for="email">Email <span class="required" >*</span></label>
<input name="email" id="email" class="form-control" placeholder="email#domain.com" type="text">
<label for="phone">Phone</label>
<input name="phone" id="phone" class="form-control" placeholder="(xxx) xxx-xxxx" type="text">
<label for="address">Area of Interest </label>
<input name="address" id="address" class="form-control" placeholder="Location" type="text">
<label for="comments">Comments</label>
<textarea name="comments" id="comments" placeholder=""></textarea>
<input name="submit" id="submit" class="submit_btn" value="Submit" type="submit">
<img src="images/loader.gif" alt="Loader" class="loader">
<div class="info_msg">
<p><span class="required">*</span> indicates required field.</p>
</div>
<div class="response_msg">
<p></p>
</div>
</form>
This is the js:
jQuery(document).ready(function ($) {
$("#formContact").validate({
ignore: ".ignore",
rules: {
name: "required",
email: {
required: true,
email: true
}
},
invalidHandler: function (form, validator) {
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Please fill all the required fields.');
},
submitHandler: function (form) {
$.ajax({
type: "POST",
url: $(form).attr('action'),
data: $(form).serialize(), // serializes the form's elements.
beforeSend: function(){
$('img.loader').fadeIn();
},
success: function (data) {
var json = $.parseJSON(data);
//alert(json.status , json.message);
$('#formContact').find('#response_msg p').removeClass().html('');
if(json.status !='') {
if(json.status == 'success') {
$('#formContact').trigger('reset');
}
setTimeout(function(){
$('#formContact').find('#response_msg p').removeClass().addClass(json.status).html(json.message).fadeIn();
}, 1000);
}
},
error:function (xhr, ajaxOptions, thrownError){
$('#formContact').find('#response_msg p').removeClass().addClass('error').html('Some error occured. Please try again.').fadeIn();
},
complete: function(){
$('img.loader').fadeOut();
}
});
}
});
});
</script>
This is the contact-submit.php:
//session_start();
require 'include/include.php';
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$phone = trim($_POST['phone']);
$address = trim($_POST['address']);
$comments = trim($_POST['comments']);
$errors = array();
if($name == '' or $email == '' ) {
$response = array('status' => 'error', 'message' => 'Please fill all the required fields.');
echo json_encode($response);
exit;
}
else {
if(strlen($name) < 3) {
$errors[] = 'Name should be 3 characters long.';
}
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter valid email.';
}
$errors = array_filter($errors);
if (!empty($errors)) {
$message = implode("<br>", $errors);
$response = array('status' => 'error', 'message' => $message );
echo json_encode($response);
exit;
}
else {
$mailsubject = "Contact Us Form Details - ".$site_name;
$sendmessage = "Dear Administrator,<br /><br />
<b>Name:</b> $name<br /><br />
<b>Email:</b> $email<br /><br />
<b>Phone:</b> $phone <br /><br />
<b>Address:</b> $address <br /><br />
<b>Comments:</b> $comments <br /><br />";
$mail_str = "";
$mail_str = '<html><head><link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css"></head><body style="max-width: 600px; margin: 0 auto; font-family: Open Sans, sans-serif; font-size: 15px; line-height: 20px;"> <table style="border:1px solid #000000" width="95%" align="center" cellspacing="0" cellpadding="0"> <tbody><tr style="background-color:#365744"><td style="padding: 10px; ">'.$site_name.'</td></tr><tr style="background-color:#ffffff"><td style="padding: 10px; ">'.$sendmessage.' </td></tr><tr style="background-color:#383634; color: #fff;"><td style="padding: 10px; ">Thanks! - '.$site_name.'</td></tr></tbody></table></body></html>';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = sprintf('From: %s <%s>', $name, $email);
$headers = implode("\r\n", $headers);
#echo "<hr/>"; echo $to_mail;echo "<hr/>";echo $mailsubject;echo $mail_str; echo $headers; exit;
$emailsend = mail($admin_email, $mailsubject, $mail_str, $headers);
if($emailsend) {
$response = array('status' => 'success', 'message' => sprintf('Thank you for your interest in %s. <br /> A representative will be in contact with you shortly', $site_name), 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
else {
$response = array('status' => 'error', 'message' => 'Some error occured. Please try again.', 'email_sent' => $emailsend);
echo json_encode($response);
exit;
}
}
}
#---------------Mail For Admin (Ends)--------------------------------------------------
//header("Location:thank-you.html");
exit;
?>```

According to your code class="response_msg" should be id="response_msg" in your form.
You should be setting the header when returning json.
header('Content-Type: application/json');

Try adding a preventDefault call. Otherwise, the form is probably being submitted via the normal form POST process after your Ajax is finished and thus is redirecting to the contact-submit.php page and you see the echo out of the response on a blank page.
Try this edit:
...
submitHandler: function (form, e) {
e.preventDefault();
$.ajax({
type: "POST"
...

I've debugged your code and tested it as working. You need to add the following 4 changes:
Specify the data type to jQuery. Add the dataType line as below.
data: $(form).serialize(), // serializes the form's elements.
dataType: 'json',
beforeSend: function(){
Let jQuery do the JSON parsing. Change this:
success: function (data) {
To this:
success: function (json) {
Get rid of this line:
var json = $.parseJSON(data);
Your #response_msg selector is off, because you've given the container a .response_msg class, instead of an id. Change this:
<div id="response_msg">
To this:
<div class="response_msg">
Or change the selectors to refer to the class instead.
And things should then work as expected.

Related

How do i stop the form validation code from repeating when i click the submit button (php ajax jquery html)

Hey all i'm new to working with ajax but i am trying to make some form validation and its going well except for this code repeating itself.
This is what happens after clicking the submit button twice... and if i keep pressing submit it keeps repeating. I only need it to show once no matter how many times the submit button is pressed.
Much appreciated to anyone who could give me a hint on how to stop this code repeating!! Thanks!
The forms action calls this php file:
$errors = [];
$data = [];
// change the $error message for each field here
if (empty($_POST['name'])) {
$errors['name'] = '<div class="my-3 alert alert-danger";>Please enter a valid name.</div>';
} else if (!empty($_POST['name'])) {
$errors['name'] = '<div class="my-3 alert alert-success";>Name Entered.</div>';
}
if (empty($_POST['email'])) {
$errors['email'] = '<p class="my-3 alert alert-danger";>Please enter a valid email address.</p>';
} else if (!empty($_POST['email'])) {
$errors['email'] = '';
}
if (empty($_POST['comment'])) {
$errors['comment'] = '<p class="my-3 alert alert-danger";>Please leave a comment.</p>';
} else if (!empty($_POST['comment'])) {
$errors['comment'] = '';
}
// if the fields are not empty then return successful
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$data['success'] = true;
$data['message'] = 'Your Request Has Been Successful! <a class="text-success" href="./">Click here to continue.</a>';
}
echo json_encode($data);
I also have this form.js file linked:
$(document).ready(function () {
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
comment: $("#comment").val(),
};
$.ajax({
type: "POST",
url: "./php/process.php",
data: formData,
dataType: "json",
encode: true,
})
.done(function (data) {
console.log(data);
if (!data.success) {
if (data.errors.name) {
$("#name-group").addClass("has-error");
$("#name-group").append(
'<div class="help-block">' + data.errors.name + "</div>"
);
}
if (data.errors.email) {
$("#email-group").addClass("has-error");
$("#email-group").append(
'<div class="help-block">' + data.errors.email + "</div>"
);
}
if (data.errors.comment) {
$("#comment-group").addClass("has-error");
$("#comment-group").append(
'<div class="help-block">' + data.errors.comment + "</div>"
);
}
} else {
$("form").html(
'<div class="alert alert-success">' + data.message + "</div>"
);
}
})
.fail(function (data) {
$("form").html(
'<div class="alert alert-danger">Could not reach server, please try again <a href="./test-form" >here</a>.</div>'
);
});
event.preventDefault();
});
});
And finally the form itself:
<form action="./php/process.php" method="POST">
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Full Name"
onchange="myFunction()" />
</div>
<div id="email-group" class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" name="email"
placeholder="email#example.com" onchange="myFunction()" />
</div>
<div id="comment-group" class="form-group">
<label for="comment">Leave a comment:</label>
<input type="text" class="form-control" id="comment" name="comment"
placeholder="Leave a comment" onchange="myFunction()" />
</div>
<button type="submit" class="btn btn-success">
Submit
</button>
</form>

Sending an email with ajax and object oriented php best practices

I am building a form to send an email and I want to use Object Oriented Php and Ajax.
I was able to build the PHP backend (variable and function) regardless of Ajax, but I have problems in making the Ajax call because I have not yet understood what are the steps to follow.
My problem is that I don't really understand how the ajax URL works (the call the to PHP file). Should I try to target the function (and how can I do) or should I call the page directly, in which I'm gonna create the json function to output a json file to parse with ajax?
Here's my code:
Footer.php and main.js
$('#contact-form').on('submit',function(e) {
e.preventDefault();
$('.output-message').text('Loading...');
const form = $(this);
const post_url = $(this).attr("action");
console.log(post_url);
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
if (result == 'success'){
$('.output-message').text('Message Sent!');
} else {
$('.output-message').text('Error Sending email!');
}
}
});
return false;
});
<form id="contact-form" name="contact-form" action="Contact.php" method="POST" data-parsley-validate="">
<div class="row">
<div class="col-md-6">
<div class="md-form mb-0">
<input type="text" id="name" name="name" class="form-control" required="">
<label for="name" class="">Your name</label>
</div>
</div>
<div class="col-md-6">
<div class="md-form mb-0">
<input type="email" id="email" name="email" class="form-control" required="">
<label for="email" class="">Your email</label>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="md-form">
<textarea type="text" id="message" name="message" rows="2" class="form-control md-textarea" required=""></textarea>
<label for="message">Your message</label>
</div>
</div>
</div>
<div class="text-center text-md-right">
<input type="submit" id="submit" class="btn-primary" name="submit" value="Request Info">
<span class="output-message"></span>
</div>
</form>
And the php Class:
Contact.php
<?php
class Contact {
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
echo '<p class=\'message error\'>';
echo '<font color="black">' . $errors . '</font>';
echo '</p><br />';
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
$sendMail->sendMail();
}
?>
The javascript part doesn't work, and I'm trying to understand this part:
const post_url = $(this).attr("action");
$.ajax({
url: post_url,
Should I create another function in PHP that will output a JSON file that collects all the variables?
My though is that I'm serializing the URL and then I will send it to the PHP file, but I'm not even able to console.log() the result.
Refactor a little bit :
class Contact
{
public $name;
public $email;
public $message;
public $admin = 'myemail#email.email';
public $errors;
public function sendMail() {
$errors = "";
if ($this->name == "") {
$errors .= '- You forgot to enter a name!<br />';
}
if ($this->email == "") {
$errors .= '- You forgot to enter an email!<br />';
}
if ($this->message == "") {
$errors .= '- You forgot to enter a message!<br />';
}
if(empty($errors)) {
$contents = "To: $this->name<br />Message: $this->message";
$headers = "From:" . $this->email;
$sendmail = mail($this->admin, $this->message, $contents, $headers);
} else {
throw new Exception($errors, 400);
}
}
}
if(isset($_POST['submit'])) {
$sendMail = new Contact();
$sendMail->name = $_POST['name'];
$sendMail->email = $_POST['email'];
$sendMail->message = $_POST['message'];
header('Content-Type: aaplication/json');
try {
$sendMail->sendMail();
echo json_encode(array('success' => 'success'));
} catch (Exception $e) {
header ('HTTP/1.1 400 Bad Request')
$errors = array('error' => $e->getMessage);
echo json_encode($errors);
}
}
I've made it return the string instead of echoing in the class, and I've thrown an exception on an error. Also, since we are sending to JS I made it return JSON.
Lastly, change the JS here:
$.ajax({
url: post_url,
method: form.attr('method'),
data: form.serialize(),
type:'POST',
success: function(result){
console.log(result);
$('.output-message').text('Message Sent!');
}
error: function(result) {
console.log(result);
$('.output-message').text('Error Sending email!');
}
});
JS will check a 200, so know if it is success. Since you now send a 400 on error, the error function will trigger! Give that a try :-)

AJAX page not meeting success criteria...Error in JSON return type....Always showing "There is an error" no matter what

**Hi guys. I created an AJAX page that validates a form and displays errors.But the problem is no matter what it always displays there is an error **
Contact form:
<form id="contact-form" method="post" action="">
<fieldset>
<label for="name" class="fullname">
<span>Full name:</span>
<input type="text" name="fullname" id="fullname">
</label>
<label for="email" class="email">
<span>Email:</span>
<input type="email" name="email" id="email">
</label>
<label for="name1" class="message">
<span>Message:</span>
<textarea name="name1" id="name1"></textarea>
</label>
<div class="btns">
<a class="button" onClick="document.getElementById('contact-form').reset()">Clear</a>
<a class="button" name="submit" id="submit">Send</a>
</div>
</form>
The AJAX program that I wrote is
<script>
$(document).ready(function(){
$('#submit').click(function() {
$('#contact-form').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val(),
name1 : $('#name1').val(),
name : $('#fullname').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#contact-form').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#contact-form').show(500);
}
});
return false;
});
});
</script>
And Lastly the PHP Code for Validation is
<?php
$return['error'] = false;
while (true) {
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
break;
}
if (empty($_POST['name'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you name.';
break;
}
if (empty($_POST['name1'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you message.';
break;
}
break;
}
if (!$return['error'])
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . ' as email, ' . $_POST['name'] . ' as name and ' . $_POST['email'] . ' as url.';
echo json_encode($return);
?>
It would be great help if extra validators for email check and length check are added.Thanks a LOT in advance.
Change your input type text or write valide email
<input ng-model="t.unsubscribeEmail" type="text" class="textboxfields" placeholder="Enter email address">
or write valide email in
<input ng-model="t.unsubscribeEmail" type="email" class="textboxfields" placeholder="Enter email address">
use this link

Contact form don't send well

I have a problem when sending data to the contact form. Data is sent to e-mail only if you click many times, but if you tab to move to the button and press enter data is sent immediately. But still fall into the spam.
HTML
<div id="f1" class="contact_wrapper">
<form>
<div id="r2"></div>
<input type="text" name='rname' id="names" class="name" placeholder="Ваше имя">
<input type="email" name='email' id="eml" class="email" placeholder="Ваше Email">
<input type="text" name='subject' id="phon" class="contact_number" placeholder="Контактный телефон">
<textarea name="message" id="masage" cols="30" rows="10"></textarea>
<input name="" id="button" type="button" value="Отправить" class="submit" onclick="mail2('Радиус-01 Оформить заявку - последняя форма','names','eml','phon','masage','f1','r2')">
</form>
</div>
AJAX
<script>
function mail2(subject,names,eml,phon,masage,f,rr){
var names = document.getElementById(names).value;
var eml = document.getElementById(eml).value;
var phon = document.getElementById(phon).value;
var masage = document.getElementById(masage).value;
var frt = document.getElementById('generator_konr').value;
var params = {subject:subject,names:names,eml:eml, phon:phon,masage:masage,kon:frt};
$.ajax({
type: "POST",
url: "mail2.php",
data: params,
success: function(data){
$('#ertretgfdg').html(data).fadeIn("slow");
}
});
}
</script>
mail2.php
<?
### Referals script start
$debug=0;
function writelog($s) {
global $lf,$debug;
if ($debug)
fputs($lf,"$s\n");
}
if ($debug)
$lf=#fopen(dirname(__FILE__).'/'.'debug.log','a');
$t=date('Y-m-d H:i:s');
$utm='нет';
$term='нет';
$ip=$_SERVER['REMOTE_ADDR'];
$utmdata='';
writelog("Session started (zakaz.php) at '$t', IP='$ip'");
writelog("REQUEST: ".print_r($_REQUEST,true));
if (isset($_COOKIE['utmdata'])) {
writelog("Found saved cookie UTMdata");
$utmdataexp=explode('&',$_COOKIE['utmdata']);
if (count($utmdataexp)>=2 && !empty($utmdataexp[0]) && !empty($utmdataexp[1])) {
$t=$utmdataexp[0];
$utm=$utmdataexp[1];
$term=isset($utmdataexp[2]) ? $utmdataexp[2] : 'нет';
$utmdata=$t.'&'.$utm.'&'.$term;
}
}
writelog("UTMdata is '$utmdata'");
### Referals script end
$phon = $_POST['phon'];
$names = $_POST['names'];
$subject = $_POST['subject'];
$kon = $_POST['kon'];
$eml = $_POST['eml'];
$masage = $_POST['masage'];
if ($names=='' or $names=='Введите ваше имя') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите свое имя");</script>';
exit;
}
if ($phon=='' or $phon=='Ваш телефон' or $phon=='Введите номер телефона') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите номер телефона");</script>';
exit;
}
if ($eml=='' or $eml=='Ваш email' or $eml=='Введите ваш email') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваш email");</script>';
exit;
}
if ($masage=='' or $masage=='Ваше сообщение' or $masage=='Введите ваше сообщение') {
echo '<script>$().toastmessage(\'showErrorToast\', "Введите ваше сообщение");</script>';
exit;
}
$er=null;
if ($subject=='Выбран конкретный генератор') {
$ert='Генератор: '.$kon.'<br/>';
}
$body ='
По вопросу: '.$subject.'<br/>
'.$ert.'
Имя: '.$names.'<br/>
Телефон: '.$phon.'<br/>
Мыло: '.$eml.'<br/>
Сообщение: '.$masage.'<br/>
Рекламная площадка:</b> '.$utm.'<br />
Ключевое слово: '.$term.'<br />
';
$email='myemail#gmail.com';
$headers = "Content-type: text/html; charset=utf-8\r\n";
$headers .= "From: <".$em.">\r\n";
if (mail($email, $subject_t, $body, $headers)) {
echo '<script>$().toastmessage(\'showSuccessToast\', "Сообщение успешно отправлено");</script>
<script>$(".header .sform").delay( 2000 ).slideToggle();</script>';
exit;
} else {
echo '<script>$().toastmessage(\'showErrorToast\', "Ошибка, повторите попытку");</script>';
exit;
}
?>
<!--

PHP/Ajax contact form clear input fields only if success

I've a simple working php/ajax contact form with validation. I'd like to clear all fields after VALID submission, so I tried $("#myform")[0].reset(); see in the code below. It clears the form nicely, but the problem is it also clears everything when the validation wasn't successful, which is really annoying.
Here's the HTML:
<form id="myform" method="post" action="sendEmail.php">
<div id="container">
<div id="main">
<p>Name / Company <span>*</span></p>
<input type="text" name="name" id="name" />
<p>Email Address <span>*</span><p>
<input type="text" name="email" id="email" />
<p>Offer / Message <span>*</span></p>
<textarea name="message" id="message" rows="6"></textarea>
<p><input type="submit" name="submit" id="submit" value="Send Request" /></p>
<p><ul id="response" /></p>
</div>
</div>
And the php:
<?php
$name = trim($_POST['name']);
$email = $_POST['email'];
$message = $_POST['message'];
$site_owners_email = 'sample#yahoo.com';
$site_owners_name = 'Joe';
if (strlen($name) < 3) {
$error['name'] = "* Please enter your name.";
}
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "* Please enter a valid email address";
}
if (strlen($message) < 4) {
$error['message'] = "* Please leave an offer / message.";
}
if (!$error) {
require_once('phpMailer/class.phpmailer.php');
$mail = new PHPMailer();
$mail->From = $email;
$mail->FromName = $name;
$mail->Subject = "Subject";
$mail->AddAddress($site_owners_email, $site_owners_name);
$mail->Body = $message;
$mail->Send();
echo "<li class='success'> Thanks for your request!<br> We will respond to you as soon as possible. </li>";
} # end if no error
else {
$response = (isset($error['name'])) ? "<li>" . $error['name'] . "</li> \n" : null;
$response .= (isset($error['email'])) ? "<li>" . $error['email'] . "</li> \n" : null;
$response .= (isset($error['message'])) ? "<li>" . $error['message'] . "</li>" : null;
echo $response;
} # end if there was an error sending
?>
At last, the js:
$(function() {
var paraTag = $('input#submit').parent('p');
$(paraTag).children('input').remove();
$(paraTag).append('<input type="button" name="submit" id="submit" value="Send Request" />');
$('#main input#submit').click(function() {
$('#main').append('<img src="images/ajax-loader.gif" class="loaderIcon" alt="Loading..." />');
var name = $('input#name').val();
var email = $('input#email').val();
var message = $('textarea#message').val();
$.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'name=' + name + '&email=' + email + '&message=' + message,
success: function(results) {
$('#main img.loaderIcon').fadeOut(1000);
$('ul#response').html(results);
$("#myform")[0].reset();
}
}); // end ajax
});
});
I'm new to php and js, so I've pasted all of my code, to be easier for you if i did something wrong. Thanks for your help!
Well, a good idea is returning a JSON object form PHP, so you can check for errors on Javascript.
PHP:
$result = array(
"error" => false,
"html" => null
);
if(!$is_valid){
$result["error"] = true;
$result["html"] = "<b>Error</b>";
}else{
$result["error"] = false;
$result["html"] = "<b>Success</b>";
}
echo json_encode($result);
jQuery
$.ajax({
type: 'post',
url: 'url.php',
data: {/*put a cool data here*/},
dataType : "json", // return a json object
success: function(result) {
if(result.error){
/* On error stuff */
$("body").append(result.html);
}else{
/* On success stuff */
$("body").append(result.html);
}
}
});

Categories