Ajax Contact form validation and submit - ajax

I'm trying to make a HTML contact form. Here's my code
`Get in Touch
<p class="success-sending-message">Thank you, your message has been sent!</p>
<p class="error-sending-message">There has been an error, please try again.</p>
<div id="contact-form">
<form action="" id="contactForm" class="styled" method="post">
<label for="contact_name">Name</label>
<input type="text" tabindex="3" id="contact_name" name="contact_name" value="" class="requiredField textbox" />
<label for="contact_email">Email</label>
<input type="text" tabindex="4" id="contact_email" name="contact_email" value="" class="requiredField email textbox" />
<label for="contact_subject">Subject</label>
<input type="text" tabindex="5" id="contact_subject" name="contact_subject" value="" class="requiredField textbox" />
<label for="contact_message">Your Message</label>
<div class="textarea-wrap">
<textarea cols="65" rows="9" tabindex="6" id="contact_message" name="contact_message" class="requiredField"></textarea>
</div>
<div class="form-section">
<button class="button" tabindex="7" type="submit" id="born-submit" name="born-submit">Send Message</button>
<input type="hidden" name="submitted" id="submitted" value="true" />
<span class="sending-message"><img src="css/images/loading-light.gif" /> Sending...</span>
</div>
</form>
</div>`
And here's my validation script
$(window).load(function() {
/* Ajax Contact form validation and submit */
jQuery('form#contactForm').submit(function() {
jQuery(this).find('.error').remove();
var hasError = false;
jQuery(this).find('.requiredField').each(function() {
if(jQuery.trim(jQuery(this).val()) == '') {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
hasError = true;
} else if(jQuery(this).hasClass('email')) {
var emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!emailReg.test(jQuery.trim(jQuery(this).val()))) {
jQuery(this).addClass('input-error');
hasError = true;
}
}
});
if(!hasError) {
jQuery(this).find('#born-submit').fadeOut('normal', function() {
jQuery(this).parent().parent().find('.sending-message').show('normal');
});
var formInput = jQuery(this).serialize();
var contactForm = jQuery(this);
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
}
return false;
});
jQuery('.requiredField').blur(function() {
if(jQuery.trim(jQuery(this).val()) != '' && !jQuery(this).hasClass('email')) {
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
} else {
if (jQuery(this).is('textarea')){
jQuery(this).parent().addClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
}
});
jQuery('.email').blur(function() {
emailReg = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(emailReg.test(jQuery.trim(jQuery(this).val())) && jQuery(this).val() != '') {
jQuery(this).removeClass('input-error');
} else {
jQuery(this).addClass('input-error');
}
});
jQuery('.requiredField, .email').focus(function(){
if (jQuery(this).is('textarea')){
jQuery(this).parent().removeClass('input-error');
} else {
jQuery(this).removeClass('input-error');
}
});
});
My form is working properly, After filling details It is showing me "Thank you, your message has been sent!" But where is this message going, I don't have any of the process.php file and all. I want that email should be send to my email id.

Bonjour ... Look in the firebug or chrome developper tools console to see the post trace.
In your php file, you can put echos or var_dump to be sure all it's ok.
Another thing ... the form action is empty.

Currently there's no where it is going. Give where it needs to go in the action="" attribute of the <form>. And also, in the actioned URL, typically, a PHP file, give this code:
<?php
if (count($_POST))
{
$name = $_POST["contact_name"];
$email = $_POST["contact_email"];
$subject = $_POST["contact_subject"];
$message = $_POST["contact_message"];
$mail = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message";
if (mail("mymail#domain.com", "New Mail from Contact Form", $mail))
die ("OK");
else
die ("Fail");
}
?>
Also, you need to make a small correction in your JavaScript AJAX Call. Replace this way:
jQuery.ajax({
type: "POST",
url: jQuery(this).attr('action'),
data: formInput,
success: function(data){
if (data == "OK")
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().prev().show('normal'); // Show success message
});
else
alert ("Message not sent!");
},
error: function(data){
contactForm.parent().fadeOut("normal", function() {
jQuery(this).prev().show('normal'); // Show error message
});
}
});
Test if your server supports SMTP through PHP Script
Create a small file, which has this content, say mail.php:
<?php
var_dump(mail("yourmail#gmail.com", "Testing Message", "This mail was sent from PHP Script."));
?>
And try to access the file and see what you are getting. Please update the same in your question.

Related

ajax post failed but controller & db data ok

im posting data to controller with partailview the controller receive valid data & store it in my DB but:
im getting ajax failed Msg.
im not getting a TempData displayed as expected ( i have one for results OK and else for error).
Im not sure where to put my finger on .
Index View
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
function SubmitREgNews() {
var data = {
userName: $("#name").val(),
UserMail: $("#email").val(),
TermsOk: $("#bOk").val(),
};
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function(result) {
alert('Successfully received Data ');
console.log(result);
},
error: function() {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
}
Partial view
#if (#TempData["ErrorMes"] != null)
{
#TempData["ErrorMes"]
}
#if (#TempData["regOk"] == null)
{
<div class="row">
<div class="col-md-4">
<form id="studenteForm" novalidate class="needs-validation">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="userName" class="control-label"></label>
<input asp-for="userName" class="form-control" id="name" required />
</div>
<div class="form-group">
<label asp-for="UserMail" class="control-label"></label>
<input asp-for="UserMail" type="email" class="form-control" id="email" /> </div>
<div class="form-group form-check">
<label class="form-check-label">
<input class="form-check-input" id="bOk" asp-for="TermsOk" /> #Html.DisplayNameFor(model => model.TermsOk)
</label>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" onclick="SubmitREgNews();">Add </button>
</div>
</form>
</div>
</div>
</div>
}
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
controller
public IActionResult _RegNews()
{
return PartialView();
}
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews )
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if ( ModelState.IsValid && IsNewUser==null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return View("home/index");
}
else
{
TempData["ErrorMes"] = "You are allready register";
}
return PartialView("_RegNews", joinNews);
}
The reason you are getting ajax failed Msg may be that you are returning the wrong path "home/index". Paths in one controller that call a page in another controller should use "../home/index".
Also, Ajax doesn't change page elements. If you want to redirect to another page you can use Url.Action.
Like this:
Controller:
[HttpPost]
public async Task<IActionResult> Create([Bind("JoinId,userName,UserMail,TermsOk")] JoinNews joinNews)
{
var IsNewUser = await _context.joinNewsL.FirstOrDefaultAsync(a =>
a.UserMail.ToUpper() == (joinNews.UserMail.ToUpper()));
if (ModelState.IsValid && IsNewUser == null)
{
joinNews.JoinId = Guid.NewGuid();
joinNews.JoinDate = DateTime.Now;
_context.Add(joinNews);
await _context.SaveChangesAsync();
TempData["regOk"] = "You are register";
return Json(new { redirectUrlOne = Url.Action("Index", "Home")});
}
else
{
TempData["ErrorMes"] = "You are allready register";
return Json(new { redirectUrlTwo = Url.Action("_RegNews", "NewsLetter") });
}
}
And your ajax:
$.ajax({
type: 'POST',
url: "/NewsLetter/Create",
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: data,
success: function (result) {
alert('Successfully received Data ');
if (result.redirectUrlOne !== undefined) {
window.location.replace(result.redirectUrlOne);
} else {
window.location.replace(result.redirectUrlTwo);
}
console.log(result);
},
error: function (error) {
alert('Failed to receive the Data');
console.log(JSON.stringify(error));
console.log('Failed ');
}
});
If you don't want to use Url.Action, you can also do not use Ajax, using the Form Tag Helper to submit data is the same. You can check the details in this official document.

Ajax submit and replace submit button with checkmark after success

First, I'm not having luck with ajax submitting at all in cakephp 1.3 environment. Once I successfully submit, I'm hoping user stays on page and submit button hidden or replaced with a checkmark. I've tried a few things... controller without $action and then .click function instead of on submit. I'm also not versed in debugging js to see where it might be wrong so any suggestions are welcome.
Maybe "update_a" is the $action within my dashboard controller
"function applications($action) {" instead?
dashboard controller
function update_a($action) {
...
switch ($action) {
case 'save':
if (!empty($this->data)) {
// update fields in database table matching model
$this->data['Model']['submitted'] = $_POST['submitted'];
$this->data['Model']['locked'] = $_POST['locked'];
if ($this->Model->save($this->data)) {
// save form fields to other models
$this->OtherModel->saveField('form_status_id',$_POST['form_status_id']);
$this->OtherModel->saveField('form_status',$_POST['form_status']);
}
}
}
break;
default:
//$this->redirect("admin/index");
$this->render("dashboard/applications");
break;
} //case
} // end function
html
<body>
<form id='update_a' action='save'>
<div class='form-group'>
<input type='hidden' class='hidden' name='locked' id='locked' value='1'>
<input type='hidden' class='hidden' name='form_status' id='form_status' value='Locked'>
<input type='hidden' class='hidden' name='form_status_id' id='form_status_id' value='3'>
<input type='hidden' class='hidden' name='submitted' id='submitted' value='<?php echo date("Y-m-d G:i:s") ?>'>
</div>
<div class='text-center'>
<input name='submit' type='button' class='btn btn-default' value='Submit Form A'>
</div>
</form>
</body>
<script>
$(document).ready(function () {
$('#update_a').on('submit', function (e) {
//$('#update_a').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/dashboard/update_a',
data: $('#update_a').serialize(),
success: function () {
alert('Form A has been submitted and locked for editing');
$('#update_a').hide();
},
error : function() {
alert("Error");
}
});
return false;
});
});
</script>

controller not sending data back to ajax request codeigniter

I have developed a login system using ajax the problem is when i send the ajax request everything is working and validating fine i just need to pass data back to my ajax request I am using echo json_encode("true"); but somehow it is just echoing the value true in the controller and not going back in the view!
HTML
<form onsubmit="return validate()" method="post" action="<?php echo base_url(); ?>admin/admin_login">
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='submit' class="btn btn-primary btn-block btn-large">Login</button>
</form>
AJAX
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true;
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
admin_login controller
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
//redirect("Admin/contact");
header('Content-Type: application/json');
echo json_encode("true");
}
else
{
header('Content-Type: application/json');
echo json_encode("false");
//redirect("Admin");
}
}
Now iam going to change the code little
change the HTML form to
<form>
<input class="md-input" placeholder="username" type="text" name = 'login_username' id = 'login_username' />
<input class="md-input" placeholder="password" type="password" name= 'login_password' id= 'login_password' />
<button type='button' onclick="validate()" class="btn btn-primary btn-block btn-large">Login</button>
</form>
and Now change your ajax to
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
$.ajax({
type: 'post',
url: '<?php echo base_url()."Admin/admin_login"; ?>',
data:{ "login_username" : $("#login_username").val(), "login_password" : $("#login_password").val() },
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}
</script>
and your controller to
public function admin_login(){
$data = $this->input->post();
$status=$this->admin_validate->validate($data);
if($status){
$session=array(
"admin"=>$this->input->post("login_username"),
);
$this->session->set_userdata($session);
echo "true";
}
else
{
echo "false";
}
}
Hope this helps you. :)
Have you tried sending true or false without the quotation marks?, if not try creating an array and then passing it to the echo json_encode(); something like:
$result = array();
array_push($result, true);
echo json_encode($result);
on your ajax you will have to read it as follow
if(data[0] == true){
alert("Ok");
}else{
alert("Not OK");
}
Hope it helps
you are returning true in the script so the form is get submitted. no ajax call occurs.
<script>
function validate(){
if(!$("#login_username").val()){
alert("username is required");
return false;
}
if(!$("#login_password").val()){
alert("Password is required");
return false;
}
return true; // HERE THE ISSUE //
var data={
"login_username" : $("#login_username").val(),
"login_password" : $("#login_password").val()
};
$.ajax({
type: 'post',
url: '<?=base_url()?>Admin/admin_login',
dataType: 'json',
data:data,
success: function (data) {
if(data=="true"){
alert("ok");
}
else
{
alert("not ok");
}
}
});
}

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

can't get json return in codeigniter

I have a login page, that sends a ajax request to the server when someone tries to log in. The ajax, goes to the server, cause they get logged in I've been able to confirm. But the problem is it seems my jQuery isn't receiving the JSON.
The function in my controller is:
public function login(){
$this->load->model('users_model');
if((!!$this->input->post('email')) || (!!$this->input->post('password'))){
$ret = $this->users_model->login($this->input->post('email'), $this->input->post('password'));
echo json_encode(array('status' => "OK", 'msg' => 'Logged in!')); //also tried return
}else{
echo json_encode(array('status' => 'FAIL', "msg" => 'Invalid Email or Pass'));
}
}
and the AJAX function is:
<script type="text/javascript">
$(document).ready(function() {
$("#login").ajaxForm(function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
};
});
});
</script>
if I alert the json variable, it's blank, and if I do json.msg it say undefined. So... what do I have to do to get this to give the callback, a json object, or an object of any kind? Please explain it so I understand the problem, not just how to fix it. Thanks a lot!
EDIT:
Here's the form too:
<span class="error_msg"></span></br>
<form id="login" action="<?php echo base_url(); ?>users/login" method="POST" enctype="multipart/form-data">
Email: <input name="email" type="text"/></br>
Password: <input type="password" name="password"></br>
<input type="submit"/>
</form>
Ah, I think I understand.
Is this the plugin you are using? http://www.malsup.com/jquery/form/#api
In that case, use ajaxSubmit, not ajaxForm.
Other examples online do something like this:
$(document).ready(function() {
$('#login').submit(function() {
$("#login").ajaxSubmit({
success: function(json) {
alert(json);
if(json.status == true) {
alert(json.msg);
//window.location = '<?php echo base_url(); ?>';
} else {
alert("Problem");
$(".error_msg").html(json.msg);
}
}
});
return false;
});
});

Resources