contact form jquery php phonegap - success issue - php

i try to create a contact form in jquery php 4 phonegap, my problem how can i have response success from php? or if i can try other solutions but havent ideas 4 for the moment ^^
thx a lot
p.s. the form works (if i delete response success form js)
index.js
$(document).on('pageinit', function() {
$('#send').click(function() {
var url = 'send02.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form02');
$('.required', $contactform).each(function(i) {
if($(this).val() === '') {
error++;
}
});
// each
if(error > 0) {
alert('Inserisci tutti i campi obbligatori segnati con asterisco*.');
} else {
var email = $contactform.find('input[name="email"]').val();
var datetime = $contactform.find('input[name="datetime"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var selectnative4 = $contactform.find('select[name="selectnative4"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type : "POST",
url : url,
data : {
email : email,
datetime : datetime,
mobilephone : mobilephone,
selectnative4 : selectnative4,
message : message
},
success : function(data) {
if(data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Impossibile inviare il messaggio. Per piacere riprova.');
}
}
});
//$.ajax
}
return false;
});
});
and send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["email"])) {
$email = strip_tags($_GET['email']);
$datetime = strip_tags($_GET['datetime']);
$mobilephone = strip_tags($_GET['mobilephone']);
$selectnative4 = strip_tags($_GET['selectnative4']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#facebook.com';
$subject = 'Prenotazione Online';
$mailbody = "
Nominativo: $email
Telefono: $mobilephone
data prenotazione: $datetime
Scelta dal Menù: $selectnative4
Messaggio: $message
in data: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>

Related

Web page message [object object]

I'm using a framework called Ispinia to do a simple system for my Company, and when I try to submit anyting give this error:
Web page message [object object].
I'm using IE11.
Thanks in advance!
CODE: Controller.js
function vila_do_conde_ctrl($scope, $http, SweetAlert){
$scope.dataInicio = new Date();
$scope.dataFim = new Date();
$scope.teste = function(){
alert($scope.myDate);
}
$scope.preencheEmbarques = function(){
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_embarques.php?oi="+$scope.oi)
.then(function (response) {$scope.embarques=response.data.records;$scope.emb = ""; $scope.dataChegada = ""; $scope.dataSaida = ""; $scope.dataDesova = ""; $scope.tipoCarga = ""; if($scope.ctn) $scope.ctn = ""; $scope.fornecedor = ""; $scope.servicoAdd = ""; $scope.qte = ""; $scope.unidade = ""; $scope.dataInicio = ""; $scope.dataFim = ""; $scope.obs = ""; $scope.servicos = ""; }, function (response){alert(response);});
};
$scope.buscaServicos = function(){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_servicos.php?emb="+embarque)
.then(function (response) {
$scope.servicos=response.data.records;
for(var i=0; i<$scope.servicos.length; i++){
var dataAux = $scope.servicos[i].DataInicio.split("-");
$scope.servicos[i].DataInicio = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
dataAux = $scope.servicos[i].DataFim.split("-");
$scope.servicos[i].DataFim = dataAux[2]+"/"+dataAux[1]+"/"+dataAux[0];
}
}, function (response){alert(response);});
};
$scope.preencheDados = function(){
if($scope.emb){
var embarque = encodeURIComponent($scope.emb.trim());
$http.get("http://127.0.0.1/DIARIODEBORDO/php/preenche_dados.php?emb="+embarque)
.then(function (response) {
$scope.dados=response.data.records[0];
if($scope.dados.DtChegada){
$scope.dataAux=$scope.dados.DtChegada.split("-");
$scope.dataChegada=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtSaida){
$scope.dataAux=$scope.dados.DtSaida.split("-");
$scope.dataSaida=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
if($scope.dados.DtDesova){
$scope.dataAux=$scope.dados.DtDesova.split("-");
$scope.dataDesova=$scope.dataAux[2]+"/"+$scope.dataAux[1]+"/"+$scope.dataAux[0];
}
$scope.tipoCarga=$scope.dados.TipoCarga;
$scope.ctn=$scope.dados.Container;
$scope.buscaServicos();
}, function(response){alert(response);});
}
};
$scope.adicionarServico = function(){
if($scope.oi && $scope.emb && $scope.fornecedor && $scope.servicoAdd && $scope.qte && $scope.unidade && $scope.dataInicio && $scope.dataFim){
var embarque = encodeURIComponent($scope.emb.trim());
var fornecedor = encodeURIComponent($scope.fornecedor.trim());
var servico = encodeURIComponent($scope.servicoAdd.trim());
var quantidade = encodeURIComponent($scope.qte);
var unidade = encodeURIComponent($scope.unidade.trim());
var data_inicio = encodeURIComponent($scope.dataInicio.getFullYear()+"-"+ ($scope.dataInicio.getMonth() + 1) +"-"+$scope.dataInicio.getDate());
var data_fim = encodeURIComponent($scope.dataFim.getFullYear()+"-"+ ($scope.dataFim.getMonth() + 1) +"-"+$scope.dataFim.getDate());
var obs = "";
if($scope.obs)
obs = encodeURIComponent($scope.obs);
var container = ""
if($scope.tipoCarga){
if($scope.ctn)
container = encodeURIComponent($scope.ctn);
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_tipo_carga.php?oi="+$scope.oi+"&emb="+embarque+"&ctn="+container)
.then(function (response) {}, function (response){alert(response);});
}
$http.get("http://127.0.0.1/DIARIODEBORDO/php/adicionar_servico.php?oi="+$scope.oi+"&emb="+embarque+"&forn="+fornecedor+"&servico="+servico+"&qte="+quantidade+"&unidade="+unidade+"&dtInicio="+data_inicio+"&dtFim="+data_fim+"&obs="+obs)
.then(function (response) {
SweetAlert.swal({
title: "Serviço adicionado!",
//text: "You clicked the button!",
type: "success"
});
$scope.buscaServicos();}, function (response){alert(response);});
}
else
alert("Preencha todos os campos!");
};
MODEL:
<?php
$oi = $_GET['oi'];
$emb = $_GET['emb'];
$fornecedor = $_GET['forn'];
$servico = $_GET['servico'];
$quantidade = $_GET['qte'];
$unidade = $_GET['unidade'];
$data_inicio = $_GET['dtInicio'];
$data_fim = $_GET['dtFim'];
$obs = $_GET['obs'];
// Create connection
$conn = new mysqli($host, $usuario, $senha, $base_de_Dados);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($obs != "")
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM, OBSERVACOES) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."','".$obs."')";
else
$sql = "INSERT INTO diario_bordo.servicos (OI, EMBARQUE, FORN_SERVICO, SERVICO, QUANTIDADE, UNIDADE, DATA_INICIO, DATA_FIM) VALUES ('".$oi."','".$emb."','".$fornecedor."','".$servico."',".$quantidade.",'".$unidade."','".$data_inicio."','".$data_fim."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
[object Object] is the way JavaScript outputs an object. Not sure what the purpose of your script is, but you can show the sub-object by using objectname.key.
e.g. if 'person' is an object containing name and mail address, you can access the sub-objects (probably strings in this example) by calling person.name and person.mailaddress.
I think you should now go through your code again and have a look at all alert messages.

error in ajax response if condition error

I want to show error ie. Email already exists in database. If not show Thank you message.
I'm using ajax and jquery for this. Here is my code:
Ajax jquery:
<script type="text/javascript" >
$(function() {
var val_holder;
$("#subscribe").click(function() {
val_holder = 0;
var subscribe_mail = jQuery.trim($("#subscribe_mail").val()); // email field
var email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(subscribe_mail == "") {
$(".error_message").html("This field is empty.");
val_holder = 1;
}
if(subscribe_mail != "") {
if(!email_regex.test(subscribe_mail)){ // if invalid email
$(".error_message").html("Your email is invalid.");
val_holder = 1;
}
}
if(val_holder == 1) {
return false;
}
val_holder = 0;
var dataString = '&subscribe_mail=' + subscribe_mail;
$.ajax({
type: "POST",
url: "ajax_subscribe.php",
data: dataString,
datatype: "json",
success: function(response) {
console.log(response);
if(response!= '')
{
$('.error_message').html(subscribe_mail + ' is already Exists.');
return true;
} else {
$('.error_message').html('Thanks For subscription!');
return false;
}
}
});
$("#subscribe_form")[0].reset();
return false;
});
});
And php file code is:
<?php error_reporting('E_ALL ^ E_NOTICE'); include('config.php');if($_POST) { $subscribe_mail = $_POST['subscribe_mail'];
$date = date('Y-m-d');
$q = mysql_query("select * from signups where signup_email_address='".$subscribe_mail."' ") or die(mysql_error());
$n = mysql_fetch_row($q);
if( $n>0 )
{
echo 'Already Exists';
}
else
{
$insert = mysql_query("insert into signups(signup_email_address,signup_date) values('$subscribe_mail','$date')") or die(mysql_error());
$from = 'sunshine.kapoor270#gmail.com';
$to = $subscribe_mail;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= "From: " . $from . "\r\n"; // Sender's E-mail
$headers .= "Reply-to: " . $from . "\r\n";
$headers .= "Return-Path: $from\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$subject = "Thanks for Subscription";
$message = "Subscription email id : ".$subscribe_mail." ";
$sentmail = mail($to,$subject,$message,$headers);
$sentmail = mail($from,$subject,$message,$headers);
} } ?>
Only
if(response!= ''){$('.error_message').html(subscribe_mail + ' is already Exists.'); return true; }
this condition is working. its not going to else part if response is blank.
It depends on what you send back in your response when the user does not exist in database.
You can change the condition to:
if (!$.trim(response)){......
if the response is null or empty.
You should maybe delete your final ?> in your PHP-files because you can omit this. Those and the lines after the closing PHP-Tag are responsible for additional empty-chars/enters which make calinaadi´s answer a good one.
And you should check your includes for the same behaviour.
I would never check on nothing or empty strings and thatwhy reverse your if:
if(str.trim(response) == 'Already Exists') {
$('.error_message').html('Thanks For subscription!');
return false;
} elseif(str.trim(response) == 'New User') {
return true;
} else {
$('.error_message').html(subscribe_mail + ' is some strange unknown Stringoutput.');
return false;
}

Ajax display response in blank page

After submitting a form with ajax the returned result appears on a new page. The chrome console returns me an error in almost every element: it is not a function validates, but php insert them and shows the result displayed in this new page.
$(document).ready(function () {
$('#newsletter').submit(function(e){
var $this = $(this);
e.preventDefault();
$response = $('#response'),
$mail = $('#email'),
testmail = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
hasError = false;
$response.find('p').remove();
if (!testmail.test($mail.val())) {
$response.html('<p class="error">Please enter a valid email</p>');
hasError = true;
}
if (hasError === false) {
$response.find('p').remove();
$response.addClass('loading');
$.ajax({
type: "POST",
dataType: 'json',
cache: false,
url: $this.attr('action'),
data: $this.serialize()
}).done(function (data) {
console.log(data);
$response.removeClass('loading');
$response.html('<p>'+data.message+'</p>');
}).fail(function() {
$response.removeClass('loading');
$response.html('<p>An error occurred, please try again</p>');
})
}
return false;
});
});
php code
<?php
$host = "";
$dbname = "";
$user = "";
$pass = "";
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$datetime = date('Y-m-d H:i:s');
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
The error displayed: undefinied is not a function in
$response = $('#response'),
$mail = $('#email'),
var $this = $(this);
Message displayed in blank page:
{"status":"success","message":"You have been successfully subscribed"}
Solved. Now works fine in another way, but I would like to know the mistake.
This works
(function ($, window, document, undefined) {
'use strict';
var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
var formData = {
'news' : $('input[name="news"]').val(),
'email' : $('input[name="email"]').val(),
};
$.ajax({
type : 'POST',
url : 'news.php',
data : formData,
dataType : 'json',
encode : true
}).done(function (data) {
if (!data.success) {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
} else {
$('#response').html(data);
$response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
}
}).fail(function (data) {
response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));

Why is my php email script sending an email to my spam not in my inbox

Here is my php code below. When I click "send email" button it works fine. But it doesn't appear to my Inbox. It was routed to Spam folder:
<?php
function sendmail(){
$message = $_POST['message'];
$email = $_POST['email'];
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$to = 'mpylla#gmail.com';
$subject = 'From :'.$email;
$message1 = 'From: '.$name."\nEmail: ".$email."\nMessage: ".$message;
mail($to, $subject, $message1);
}
sendmail();
?>
and this ajax script is in my HTML code:
$("#submit").click(function(e) {
var name = $("#name").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var message = $("#message").text();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (!emailReg.test(email)) {
alert('Ju lutem shkruan nje e-mail valide');
return false;
}
if (email.length == 0) {
alert("Email duhet te shenohet");
return false;
}
if (name.length == 0) {
alert("Emri duhet te shenohet");
return false;
}
if (lastname.length == 0) {
alert("Mbiemri duhet te shenohet");
return false;
}
if (message.length == 5) {
alert("Mesazhi duhet te shenohet");
return false;
} else {
$.ajax({
type: "POST",
url: "mail.php",
data: $("#myform").serialize(),
success: function(response) {
$("#sukses").fadeIn('slow');
setTimeout(function() {
$("#sukses").fadeOut('slow');
document.getElementById('myform').reset();
}, 100);
clearInterval();
}
});
}
e.preventDefault();
e.stopPropagation();
});
This is usually down to the content of the email itself and the type of mailbox you are sending the email to.
Each have various spam filters in place to restrict malicious emails. Take a look at this for some tips to help you.

Issues with AJAX grabbing and saving records

I am working on a form to database save/grab using ajax/jquery. I am having issues saving and grabbing though. My ajax keeps failing and I can't tell why. I know this should work. I movedmy ajaxCall to its own function to call it on load and on submit and that is when things seemed to go south. Can someone point me in the right direction on what is wrong. I have my jquery and php below.
JQUERY/AJAX CODE
$(document).ready(function() {
ajaxCall();
$('#submitBtn').on('click',function(event) {
var formData = $('form').serialize();
event.preventDefault();
ajaxCall(formData);
}); //END OF .ON
function ajaxCall(formData) {
$.ajax({
url: "php/save.php",
type: "POST",
dataType: "json",
//dataType: "string",
data: formData,
async: true,
success: successCall,
error: errorCall
});
} //END OF AJAX CALL FUNCTION
function errorCall() {
alert("There was an error with this request!")
}// END OF ERROR CALL FUNCTION
function successCall(data) {
//var records = $.parseJSON();
var record = "";
console.log(data);
/*$.each(data, function() {
ID = this['ID'];
NAME = this['NAME'];
PHONE = this['PHONE'];
ADDRESS = this['ADDRESS'];
var html = "<tr><td>" + ID + "</td><td>" + NAME + "</td><td>" + PHONE + "</td><td>" + ADDRESS + "</td></tr>";
$(html).appendTo("table");
});*/
//var jsonObject = $.parseJSON(data);
//alert("ajax call complete");
} //END OF SUCCESS CALL FUNCTION
}); //END OF .READY
PHP CODE
class dbClass {
private $host = "localhost";
private $username = "root";
private $password = "";
private $schema = "formtest";
public $dbCon;
function __construct() {
$this->dbCon = new mysqli($this->host,$this->username,$this->password,$this->schema);
if ($this->dbCon->connect_error) {
die("Issue Connecting: " . $dbCon->connect_errorno . "Error: " . $dbCon->connect_error);
}
//var_dump($dbCon);
}
function saveDBRecord($dbName, $dbPhone, $dbAddress) {
//HOW TO FIGURE THIS OUT
$query = $this->dbCon->prepare("INSERT INTO contact (contact_name,contact_phone,contact_address) VALUES (?,?,?)");
$query->bind_param("sss",$dbName,$dbPhone,$dbAddress);
//var_dump($query);
$query->Execute();
$recordData = $this->grabRecords();
return $recordData;
}
function grabRecords() {
$query = $this->dbCon->query("SELECT * FROM contact;");
//var_dump($query);
$data = array();
$counter = 0;
$i = 0;
while($row = $query->fetch_row())
{
$record = array(
"ID" => $row[0],
"NAME" => $row[1],
"PHONE" => $row[2],
"ADDRESS" => $row[3]
);
$data[] = $record;
//$data[$i++] = "ID: {$row[0]} NAME: {$row[1]} PHONE: {$row[2]} ADDRESS: $row[3]";
//$data .= "ID: {$row[0]} NAME: {$row[1]} PHONE: {$row[2]} ADDRESS: $row[3]";
//$counter .= $counter;//var_dump($data);
//$assoc = $query->fetch_all();
//var_dump($assoc);
//return $assoc;
}
//var_dump($data);
return $data;
}
function __destruct() {
$this->dbCon->close();
}
} //END OF dbClass
$dbClassConnection = new dbClass();
/*function displayRecords($recordData) {
//var_dump($recordData[0]);
}*/
//$name = $_POST['name'];
//$phone = $_POST['phone'];
//$address = $_POST['address'];
//$name = "AutoInput";
//$phone = "AutoInput";
//$address = "AutoInput";
//var_dump($dbClassConnection);
if ($_POST['name'] == "" || $_POST['phone'] == "" || $_POST['address'] == "") {
$recordData = $dbClassConnection->grabRecords()
echo json_encode($recordData);
//echo json_encode("HELLO");
//$recordData = $dbClassConnection->grabRecords();
//echo json_encode("FIRST IF");
//var_dump($recordData);
} else {
$name = $_POST['name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$recordData = $dbClassConnection->saveDBRecord($name,$phone,$address);
//$jsonData = displayRecords($recordData);
//var_dump(json_encode($recordData);
echo json_encode($recordData);
//var_dump($jsonData);
//echo json_encode("SECOND IF");
//var_dump($recordData);
}
//$name = $_POST['name'];
//ar_dump($name;
//echo json_encode($_POST);
//IF SUBMIT TRUE
//saveDBRecord and grabRecords
//ELSE
//JUST GrabRecords
?>
The issue was that the ajaxCall onLoad needed to serialize the formData as well and then the issue was with how I was handling the POST data for the IF statements.

Categories