I'm having an issue with an contact form everything works except it will not show the success message after the form is added to the db.
The process script
$post = (!empty($_POST)) ? true : false;
if($post)
{
include 'db.php';
include 'functions.php';
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$phone = stripslashes($_POST['phone']);
$device = stripslashes($_POST['device']);
$model = stripslashes($_POST['model']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
{
$error .= 'Please enter your name.<br />';
}
// Check email
if(!$email)
{
$error .= 'Please enter an e-mail address.<br />';
}
if($email && !ValidateEmail($email))
{
$error .= 'Please enter a valid e-mail address.<br />';
}
// Check phone number
if(!$phone)
{
$error .= 'Please enter your phone number.<br />';
}
// Check device
if(!$device)
{
$error .= 'Please enter your device manufacturer.<br />';
}
// Check device model
if(!$model)
{
$error .= 'Please enter your device model.<br />';
}
// Check message (length)
if(!$message || strlen($message) < 15)
{
$error .= "Please enter your message. It should have at least 15 characters.<br />";
}
// Get current time stampe
$date = time();
if(!$error)
{
$addDB = "INSERT INTO contactus (`name`,`email`,`phone`,`device`,`model`,`subject`,`message`, `date`, `read`) VALUES ('$name','$email','$phone','$device','$model','$subject','$message','$date', '')";
$result = mysqli_query($con,$addDB) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR);
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.'</div>';
}
}
And here is the jQuery part
<script type="text/javascript">
$(document).ready(function ()
{ // after loading the DOM
$("#ajax-contacts").submit(function ()
{
// this points to our form
var str = $(this).serialize(); // Serialize the data for the POST-request
$.ajax(
{
type: "POST",
url: 'includes/contact-process.php',
data: str,
success: function (msg)
{
$("#note").ajaxComplete(function (event, request, settings)
{
if (msg == 'OK')
{
result = '<div class="notification_ok">Your message has been sent. Thank you!</div>';
$("#fields").hide();
}
else
{
result = msg;
}
$(this).html(result);
});
}
});
return false;
});
});
</script>
Thanks any help is gladly appreciated.
Drop this line:
$("#note").ajaxComplete(function (event, request, settings)
You don't need it as you are already in the success: function.
For debugging purpose you can try to put in an alert("Test"); just above that troublesome line to check if it is displayed.
Note that the success callbacks have been deprecated and you should instead use .done. See the jQuery API for more info:
You could also try and do some debugging yourself. E.g. Chrome has some really good developer tools where you can see a lot of stuff and you can even setup breakpoints and walk through your code step-by-step. Very useful.
Hit F12 to show Developer Tools.
Go in to Settings:
Enable logging of XHR/Ajax requests:
When doing Ajax requests hereafter it will be logged in the console:
Just rightclick on that Ajax request to trigger a new identical request. In this way you can see exactly what the browser sends and what your PHP script receives. Of course the request needs to be GET for you to debug the variables being passed.
Related
I tried questions showing up before asking a question didnt have chance to make it work.
it works fine when I add it to mail send success alert, But I dont want to add script in php part.
I am trying to redirect contact page to an another page after form
success and delay a few seconds.
Here is my Jquery ajax :
$(document).ready(function(){
$('#ContactForm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"modules/contact.inc.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
setTimeout(function() {
window.location = 'index.php';
}, 1000);
} else {
$('#result').html(data.error);
$('#ContactForm')[0].reset();
}
}
});
});
});
I tried the folowing setTimeout(); in success function but didnt work:
setTimeout(function() {
window.location.replace("index.php");
},1000);
Then I tried : window.location.replace("index.php"); without setTimeout function didnt work too.
window.location.href
window.location.hostname
window.location
This one works for modal in another page
setTimeout(function() {
window.location.reload();
}, 3000);
These are my tries didnt have a chance, Thanks for any advice and help.
EDIT: Here is php part for data.error contain:
$error = "";
// Validate user name
if(empty($_POST["fname"])){
$error .= "<p class='error'>İsim girmediniz.</p>";
} else {
$name = test_input($_POST["fname"]);
}
// Validate email address
if(empty($_POST["email"])){
$error .= "<p class='error'>E-Posta girmediniz.</p>";
} else{
$email = $_POST["email"];
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error .= "<p class='error'>E-Posta doğru formatta değil.</p>";
}
}
// Validate user subject
if(empty($_POST["subject"])){
$error .= "<p class='error'>Konu girmediniz.</p>";
} else {
$subject = test_input($_POST["subject"]);
}
// Validate user message
if(empty($_POST["message"])){
$error .= "<p class='error'>Mesaj girmediniz.</p>";
} else {
$message = test_input($_POST["message"]);
}
// Validate user departman
if(empty($_POST["departmant"])){
$error .= "<p class='error'>departman Seçin.</p>";
} else {
$departman = test_input($_POST["departmant"]);
}
if($error === ''){
require "../PHPMailer/mailer.php";
$mail = new mailSend();
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$name = test_input($_POST["fname"]);
$subject = test_input($_POST["subject"]);
$departman = test_input($_POST["departmant"]);
$message = test_input($_POST["message"]);
$error = $mail->sendMail($email,$name,$subject,$departman,$message);
}else{
$error .= "<p class='error'>Formda bir hata oluştu.</p>";
}
$data = array(
'error' => $error
);
echo json_encode($data);
EDIT : Got it work thanks for answers,
Displaying error causing the problem, $('#result').html(data.error); I changed it to text message instead of success message from php:
$('#result').html('Form successfuly');
$('#ContactForm')[0].reset();
setTimeout(function() {
window.location = 'index.php';
}, 1000);
it works fine.
String.replace() requires two parameters. As written, it will look for the string "index.php" and replace it with nothing. Try adding a regex to match everything and replace with your new URL.
setTimeout(function() {
window.location.replace( /.*/, "index.php");
},1000);
Use the full URL (i.e. https://yourdomain.com/index.php) or write a better regex. For instance, if your domain ends with .com, you could do something like:
setTimeout(function() {
window.location.replace( /\.com\/.*/, ".com/index.php");
},1000);
My code is working well but problem in output. I don't get exact output that i want.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
console.log(data);
},
error:function(){
console.log("Error: Unknown Error");
}
});
});
PHP code:
<?php
if(isset($_SESSION['userId'])) {
echo "1";
} else {
echo "0";
}
?>
output in success gives also html code, why?
0 </div>
<footer class="nav navbar-inverse">
...........
</footer>
</body>
</html>
I want in my output only 0 in a variable, not html code.
The problem is with your php code here's an example php code. You need to encode as JSON this lets jQuery .success or .fail have a JSON response as a callback.
What I am doing is I have a php file and a js file.
PHP
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$msg = $_POST['message'];
$nospace_name = trim($_POST['name']);
$nospace_email = trim($_POST['email']);
$nospace_message = trim($_POST['message']);
if (empty($nospace_name))
$errors['name'] = "Name field is required.";
if (empty($nospace_email))
$errors['email'] = "Email field is required.";
if (empty($nospace_message))
$errors['message'] = "I would love to see your message.";
if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
$errors['bad_email'] = "Please enter a valid email address";
// if there are any errors in our errors array, return a success boolean of false
if (!empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// if there are no errors process our form, then return a message
// prepare message to be sent
$to = "me#example.com";
$subject = "Website Contact Form: ".$name;
// build the message
$message = "Name: ".$name."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Message: ".$msg;
// send it
$mailSent = mail($to, $subject, $message, $headers);
// check if mail was sent successfully
if (!$mailSent) {
$errors['unknown_error'] = "Something went wrong...Please try again later";
$data['success'] = false;
$data['errors'] = $errors;
}
else {
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
}
}
// return all our data to an AJAX call
echo json_encode($data);
?>
JS
$(function() {
$("#contactForm").submit(function(e) {
$.ajax({
type: 'POST',
url: 'contact.php',
data: $(this).serialize(),
dataType: "json"
})
.done(function(msg) {
if (msg.success == true) {
response = '<div class="success">' + msg.message + '</div>';
$contactform.hide();
}
else {
response = '<div class="error">' + msg.errors + '</div>';
}
// Show response message.
$("#contactForm").prepend(response);
})
e.preventDefault();
});
});
Because the php is successful in returning a result.
The error would be triggered if the php failed to return.
If you want your Ajax handler to do something different if not logged in either specify in the Ajax handler (not recommended) or do it on the server side (in the php) returning what you want if they are not authenticated.
$("#search_traveller_button").click(function(){
$.ajax({
url: "index.php?act=checkSessionUser",
type: "POST",
cache: false,
success: function(data){
if (data==1){
console.log ("yeah it worked")
}else {
console.log ("error")
}
});
});
I am new in HTML and PHP, I have created a contact form for the users where they can add their messages. When they click on the send button I want the page to stay on this contact form and show a text message below that says it is succesfully sent. Here is my code some of it .
if (isset($_POST['submit']))
{
if (!isset($_POST['name'])) {
echo "please enter the name";
}else {
if (!isset($_POST["emailaddress"])) {
echo "please enter the email adresse ";
}else {
if (!isset($_POST["subject"])) {
echo " Please enter the message ";
} else {
$nom = $_POST['name'];
$email = $_POST['emailaddress'];
$msg = $_POST['subject'];
$sql = "INSERT INTO contacts (name, email, message) VALUES ('$nom', '$email', '$msg') ";
if (!mysql_query($sql)){
die ('error : ' . mysql_error());
} else {
mysql_close($link);
?>
</br></br>
<p25><center>sent succesfully! thanks</center></p25>s
<?php
echo "<script>setTimeout(\"location.href = 'no-sidebar.php'\",8000);</script>";
You need to understand each line of code.
if (!isset($_POST['name'])) {
echo "please enter the name";
}
The page will get reloaded on the first instance.
You need to do the form validation part in javascript. In this way, if some validation error happens, it can be displayed somewhere in the page without reloading it.
Then send the data to php through ajax, where you set your model and pass it to database and send a response back to javascript which can then print the message that the form has been submitted successfully.
Here's what I'm saying:
<input type="text" id="email" />
<button id="submit">Submit</button>
<div id="status"></div>
Javascript Part:
$(document).ready(function(){
$('#submit').on('click', function(){
var email = $('#email').val();
if(email.trim().length === 0){
$('#status').html('Email not provided');
}else{
$.ajax({
type : 'POST',
data : {action: 'sendData' , email : email}, // object
url : 'example.php',
cache: false,
success: function(response){
$('#status').html(response);
}
});
}
});
});
And in the php side, then you can just get the value which is already validated and return true or false based on your data insertion result to database.
example.php
<?php
if(isset($_POST['action']) && $_POST['action'] == 'sendData'){
$email = $_POST['email'];
if(dbinsertion successful){
echo "Success";
}else{
echo "Something went wrong";
}
}
?>
You have to use jquery here. Hope you understood.
I do have two kind of echo in my ajax processing script. One for error messages and other one for form processing success.
This is how its look.
if (strlen($password) != 128) {
$errorMsg = "<div class='alert alert-danger alert-dismissible' role='alert'>\n";
$errorMsg .= "<strong>Oops!</strong> System error, Invalid password configuration.\n";
$errorMsg .= "</div>\n";
echo $errorMsg;
}
And other one is
// Print a message based upon the result:
if ($stmt->affected_rows == 1) {
// Print a message and wrap up:
$successMsg = "<div class='alert alert-success alert-dismissible' role='alert'>\n";
$successMsg .= "Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the 'Password Modification' link.\n";
$successMsg .= "</div>\n";
echo $successMsg;
}
So, I am using one DIV to populate these message upon the ajax success.
My question is, is there a way to identify which message is displaying with ajax success?
Hope somebody may help me out.
Thank you.
You can use filter() to see if the response has the class of .alert-danger:
// $.ajax({ ...
success: function(html) {
var $html = $(html);
if ($html.filter('.alert-danger').length) {
// something went wrong
}
else {
// it worked
}
}
Note however, that a better pattern to use would be to return JSON containing the message to display, along with the class of the alert and a flag to indicate its state. Something like this:
var $arr;
if (strlen($password) != 128) {
$arr = array('success'=>false,'cssClass'=>'alert-danger','message'=>'Oops! System error, Invalid password configuration.');
}
if ($stmt->affected_rows == 1) {
$arr = array('success'=>true,'cssClass'=>'alert-success','message'=>'Your password has been changed. You will receive the new, temporary password at the email address with which you registered. Once you have logged in with this password, you may change it by clicking on the Password Modification link.');
}
echo json_encode($arr);
// $.ajax({ ...
success: function(json) {
if (json.success) {
// it worked
}
else {
// something went wrong
}
// append the alert
$('#myElement').append('<div class="alert alert-dismissible + ' + json.cssClass + '" role="alert">' + json.message + '</div>');
}
I'm trying to build a simple email signup, and I came across this tutorial which seemed to be exactly what I wanted to do (http://net.tutsplus.com/tutorials/javascript-ajax/building-a-sleek-ajax-signup-form/). I don't have much programming knowledge, so this was my best bet at getting something up and running. I followed the tutorial, but unfortunately, I'm having some problems with it.
My problem is when I try to submit an email address, I get Uncaught SyntaxError: Unexpected token < in jquery.js, on line 565.
When I expand the error in Dev Tools, it shows:
jQuery.extend.parseJSON jquery.js:565
$.ajax.success common.js:36
jQuery.Callbacks.fire jquery.js:1046
jQuery.Callbacks.self.fireWith jquery.js:1164
done jquery.js:7399
jQuery.ajaxTransport.send.callback jquery.js:8180
As I said, I'm a rookie with this, so I greatly appreciate any help. I've been researching for a while, but haven't found any issue the same as mine. Some were similar, but I couldn't fix the issue with any of the solutions I came across.
This is the form code:
<form id="newsletter-signup" action="?action=signup" method="post">
<fieldset>
<label for="signup-email">Sign up for email offers, news & events:</label>
<input type="text" name="signup-email" id="signup-email" />
<input type="submit" id="signup-button" value="Sign Me Up!" />
<p id="signup-response"></p>
</fieldset>
</form>
This is the signup JS:
/* SIGNUP */
$('#newsletter-signup').submit(function(){
//check the form is not currently submitting
if($(this).data('formstatus') !== 'submitting'){
//setup variables
var form = $(this),
formData = form.serialize(),
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#signup-response');
//add status data to form
form.data('formstatus','submitting');
//show response message - waiting
responseMsg.hide()
.addClass('response-waiting')
.text('Please Wait...')
.fadeIn(200);
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success:function(data){
//setup variables
var responseData = jQuery.parseJSON(data),
klass = '';
//response conditional
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
//show reponse message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
//set timeout to hide response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
form.data('formstatus','idle');
});
},3000)
});
});
}
});
}
//prevent form from submitting
return false;
});
And this is the PHP:
<?php
//email signup ajax call
if($_GET['action'] == 'signup'){
mysql_connect('host','user','password');
mysql_select_db('table');
//sanitize data
$email = mysql_real_escape_string($_POST['signup-email']);
//validate email address - check if input was empty
if(empty($email)){
$status = "error";
$message = "You did not enter an email address!";
}
else if(!preg_match('/^[^\W][a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\#[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)*\.[a-zA-Z]{2,4}$/', $email)){ //validate email address - check if is a valid email address
$status = "error";
$message = "You have entered an invalid email address!";
}
else {
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if(mysql_num_rows($existingSignup) < 1){
$date = date('Y-m-d');
$time = date('H:i:s');
$insertSignup = mysql_query("INSERT INTO signups (signup_email_address, signup_date, signup_time) VALUES ('$email','$date','$time')");
if($insertSignup){ //if insert is successful
$status = "success";
$message = "You have been signed up!";
}
else { //if insert fails
$status = "error";
$message = "Ooops, Theres been a technical error!";
}
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
//return json response
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
Thanks!
UPDATE: Shad - I inserted that code right after 'success:function(data){' Is that correct? After doing that, when trying to submit an email address, I get this in the console, pointing to the line with the newly added code:
Failed:
SyntaxError
arguments: Array[1]
get message: function getter() { [native code] }
get stack: function getter() { [native code] }
set message: function setter() { [native code] }
set stack: function setter() { [native code] }
type: "unexpected_token"
__proto__: Error
<br />
<b>Warning</b>: mysql_num_rows(): supplied argument is not a valid MySQL result resource in <b>/homepages/37/d403623864/htdocs/_php/launch_notify.php</b> on line <b>22</b><br />
{"status":"error","message":"Ooops, Theres been a technical error!"}
Screenshot of Dev Tools with that error. Let me know if you need to see any of the lines expanded or anything: http://i.stack.imgur.com/IwnBr.png
UPDATE #2: Using the code provided by satoshi, I think I made a little progress on figuring out the issue, but I still haven't solved it. I think I narrowed it down to a MySQL connection issue. I tried this code:
<?php
mysql_connect("[DB]","[USER]","[PASS]")
or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("signups")
or die(mysql_error());
echo "Connected to Database";
?>
And the response I get is:
Connected to MySQL
Access denied for user '[USER]'#'%' to database 'signups'
I've tried a bunch of things, but can't figure it out. My host is 1&1, and I created the table through there using PHPMyAdmin. I've tried different tables, all get the same issue. Here's a screenshot showing the table in PHPMyAdmin: http://i.stack.imgur.com/Oe0Fm.png
Thanks again for all the help so far everyone. I appreciate it.
Your PHP file is warning you because $existingSignup is not a valid resource. This is because your SQL query is invalid. For this reason, because PHP is outputting something unexpected, the page doesn't return a valid JSON response.
Please verify that your mysql_query(...) call returns a valid resource before calling mysql_num_rows(...), like this:
$existingSignup = mysql_query("SELECT * FROM signups WHERE signup_email_address='$email'");
if($existingSignup !== FALSE)
{
if(mysql_num_rows($existingSignup) < 1){
// ...
}
else { //if already signed up
$status = "error";
$message = "This email address has already been registered!";
}
}
else {
$status = "error";
$message = mysql_error();
}
Edit: please note that the query is syntactically correct, I guess you face the problem because you didn't set up the DB table correctly.