How empty input value when success submit in jquery - php

I want to clear the input values when the form is submitted correctly, But there is a problem, if not inserted, the inputs are erased.
I will be grateful for help me.
This is my code:
$(document).ready(function(){
$("#Insert").click(function(){
var email = $("#email").val();
var title = $("title").val();
var text = $("text").val();
var cSend = true;
$.post("ajax.php",{email:email,title:title,text:text,cSend:cSend},function(data){
$("#contactResualt").html(data);
});
});
});
//ajax.php
if(isset($_POST['cSend'])){
if (empty($_POST['email']) || empty($_POST['title']) || empty($_POST['text'])){
echo '<div class="alert alert-warning">Fill empty fields</div>';
}
else{
$email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
if($resualt){
echo '<div class="alert alert-success">Insertion was successful</div>';
}
else{
echo '<div class="alert alert-warning">Insertion failed</div>';
}
}
}
So, I just want the information to be correctly inserted, Inputs will be cleared.

If you only want to erase the fields when the insert was successful, you can put an indicator attribute into the response HTML:
if($resualt) {
echo '<div class="alert alert-success" data-success="true">Insertion was successful</div>';
}
else {
echo '<div class="alert alert-warning" data-success="false">Insertion failed</div>';
}
Then use the indicator in the AJAX callback to determine whether you should reset the form:
$.post("ajax.php", {
email: email,
title: title,
text: text,
cSend: cSend
}, function(data) {
$("#contactResualt").html(data);
if($("#contactResualt [data-success]").attr("data-success") === "true") {
$("#email, #title, #text").val("");
}
});

You can clear the input field by using $('input').val('');
$(document).ready(function(){
$("#Insert").click(function(){
var email = $("#email").val();
var title = $("title").val();
var text = $("text").val();
var cSend = true;
$.post("ajax.php",
{email:email,title:title,text:text,cSend:cSend},function(data){
var json_obj = $.parseJSON(data);//parse JSON
$("#contactResualt").html(json_obj.msg);
if(json_obj.status){
$('input').val('');
}
});
});
});
Ajax.php
if(isset($_POST['cSend'])){
if (empty($_POST['email']) || empty($_POST['title']) ||
empty($_POST['text'])){
$result['status'] = false;
$result['msg'] = '<div class="alert alert-warning">Fill empty
fields</div>';
}
else{
$email = $_POST['email'];
$title = $_POST['title'];
$text = $_POST['text'];
$Contactus = new Contactus();
$resualt = $Contactus->SendPM($email,$title,$text);
if($resualt){
$result['status'] = true;
$result['msg'] = '<div class="alert alert-success">Insertion was successful</div>';
}
else{
$result['status'] = false;
$result['msg'] = '<div class="alert alert-warning">Insertion failed</div>';
}
}
echo json_encode($result);
}

Related

ajax login success data but not redirect to index page

i want to validate login form using ajax success response is working but if all goods it should be redirect to index page but it's not working , i don't understand what's wrong please help. thanks in advance..
$(document).ready(function(){
var response;
$('#submit').click(function(e){
e.preventDefault();
$('.alert-box').html('<div id="loading" style="margin: 0 auto;" >
</div>');
var action = 'ajax_validation';
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url:"do_login.php",
method:"POST",
data:{action:action, username:username, password:password},
success:function(data){
response = data;
if(response === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
});
});
});
above these ajax request
this is action page code
include('includes/db.php');
if(isset($_POST["action"])){
$check_username = $_POST['username'];
$check_password = $_POST['password'];
if(empty($check_username) && empty($check_password)){
echo "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
die("QUERY FAILED".mysqli_error($select_query));
}
if(mysqli_num_rows($select_query)==0){
echo "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
echo $row['email'];
}
}
}
}
In your resposne you are echoing
echo $row['email'];
This should be:
echo 1;
Your problem is that you are checking if value is 1 in ajax:
success:function(data){
response = data;
if(response === 1){ //<- there you are checking if your echo is 1 but you are trying to echo $row['email'];
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response);
}
}
change your echo from $row['email'] to 1
I think that the problem is response checking condition in ajax success.
You're checking if a string (email or error message) is equal and the same type of 1.
...
dataType: 'json',
success:function(data){
response = data;
if(response === 1){
...
You can use a json response with status/error code:
...
success:function(data){
response = JSON.parse(data);
if(response.status === 1){
window.location.href = "http://stackoverflow.com";
}else{
$('.alert-box').addClass("alert alert-warning");
$('.alert-box').html(response.data);
}
}
...
$check_username = $_POST['username'];
$check_password = $_POST['password'];
$res = array('status'=> 0, 'data' => '');
if(empty($check_username) && empty($check_password)){
$res['status'] = 0;
$res['data'] = "Please fill all field";
}else{
$query = "SELECT * FROM user WHERE email = '{$check_username}' AND password = '{$check_password}' ";
$select_query=mysqli_query($connection,$query);
if(!$select_query){
$res['status'] = 0;
$res['data'] = "QUERY FAILED".mysqli_error($select_query);
echo json_encode($res);
return;
}
if(mysqli_num_rows($select_query)==0){
$res['status'] = 0;
$res['data'] = "Username or password are incorrect!";
}else{
while ($row=mysqli_fetch_assoc($select_query)) {
$_SESSION['username'] = $row['email'];
$res['status'] = 1;
$res['data'] = "".$row['email'];
}
}
}
echo json_encode($res);
In addition i suggest to put only the username in query where condition and check if the password match with php.

Open cart send mail from model

I am using Opencart V2.0.1.1 for one project and i have a custom form in product page(.tpl). I want to send mail to store owner on submit of that form. I am able to process it and receiving the data till model but from model i am not able to send the mail and i am getting below error.
SyntaxError: Unexpected token < OK Notice: Undefined property:
Mail::$ErrorInfo in
/opt/lampp/htdocs/dutees/catalog/model/catalog/product.php on
line 784{"success":"success"}
Below is my code
// CONTROLLER FUNCTION
public function getquote()
{
$data = array(); $json = array();
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
}
if (isset($this->request->post['mobile'])) {
$data['mobile'] = $this->request->post['mobile'];
}
if (isset($this->request->post['address'])) {
$data['address'] = $this->request->post['address'];
}
if (isset($this->request->post['description'])) {
$data['description'] = $this->request->post['description'];
}
if($this->config->get('config_email') != 'null' || $this->config->get('config_email') !='')
$data['store_email'] = $this->config->get('config_email');
if($this->config->get('config_name') != 'null' || $this->config->get('config_name') !='')
$data['store_name'] = $this->config->get('config_name');
$this->load->model('catalog/product');
$gq_status = $this->model_catalog_product->sendQuote($data);
if($gq_status = "success"){
$json['success'] = "success";
}else{
$json['error'] = "Error : We are unable to send your request now, please use contact-us form";
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
// MODEL FUNTION
public function sendQuote($data = array()) {
$status = ""; $name ="";$email ="";$mobile ="";$address ="";$description ="";
if(isset($data['name']))
$name = $data['name'];
else
$name = "Not Available";
if(isset($data['email']))
$email = $data['email'];
else
$email = "Not Available";
if(isset($data['mobile']))
$mobile = $data['mobile'];
else
$mobile = "Not Available";
if(isset($data['address']))
$address = $data['address'];
else
$address = "Not Available";
if(isset($data['description']))
$description = $data['description'];
else
$description = "Not Available";
if(isset($data['store_email']))
$store_email = $data['store_email'];
else
$store_email = "abc#def.net";
if(isset($data['store_name']))
$store_name = $data['store_name'];
else
$store_name = "Enquiry";
$message = '
<html>
<body>
<MY HTML MAIL CONTENT GOES HERE>
</body>
</html>
';
$this->load->mail;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($store_email);
$mail->setFrom($email);
$mail->setSender($store_name);
$mail->setSubject("Product Get Quote");
//$mail->setText("test message body text");
$mail->setHtml($message);
if(!$mail->send()) {
$status = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$status = 'success';
}
return $status;
}
// VIEW AJAX
<script>
$('#gq-submit').click(function(){
var name=$('#gq-name').val();
var email=$('#gq-email').val();
var mobile=$('#gq-mobile').val();
var address=$('#gq-address').val();
var description=$('#gq-description').val();
if(name != '' && email != ''&& mobile != '' && description != ''){
$.ajax({
type:'post',
url:'index.php?route=product/product/getquote',
dataType: 'json',
data:'name='+name+'&email='+email+'&mobile='+mobile+'&address='+address+'&description='+description,
beforeSend: function() {
$('#gq-submit').button('loading');
},
complete: function() {
$('#gq-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#gq-showcheck').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});}else{
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + "Please fill all the fields" + '</div>');
}
});
</script>
You can't send mail, maybe the mail settings are incorrect and
the Opencart own Mail class hasn't any ErrorInfo field inside it.
See: system/library/mail.php
First of all set the the correct mail parameters and don't use $mail->ErrorInfo because it doesn't exist. When error occured during sending mail it calls a trigger_error.

Php ajax just want to display error message only form submit

After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});

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));

Manually sending a post in PHP

I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));

Categories