I'm using the Jquery Ajax to post a form data and display the success message. Everything works fine, but I'm not able to display the success message. Below is the code :
Javascript
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#stage').empty();
var postForm = { //Fetch form data
"name": $("#name").val(),
"element_4_1": $("#element_4_1").val(),
"element_4_2": $("#element_4_2").val(),
"element_4_3": $("#element_4_3").val(),
"email": $("#email").val(),
"input4": $("#input4").val(),
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'contact.php', //Your form processing file url
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
console.log("inside success3") ;
alert(data);
$("#stage").html(data);
if (!data.success) { //If fails
if (data.errors) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors); //Throw relevant error
console.log("inside failure") ;
}
} else {
console.log("inside success") ;
$('#stage').fadeIn(1000).append('<p>' + data.posted + '</p>');
console.log("inside success2") ;
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
PHP :
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$errors = array();
$form_data = array();
header('Content-type: application/json');
echo json_encode($form_data);
$name=$_POST['name'];
$phone=chop($_POST['element_4_1']);
$phone.=chop($_POST['element_4_2']);
$phone.=chop($_POST['element_4_3']);
$email=chop($_POST['email']);
$message1=chop($_POST['input4']);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: sales#test.com \n";
$recipient= "test#test.in";
$subject="Online Enquiry ";
$message="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you for contacting us";
$message_reply="Thank you for contacting us. We will get back to you shortly.";
//mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(isset($recipient, $subject, $message, $headers)) {
error_log($message);
$form_data['status'] = 'success';
error_log($form_data['status']);
} else {
$form_data['status'] = 'error';
error_log($form_data['status']);
} ?>
HTML
<div id="stage">
</div>
How can I print the success message
You have this at the start of your php script:
echo json_encode($form_data);
where $form_data is an empty array at that time.
You should remove that and put it at the end.
Related
I've created contact form that send form data to an email
then I'm sending ajax to the server which returns json response with success message or alert message
but I'm getting the data commented as below :
<!-- TESS -->
// {"type":"success","message":"Contact form successfully submitted. Thank you, I will get back to you soon!"}
this is the php code :
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}
and the js code :
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "../../forms/contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
console.log(alertBox,messageText);
console.log("data ",data,data.type,data.message);
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// console.log("messages ok")
// inject the alert to .messages div in our form
$('.messages').append(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
this code is taken from this tutorial
HOW TO BUILD A WORKING BOOTSTRAP CONTACT FORM
I am writing a program that send bulk email to our registered users via ajax.
I want echo every loop response when it is completed and it goes to next condition.
For Example:-
I have list of 100 Emails in database. When i submitted the request to program it will start sending emails.
Prog. works something like :
<?php
foreach($emails as $email){
$status = $this->sendMail($email);
if($status == true)
{
echo "Mail Sent";
}else{
echo "Not Sent";
}
}
?>
Now i want to print "Mail Sent"/"Not Sent" again and again for every loop.
Output:-
Mail Sent
Mail Sent
Mail Sent
Not Sent
Mail Sent
Sending..
EDIT
My PHP Code is:-
<?php
public function send_message() {
$sendTo = $this->input->post('send_to');
$template = $this->input->post('template');
$subject = $this->input->post('subject');
switch ($sendTo) {
case 1:
$users = $this->getAllEmails();
break;
case 2:
$users = $this->getRegisteredUsersEmails();
break;
case 3:
$users = $this->getTemproryUsersEmails();
break;
case 4:
$users = $this->getSubscribersEmails();
break;
}
$status = $this->sendMail($users, $template, $subject);
echo "Mail Sent";
}
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
return $status;
}
?>
My Ajax Code :-
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
data:$(this).serialize(),
success:function(data){
$("#status").html(data);
}
}
});
</script>
You have to do your loop with javascript/jquery rather than PHP. To have no overflow on server-side you should probably only call the function on success by using recursion. This way it will be synchronous.
jQuery
var emails = [
'lorem#stackoverflow.com',
'ipsum#stackoverflow.com',
'foo#stackoverflow.com'
];
index = 0;
var sendMail = function(email){
$.ajax({
url:"sendMail.php",
type: "POST"
data: { emailId: email}
success:function(response) {
index++;
document.write(response);
if(emails[index] != undefined){
sendMail(emails[index]);
}
}
});
}
sendMail(emails[index]);
PHP
$status = $this->sendMail($$_POST['email']);
$msg = $status ? "Mail Sent" : "Not Sent";
echo $msg;
I want to print the response when each time "$this->mail->send" function is called in "sendMail()"
As your code above, $status should be return in ajax function like a json object array.so I try this one ...
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
echo json_encode($status);
}
Ajax Code
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
dataType : "json",
data:$(this).serialize(),
success:function(data){
$.each(data,function(i,v){
$("#status").append(v.status);
}
}
}
});
</script>
My php runs but for some reason my variables are not being communicated. What am I doing incorrectly? I am trying to relay the message through ajax and i can't seem to get any type of error or success message to pop up, no matter where I put it in my php..which leads me to believe that the problem lies inside my ajax/javascript functions. The ajax should place the message straight in the defined . I also realize this has been asked before on here but I have truly looked at a lot of them and still can not figure out what's wrong. Thanks guys, sorry for the wall.
AJAX
<!-- Email -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('#sub_result').html("");
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'phEmail.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for email ---------------
if (data.errors.email) {
$('#sub_result').addClass('class="error"'); // add the error class to show red input
$('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#sub_result').append('<div class="success" >' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false)
{
$errors['email'] = 'Email is not valid';
}
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
}
// if there are items in our errors array, return those errors============================
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
//variables===============================================================================
$servername = "localhost";
$username = "ghostx19";
$password = "nick1218";
$dbname = "ghostx19_samplepacks";
$user = $_POST['email'];
// Create connection======================================================================
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection failed";
}
//add user================================================================================
$sql = "INSERT INTO users (email)
VALUES ('$user')";
if ($conn->query($sql) === TRUE) {
$data['success'] = true;
$data['message'] = 'Subscribed!';
} else {
$errors['email'] = 'Error';
}
$conn->close();
// message to me==========================================================================
$to = 'garvernr#mail.uc.edu';
$subject = 'New subscription';
$message = $_POST['email'];
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
//message to user=========================================================================
$to = $_POST['email'];
$subject = 'Subscribed!';
$message = 'Hello new member,
Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information. If you have recieved this email by mistake or wish to no longer be apart of this community please contact nickgarver5#gmail.com
Cheers!,
-Nick Garver ';
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
?>
HTML
<!-- Subscription -->
<div class="container shorter">
<div class="no-result vertical-align-outer">
<div class="vertical-align">
<form action="phEmail.php" method="POST">
<!-- EMAIL -->
<div id="email-group" class="form-group">
<label for="email"></label>
<input type="text" class="email" name="email" placeholder="Enter your email">
<button type="submit" class="emailbtn">Subscribe</button>
<span></span>
<!-- errors -->
</div>
</div>
</div>
</div>
<br>
<br>
<div id="sub_result">
</div>
You just need to use json_encode in your PHP becuase your data type is json and you are expecting the response in json format like that
if (!empty($error)){
// your stuff
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
}
else {
// your stuff
$data['success'] = "SUCCESS MESSAGE";
$data['errors'] = false;
echo json_encode($data);
}
That's because you forgot to encode your $data array. Do echo json_encode($data); just before your ending PHP tag(?>), like this:
// your code
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo json_encode($data);
?>
Your php don't return any value, add a simple "echo" line at the end:
...
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo $data['message'];
?>
And in js (if all the other code is correct) you receive the message.
Your php file doesn't send anything to the output.
Add a line
exit(json_encode($data));
to your php file on the line where you want to return your reply.
function registration_ajax(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','email','required|is_unique[register.email]');
if($this->form_validation->run() == FALSE){
$data = '{"status":"false","message":"Email already exists"}';
}
else
{
$email=$this->input->post('email');
$data= array(
'email'=>$email
);
$last_id = $this->model->registeration($data);
if ($last_id>0) {
$this->send_email($email);
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
echo $data;
}
public function send_email($to='',$username="",$from='khadija#precisetech.com.pk')
///function send_mail()
{
$this->load->library('encrypt');
$toEmail = $this->encrypt->encode($to);
$toEmail = str_replace('/','forwardSlash',$toEmail);
$toEmail = str_replace('=','equalSign',$toEmail);
$toEmail = str_replace('+', 'plusSign', $toEmail);
$this->load->library('email');
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'sadasds';//pust mail.com.pk
$config['smtp_port'] = '25334';
$config['smtp_user'] = 'example';
$config['smtp_pass'] = 'example1';
$config['charset'] = 'utf-8';
$config['mailtype'] = 'html';
$config['validation'] = FALSE; // bool whether to validate email or not
$this->email->initialize($config);
$message = '<h1 align="center">Hellow</h1>';
$message = '<html><body style="color:#000; font-weight:normal; font-size:13/14px;"><p style="color:#000;">Hi!</p>';
$message .= '<table rules="all">';
$message .= "<p>Congratulations! You have almost completed your registration on Electronic Mall.<br><br>Click on link here to confirm your email address<br> 10.10.10.44<br><br>Thank you for joining us and becoming part of world's largest local classified sites.In our website, you can enjoy simple ad posting, easy searching and endless local listing for products.We appreciate you for choosing us in online market place.<br> Wishing you alot of success on your classified journey.Get started now!<br><br></p>";
$message .= "<p>Regards,<br>The Electronic Mall Team</p>";
$message .= "</table>";
$message .= "</body></html>";
$this->email->from($from);
$this->email->to($to);
$this->email->subject('Confirmation Email');
$this->email->message($message);
if(!$this->email->send()){
echo $this->email->print_debugger();
die();
}else{
}
}
////ajx code
//////////////////
<script>
$(document).ready(function(){
$('#registration_form').on('submit',function(e){
var email = $('#email').val();
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
/// $('#myModal').modal('hide');
$('#message_sent').html(message);
}
else{
$('#message').html(message);
}
}
});
e.preventDefault();
});
});
</script>
I want that after email is sent successfully then this message should be displayed
$data = '{"status":"true","message":"Email Created successfully"}';
When I commented the mail sending function then it display the successful message, I want that the message should be display after sending email.
have you tried returning a value from your send_email function?
if(!$this->email->send()){
return 'success';
}else{
$this->session->set_flashdata('message', 'To complete registration, click the link in email we just send you at khadija#precisetech.com.pk');
redirect('controller/login_register','refresh');
die();
}
then in your :
if ($last_id>0) {
$res = $this->send_email($email);
if($res === 'success'){
$data = '{"status":"true","message":"Email Created successfully"}';
}
}
I have created an application in AngularJS and it has an email contact form and it sends emails using PHP file in server.
Here's my Controller.js part in AngularJS:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
Here's my PHP Code:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail#gmail.com", $subject, $message, $from);
}
?>
The problem arises when I fill in the contact form and hit the Send button. I'm getting $scope.showEmailError();. But I get the email without problem.
And if I try to hit the button without filling the form still getting same $scope.showEmailError(); message.
Why don't you use model values from input? It looks like you try to use AngularJS but you still think with other frameworks in mind
In the following example I'm sending model to php script, if NAME is not filled then PHP returns 404 error and it's handled in AngularJS $http via .error handler. You don't have to add so much extra logic to success to deal with it
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
javascript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
<?php
$data = json_decode(file_get_contents("php://input"),true);
$name = $data->name;
$email = $data->email;
$sujet = $data->sujet;
$contenu = $data->contenu;
if($name && $email && $sujet && $contenu){
$destinataire = 'bercybilingualschool#gmail.com';
// Pour les champs $expediteur / $copie / $destinataire, séparer par une virgule s'il y a plusieurs adresses
$expediteur = $email;
$copie = 'sss17#gmail.com';
$copie_cachee = 'xxx#xxx.xxx';
$objet = $sujet; // Objet du message
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // l'en-tete Content-type pour le format HTML
$headers .= 'Reply-To: '.$expediteur."\n"; // Mail de reponse
$headers .= 'From: '.$name.'<'.$name.'>'."\n"; // Expediteur
$headers .= 'Delivered-to: '.$destinataire."\n"; // Destinataire
$headers .= 'Cc: '.$copie."\n"; // Copie Cc
$headers .= 'Bcc: '.$copie_cachee."\n\n"; // Copie cachée Bcc
$message = '<div style="width: 100%; text-align: justify; font-weight: bold">hello</div>';
mail($destinataire, $objet, $message, $headers);
}else{
}
?>