showing message after email generation or sending through ajax - javascript

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"}';
}
}

Related

Uncaught SyntaxError: JSON.parse: unexpected character ierror after include php file

Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data site:stackoverflow.com error is showing in firefox debug console.
I have a form in my website and on submit button this functions calls
$("#contact-form").on("submit",function(e)
{
var sendData = $(this).serialize();
e.preventDefault();
if ( checkSubmitInputs(this) )
{
$.ajax({
type: "POST",
url: "js/ajaxsubmit.php",
data: sendData,
success: function(data)
{
$("#loading-img").css("display","none");
// $(".response_msg").text(data);
// document.getElementById('contact-form').style.display = 'none'
// document.getElementById('success').style.display = 'block'
data = JSON.parse(data);
if(data.status){
document.getElementById('contact-form').style.display = 'none';
$("#error").text('');
$("#success").text(data.msg);
document.getElementById('success').style.display = 'block';
document.getElementById('scicon-c').style.display = 'block';
document.getElementById('error').style.display = 'none';
$("#contact-form").find("input[type=text], input[type=email], textarea").val("");
}
else {
document.getElementById('contact-form').style.display = '';
$("#success").text('');
$("#error").text(data.msg);
document.getElementById('error').style.display = 'block'
document.getElementById('success').style.display = 'none'
document.getElementById('scicon-c').style.display = 'none'
}
}
});
} else{
document.getElementsByClassName('error').style.display = 'block'
}
})
This line data = JSON.parse(data); shows above error as soon as i add include_once('mail.php'); in my ajaxsubmit.php file and without including it works perfectly.
Mail.php I am receiving mail too
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require_once("vendor/autoload.php");
$mail = new PHPMailer(true);
//Enable SMTP debugging.
$mail->SMTPDebug = 3;
//Set PHPMailer to use SMTP.
$mail->isSMTP();
//Set SMTP host name
$mail->Host = "email-smtp.us-west-1.amazonaws.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;
//Provide username and password
$mail->Username = "ID";
$mail->Password = "Pass";
//Set TCP port to connect to
$mail->Port = 587;
$mail->setFrom('demo#example', 'demo#example');
error_reporting(E_ALL); // Error/Exception engine, always use E_ALL
ini_set('ignore_repeated_errors', TRUE); // always use TRUE
ini_set('display_errors', true); // Error/Exception display, use FALSE only in production environment or real server. Use TRUE in development environment
ini_set('log_errors', TRUE); // Error/Exception file logging engine.
ini_set('error_log', 'zeeErrors.log'); // Logging file path
function sendEmailToUser($con, $emailMsg, $Subject)
{
global $mail;
$msg = "";
$subject = $Subject;
$tempArray = explode(',', $emailMsg);
$name = $tempArray[0];
$mobile = $tempArray[1];
$email = $tempArray[2];
$mail->Subject = "Test.";
$to = $email;
$htmlTemplate = file_get_contents('ration.html', true);
$mail->addAddress($to, $name); //Add a recipient
//$mail->addAddress('ellen#example.com'); //Name is optional
//$mail->addCC('cc#example.com');
//$mail->addBCC('varun7952#gmail.com');
$mail->isHTML(true);
$mail->Body = $msg;
//$mail->AltBody = "This is the plain text version of the email content";
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
}
?>
AjaxSubmit.php
<?php
include_once('mail.php');
$response = array();
if((isset($_POST['name'])&& $_POST['name'] !='') && (isset($_POST['email'])&& $_POST['email'] !='') && (isset($_POST['phone'])&& $_POST['phone'] !=''))
{
//whether ip is from share internet
$ia = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ia = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ia = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from remote address
else
{
$ia = $_SERVER['REMOTE_ADDR'];
}
/*Get user ip address details with geoplugin.net*/
$geopluginURL='http://www.geoplugin.net/php.gp?ip='.$ia;
$addrDetailsArr = unserialize(file_get_contents($geopluginURL));
/*Get City name by return array*/
$city = $addrDetailsArr['geoplugin_city'];
/*Get Country name by return array*/
$country = $addrDetailsArr['geoplugin_countryName'];
$region = $addrDetailsArr['geoplugin_regionName'];
if(!$city){
$city='Not Define';
}
if(!$country){
$country='Not Define';
}
if(!$region){
$region='Not Define';
}
//file_put_contents('zee1.log', print_r($addrDetailsArr, TRUE));
$yourName = $conn->real_escape_string($_POST['name']);
$yourEmail = $conn->real_escape_string($_POST['email']);
$yourPhone = $conn->real_escape_string($_POST['phone']);
$city = $conn->real_escape_string($city);
$country = $conn->real_escape_string($country);
$region = $conn->real_escape_string($region);
$checkSql = "SELECT name, email, contact from reg where email='".$yourEmail."' OR contact='".$yourPhone."'";
$resultCheck = $conn->query($checkSql);
if($resultCheck->num_rows > 0) {
$response['status'] = false;
$response['msg'] = "You have registered already with ".$yourEmail." OR ".$yourPhone."";;
}else {
$userLocation = $city.' '.$region.' '.$country;
$sql="INSERT INTO reg (name, email, contact,IP_Address,City) VALUES ('".$yourName."','".$yourEmail."', '".$yourPhone."','".$ia."','".$userLocation."')";
if(!$result = $conn->query($sql)){
$response['status'] = false;
$response['msg'] = 'There was an error running the query [' . $conn->error . ']';
}
else
{
$response['status'] = true;
$response['msg'] = "Thank you $yourName. Welcome in SAAS Application. We will connect with you soon. :)";
$msg = $yourName.','.$yourPhone.','.$yourEmail.','.$userLocation;
if(sendEmailToUser($conn,$msg,'Reg')){
//Email Sent
}
}
}
}
else
{
$response['status'] = false;
$response['msg'] = 'Please fill Name and Email';
}
echo json_encode($response);
?>
As i said everything is working if i don't add require in ajaxsubmit file. I am not good in php or JS so after reading so many answers i still can't figure out why i am not able to parse json at my form.
This is JSON Returned by AJAXsubmit
{
"status": true,
"msg": "Thank you Demo. Welcome in SAAS Application. We will connect with you soon. :)"
}
Your problem is that mail.php has this code in it:
try {
$mail->send();
echo "Message has been sent successfully";
return true;
} catch (Exception $e) {
echo "Mailer Error: " . $mail->ErrorInfo;
return false;
}
which, regardless of the result, causes text to be echo'ed. As a result, your json response will look something like:
Message has been sent successfully
{
... normal json response
}
which will not parse successfully.

How to fix error between JSON, jQuery, AJAX and PHP

I'm having problems figuring out what is wrong with my json. I used php's json_encode.So, on every page I have the some form which need be sent on each page to different email address. However, if I comment jQuery file, then the form is submitted correctly, all data inserted into database correctly, and in place of jQuery AJAX response I get valid JSON, like
{"response":"success","content":{"3":"Thanks John Doe! Your message is successfully sent to owner of property Hotel Milano!"}}
If I want to read and process this data with jQuery instead of get valid response I get just empty [] I was try a lot of options and so if I add JSON_FORCE_OBJECT instead of get empty [] I get empty {}. However if I write json data which need to encode after closing tag for if (is_array($emails) && count($emails) > 0) { just then json data it's encoded correctly and when a form is submitted I get valid response, but in this case form isn't sent and data isn't inserted into db. Bellow is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// define variables and set to empty values
$fname = $tel = $email_address_id = "";
$error = false;
$response = [];
//Load the config file
$dbHost = "localhost";
$dbUser = "secret";
$dbPassword = "secret";
$dbName = "booking";
$dbCharset = "utf8";
try {
$dsn = "mysql:host=" . $dbHost . ";dbName=" . $dbName . ";charset=" . $dbCharset;
$pdo = new PDO($dsn, $dbUser, $dbPassword);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
$response['response'] = 'error';
$response['errors'][] = $e->getMessage();
echo json_encode($response);
die();
}
use PHPMailer\PHPMailer\PHPMailer;
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';
require 'PHPMailer/Exception.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['submit'])) {
//print_r($_POST);
$fname = $_POST['fname'];
$tel = $_POST['tel'];
if (empty($fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can not be empty!';
} else {
if (!preg_match("/^[a-zšđčćžA-ZŠĐČĆŽ\s]*$/", $fname)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = 'Name can contain just letters and white space!';
}
}
if (empty($tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can not be empty!";
} else {
if (!preg_match('/^[\+]?[0-9]{9,15}$/', $tel)) {
$response['response'] = 'error';
$error = true;
$response['errors'][] = "Phone can contain from 9 to 15 numbers!";
}
}
if (!$error) {
// Instantiate a NEW email
$mail = new PHPMailer(true);
$mail->CharSet = "UTF-8";
$mail->isSMTP();
$mail->Host = 'secret.com';
$mail->SMTPAuth = true;
//$mail->SMTPDebug = 2;
$mail->Username = 'booking#secret.com';
$mail->Password = 'secret';
$mail->Port = 465; // 587
$mail->SMTPSecure = 'ssl'; // tls
$mail->WordWrap = 50;
$mail->isHTML(true);
$mail->setFrom('booking#secret.com');
$mail->clearAddresses();
$mail->Subject = "New message from secret.com";
$query = "SELECT owners_email.email_address_id, email_address, owner_name, owner_property, owner_sex, owner_type FROM booking.owners_email INNER JOIN booking.pages ON (pages.email_address_id = owners_email.email_address_id) WHERE `owner_sex`='M' AND `owner_type`='other' AND `pages_id` = ?";
$dbstmt = $pdo->prepare($query);
$dbstmt->bindParam(1, $pages_id);
$dbstmt->execute();
//var_dump($dbstmt);
$emails = $dbstmt->fetchAll(PDO::FETCH_ASSOC);
if (is_array($emails) && count($emails) > 0) {
foreach ($emails as $email) {
//var_dump($email['email_address']);
$mail->addAddress($email['email_address']);
$body = "<p>Dear {$email['owner_name']}, <br>" . "You just received a message from <a href='https://www.secret-booking.com'>secret-booking.com</a><br>The details of your message are below:</p><p><strong>From: </strong>" . ucwords($fname) . "<br><strong>Phone: </strong>" . $tel . "</p>";
$mail->Body = $body;
if ($mail->send()) {
$mail = "INSERT INTO booking.contact_owner (fname, tel, email_address_id) VALUES (:fname, :tel, :email_address_id)";
$stmt = $pdo->prepare($mail);
$stmt->execute(['fname' => $fname, 'tel' => $tel, 'email_address_id' => $email['email_address_id']]);
$response['response'] = "success";
$response['content'][$email['email_address_id']] = "Thanks " . ucwords($fname) . "! Your message is successfully sent to owner of property {$email['owner_property']}!";
}//end if mail send
else {
$response['response'] = "error";
$response['content'][$email['email_address_id']] = "Something went wrong! Try again..." . $mail->ErrorInfo;
}
}//end foreach for email addresses
} //end if for array of emails
/* If use this else for response I allways get this response. Even, if I write JSON for success hier I get it but data isn't sent and isn't inserted into db
else {
$response['response'] = 'error';
$response['error'][] = '$emails is either not an array or is empty'; // jQuery just read this
}//end if else for array of emails
*/
}//end if validation
}//end submit
echo json_encode($response);
}//end REQUEST METHOD = POST
And this is jQuery for submitHanfdler
submitHandler: function (form) {
//Your code for AJAX starts
var formData = jQuery("#contactOwner").serialize();
console.log(formData); //this work
jQuery.ajax({
url: '/classes/Form_process.class.php',
type: 'post',
data: formData,
dataType: 'json',
cache: false,
success: function (response) {
jQuery("#response").text(response['content']);
// debbuger;
console.log(response);
//console.log(response.hasOwnProperty('content'));
},
error: function (response) {
// alert("error");
jQuery("#responseOwner").text("An error occurred");
console.dir("Response: " + response);
}
}); //Code for AJAX Ends
// Clear all data after submit
var resetForm = document.getElementById('contactOwner').reset();
return false;
} //submitHandler
Thanks in advance for any kind of your help, any help will be highly appreciated!
I suspect the issue is the dataType: 'json' attribute. This is because the serialize function does not provide json data. See if this works:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: jQuery("#contactOwner").serialize()
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
Alternatively, if you want to use dataType: 'json', you will need to send in json data:
jQuery.ajax({
url: '/classes/Form_process.class.php',
method: 'POST',
data: {
firstName: jQuery("#contactOwner .first-name").val(),
lastName: jQuery("#contactOwner .last-name").val(),
...
}
dataType: 'json',
cache: false,
}).done(function (response) {
console.log(response);
}).fail(function (error) {
console.log(error);
});
If you add you data using an object as shown above this should work with dataType: 'json'.

Throw PHP variable back to Ajax on submit form data

Okay so I have an ajax function which sends data to register-process.php. I want the register-process.php to send the PHP value $msg back to ajax. I tried using $('.message').html("<?php $msg; ?>").fadeIn(500); on success but it does not seems to work. Is there any way to do it?
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var cpass = $("#cpass").val();
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
email: $("#email").val(),
cpass: $("#cpass").val()
};
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
$('.message').html("<?php $msg; ?>").fadeIn(500);
}
});
return false;
});
});
</script>
register-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
$cpass = (!empty($_POST['cpass']))?$_POST['cpass']:null;
$email = (!empty($_POST['email']))?$_POST['email']:null;
if($_POST){
$stmt = "SELECT COUNT(*) FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> execute();
$checkunm = $stmt->fetchColumn();
$stmt = "SELECT COUNT(*) FROM members WHERE mem_email = :email";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':email', $email);
$stmt->execute();
$checkeml = $stmt->fetchColumn();
if($uname == '' or $pass == '' or $cpass == '' or $email == ''){
$msg = "<div class='message-error'>Fields cannot be left empty. Please fill up all the fields.</div>";
}else if($checkunm > 0){
$msg = "<div class='message-error'>This username is already registered. Please use a different username.</div>";
}else if($checkeml > 0){
$msg = "<div class='message-error'>This Email ID is already registered. Please use a different Email ID.</div>";
}else if($pass != $cpass){
$msg = "<div class='message-error'>Passwords are not matching.</div>";
}else if(strlen($uname) > 12){
$msg = "<div class='message-error'>Username should not be more than 12 characters long.</div>";
}else if(strlen($uname) < 6){
$msg = "<div class='message-error'>Username must be at least 6 characters long.</div>";
}else if(strlen($pass) < 6){
$msg = "<div class='message-error'>Password must be at least 6 characters long.</div>";
}else{
// If everything is ok, insert user into the database
$stmt = "INSERT INTO members(mem_uname, mem_pass, mem_email)VALUES(:uname, :pass, :email)";
$stmt = $pdo->prepare($stmt);
$stmt-> bindValue(':uname', $uname);
$stmt-> bindValue(':pass', password_hash($pass, PASSWORD_BCRYPT));
$stmt-> bindValue(':email', $email);
$stmt-> execute();
if($meq){
$msg = "<div class='message-success'>Congratulations! You have been registered successfully. You can now login!</div>";
}else{
$msg = "<div class='message-error'>Server Error! Please try again later. If problem persists, please contact support.</div>";
}
}
}
echo $msg;
?>
In your Ajax function no need to echo the php variable.Just map response to your html element like below:
$.ajax({
type: "POST",
url: "register-process.php",
data: dataString,
cache: true,
success: function(html){
console.log(html);//see output on browser console
$('.message').html(html).fadeIn(500);
}
});

If statement not working in javascript/ajax

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

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.

Categories

Resources