ajax and php - my code is somehow duplicate the elements - javascript

i am new in ajax and i try to learn it.
i got this code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script>
$(document).ready(function(){
/**Add Ajax**/
$("#add-car-form").submit(function (evt) {
evt.preventDefault();//prevent form to be submitted as null
var postData=$(this).serialize();//get all the data from the form
var url=$(this).attr('action');//the url is the action attribute
$.post(url, postData, function(php_table_data){//send back the data from the url
$("#car-result").html(php_table_data);
});
});
});//End Document Ready
</script>
</head>
<body>
<div id="container" class="col-xs-6 col-xs-offset-3">
<div class="row">
<h2>Search our Database</h2>
<input class="form-control" type="text" name="search" id="search" placeholder="search our inventory">
<br>
<br>
<h2 class="bg-success" id="result"></h2>
</div>
<div class="row">
<form method="post" id="add-car-form" action="add_cars.php" class="col-xs-6">
<div class="form-group">
<input type="text" name="car_name" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="add car">
</div>
</form>
<div class="col-xs-6">
<div id="car-result">
</div>
</div>
</div>
</div>
</body>
</html>
and i got the add_car.php
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
header("Location: index.html");
}
?>
now, when i click submit in the form the sql statemant is working but some how i got a dublicate form as a result
here is a picture before insert data:
enter image description here
and here is a result after insterting data:
enter image description here

In add_car.php
Change your code like this
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
$table="<table><thead><tr><th>ID</th><th>Car Name</th></tr></thead><tbody>";
$query="Select * From cars ORDER BY id DESC";
$result=mysqli_query($connection,$query);
if($result){
while($row = $result->fetch_assoc()) {
$table.="<tr><td>" . $row["id"]. "</td><td>" . $row["cars"]."</td></tr>";
}
}
$table.="</tbody></table>";
echo $table;
}
?>

Related

jQuery $.ajax is not triggering anything to happen

I am trying to create a text box and whenever a user enters a message and clicks on send, the ajax should be activated and what's on insertMessage.php should get triggered. However, whenever i click on send it doesn't work. here is my chatbox.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user=$_SESSION['userid'];
$sql="SELECT * FROM `users` WHERE `Email`='$user'";
$res= mysqli_query($conn,$sql);
$user=mysqli_fetch_assoc($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>Hi <?php echo $user["FullName"]; ?></p>
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
<p>Send Message To:</p>
<ul>
<?php
$msgs=mysqli_query($conn,"SELECT * FROM users");
while($msg=mysqli_fetch_assoc($msgs))
{
echo '<li>'.$msg["FullName"].'</li>';
}
?>
</ul>
<--Back
</div>
<div class="col-md-4">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?php
if(isset($_GET["toUser"]))
{
$user=$_GET["toUser"];
$email=mysqli_query($conn,"SELECT * FROM users WHERE Email='$user'");
$emails=mysqli_fetch_assoc($email);
echo '<input type="text" value='.$user.' id="toUser" hidden/>';
echo $emails["Email"];
}
else{
$email=mysqli_query($conn,"SELECT * FROM users");
$emails=mysqli_fetch_assoc($email);
$_SESSION['toUser']=$emails['Email'];
echo '<input type="text" value='.$_SESSION['toUser'].' id="toUser" hidden/>';
echo $emails["Email"];
}
?></h5>
</div>
<div class="model-body" id="msgBody" style="height:400px; overflow-y:scroll; overflow-x:hidden;">
<?php
if(isset($_GET["toUser"]))
{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Receiver`='".$_SESSION["userid"]."' AND `Sender`='".$_GET["toUser"]."') OR (`Receiver`='".$_GET["toUser"]."' AND `Sender`='".$_SESSION["userid"]."')");
}
else{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Sender`='".$_SESSION["userid"]."' AND `Receiver`='".$_GET["toUser"]."') OR (`Sender`='".$_GET["toUser"]."' AND `Receiver`='".$_SESSION["userid"]."')");
}
while($chat=mysqli_fetch_assoc($chats))
{
if($chat["Sender"]==$_SESSION["userid"])
{
echo "<div style='text-align:right;'>
<p style='background-color:lightblue; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
else{
echo "<div style='text-align:left;'>
<p style='background-color:yellow; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
}
?>
</div>
<div class="model-footer">
<textarea id="message" class="form-control" style="height:43px;max-width:80%;float:left;">
</textarea>
<button id="send" class="btn btn-primary" style="height:70%;float:left;">Send</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#send').on('click', function(e) {
e.preventDefault();
$.ajax({
url:"insertMessage.php",
method:"POST",
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
dataType:"text",
success:function(data){
$("#message").val("");
}
});
e.preventDefault();
});
});
</script>
</html>
and here is my insertMessage.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fromUser=$_POST["fromUser"];
$toUser=$_POST["toUser"];
$message=$_POST["message"];
$output="";
$sql="INSERT INTO `message`(`Sender`, `Receiver`, `Message`) VALUES ('$fromUser','$toUser','$message')";
if($connect->query($sql)){
$output.="";
}
else{
$output.="Error. Please Try Again.";
}
echo $output;
?>
I don't know what to do i tried to find the issue so much but I couldn't. I am new to ajax so I don't know..
I am not sure what your exact problem is but there is one issue in your jQuery code, it takes an object as a value of data, like below :
data: {
fromUser: $("#fromUser").val(),
toUser: $("#toUser").val(),
message: $("#message").val()
},
dataType: "text",
Replace your semicolon (;) with a comma(,)
Put all your form elements inside a <form> in order to receive a data from your $_POST.
<form method="post" action="insertMessage.php">
/* your form elements here */
</form>
Don't forget to include method="post" in your form element, put name="fieldName" on your input elements (text, button, textarea) and a submit button.
Your data seems to have issues:
So, please change:
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
To:
data:{
fromUser: $("#fromUser").val(),
toUser:$("#toUser").val(),
message:$("#message").val()
},
Explanation:
Semi colons(;)are for closing a statement.
And the fromUser and others are properties of object data. So, they should be comma separated and it is one statement.
Also, as a suggestion:
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
The above field definition should have double quotes("") around value.
It creates issues(without semi-colons) when there are spaces in our value.
And hidden makes no meaning at all with above, is it of type="hidden" or is it class="hidden"?

image is inserted twice in the table when i upload one time only

Here I Upload Two Code one is Index.php and Another One is ImageUpload.php when i upload the image the file is move into uploads folder and the image name is twice store in the database i want only one data in database for every image that i upload and here is the database
images | int(11)
name | varchar(200)
image | longtext
<?php
include("config.php");
if(isset($_POST) && !empty($_FILES['image']['name'])){
$valid_extensions = array('jpeg', 'jpg', 'png','pdf','doc','docx'); // valid extensions
$filepath = 'uploads/';
if(!is_dir($filepath)){
mkdir($filepath, 0755, true);
}
$img = $_FILES['image']['name'];
$tmp = $_FILES['image']['tmp_name'];
list($txt, $ext) = explode(".", $img); // alternative $ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
$image_name = time().".".$ext;
$image_base64 =md5(rand());
$image = 'data:image/'.$image_name.';base64,'.$image_base64;
$query = "insert into images(name,image) values('".$image_name."','".$image."')";
mysqli_query($con,$query) or die(mysqli_error($con));
// Validate File extension
if(in_array($ext, $valid_extensions))
{
$filepath=$filepath.$image_name;
if(move_uploaded_file($tmp,$filepath)){
echo "<img width='100px' src='".$filepath."'>";
}else{
echo "Failed to upload image on server";
}
}else
{
echo 'Please upload valid image';
}
}else{
echo "Please select image to upload";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>PHP Ajax image upload without refreshing page with validation</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" >
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-offset-2 col-md-8">
<h2>PHP - Upload image on server with validation using jQuery Ajax</h2>
<div class="panel panel-info">
<div class="panel-heading">File upload using ajax in PHP</div>
<div class="panel-body">
<form action="imageUpload.php" enctype="multipart/form-data" class="form-horizontal" method="post">
<div class="preview"></div>
<input type="file" name="image" class="form-control" />
<br/>
<button class="btn btn-block btn-primary btn-upload" id="upload" name="upload">Upload</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".btn-upload").click(function(){
$(".form-horizontal").ajaxForm({target: '.preview'}).submit();
});
});
</script>
</body>
</html>
It's because your ajax request is running twice. Just add onsubmit="return false;" on your form element. So that the form is only submitted through the ajax code.
<form action="imageUpload.php" enctype="multipart/form-data" class="form-horizontal" method="post" onsubmit="return false;">
<div class="preview"></div>
<input type="file" name="image" class="form-control" />
<br/>
<button class="btn btn-block btn-primary btn-upload" id="upload" name="upload">Upload</button>
</form>
Disable the default behavior by adding e.preventDefault(); (needs you to pass the event e as an argument to your anonymous function.
$(".btn-upload").click(function(e) {
e.preventDefault();
$(".form-horizontal").ajaxForm({target: '.preview'}).submit();
});

Hide form when user click submit

I am using PHP and I have a form that I want to disappear/hide when the user clicks submit. It shouldn't appear/show for same user again.
form.php
<?php
session_start();
include('config.php');
if(isset($_SESSION['User']))
{
$nameuser = $_SESSION['User'];
}
else
{
header("location:signin.php");
}
?>
<!doctype html>
<html lang="en" class="no-js">
<head>
<title></title>
</head>
<body>
<header>
</header>
<!-- Form -->
<main class="cd-main-content">
<div class="container">
<form id="question_form" novalidate action="insertswat.php" method="post">
<div class="row">
<div class="col-25">
<label for="title">Swat form</label>
</div>
<div class="col-75">
<input type="text" id="" name="swat" >
</div>
</div><!--End -->
<hr>
<div class="row">
<input type="submit" value="submit">
</div>
</div></form><!-- End form -->
</main>
<!-- cd-main-content -->
</body>
</html>
insertswat.php
<?php
include('config.php');
$swat=$_POST['swat'];;
// Insert data into mysql
$sql = "INSERT INTO swatreport (swat)
VALUES ('$swat')";
if (mysqli_query($con, $sql)) {
header("location:swatform.php?q=success");
} else {
header("location:swatform.php?q=error");
}
mysqli_close($con);
?>
How could I go about this?
When user fill text field and clicks Submit
He will never see that form again
You can change this line <input type="submit" value="submit">
to assign id and name like this:
<input type="submit" name="submit" id="submit" value="submit">
Then:
<?php
$submit = $_POST['submit'];
if(!isset($submit)){
//Do NOT put closing curly brace
?>
<form>
//Your form you want to hide on submit
</form>
<?php
} //this is the closing curly brace
?>
//Put the stuff you want to show after submit here...
in header check if userlogged in
session_start();
if(!isset($_SESSION['loggedin'])){
header('location:login.php');
exit();
}
Try this JQuery snippet,
<script>
$( "#questions_form" ).submit(function( event ) {
$("#questions_form").fadeOut(500);
event.preventDefault();
});
</script>

Ajax call is inserting data on page in some other place

I am making use of ajax call to insert data in starting of my page. this is more like a wall post script. Whenever user posts something, the latest post is shown in the top of the posts page.
I am using JS, PHP and an HTML page.
here is my js code:
$(function() {
$("#tweet_submit").click(function()
{
var tweet = $("#tweet").val();
var x = $('.preview').attr('id');
if(x)
var z= x;
else
var z=0;
var dataString = 'tweet='+ tweet+ '&z=' +z;
if(tweet=='')
{
alert('Please type your tweet here');
}
else
{
alert('into post');
$.ajax({
type: "POST",
url: "WallPost/post_tweet1.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#preview").hide();
$("#content").prepend(html);
}
});
}return false;
});
});
This is my PHP page:
post_tweet.php
<?php
include("includes/db.php");
include("session.php");
include_once 'includes/time_stamp.php';
//echo "request sent to post";
if($_POST)
{
$tweet=$_POST['tweet'];
$upload_id=$_POST['z'];
$time=time();
$query = "INSERT INTO tweets(tweet,time,upload_id,uid_fk) VALUES ('$tweet','$time','$upload_id','$uid')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
echo "<br>".$msg;
$sql=mysqli_query($con,"select T.tid, T.tweet, T.time, T.upload_id, U.username, U.fullname, U.email FROM tweets T, users U WHERE T.uid_fk=U.uid and T.uid_fk='$uid' order by T.tid DESC LIMIT 1");
//$show_result=mysqli_query($sql);
while($row=mysqli_fetch_row($sql))
{
echo "data start here";
$tid= "$row[0]";
$tweet= "$row[1]";
$time = "$row[2]";
$img_id= "$row[3]";
$username="$row[4]";
$fullname = "$row[5]";
$email = "$row[6]";
$lowercase = strtolower($email);
$imagecode = md5( $lowercase );
$image_sql=mysqli_query($con,"select image_name from uploads where upload_id='$img_id'");
while($data=mysqli_fetch_row($image_sql))
{
$image_name="$data[0]";
$chars = 7;
$text = $image_name." ";
$text = substr($text,0,$chars);
$imgtext = "pic.twitter/".$text."...";
}
//echo "<div class='center'>";
echo "<div class='tweet_box' id='$tid'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/$imagecode?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/$username'>$fullname</a></b> <span class='uname'>#$username</span></div>";
echo "<div class='tweet_text'>$tweet ";
if($img_id!=0)
{
echo "<a href=''/>$imgtext</a></div>";
}
else
{
echo "</div>";
}
echo "<div class='tweet_options'><div class='first_option'><a href='#'>Expand</a> </div><div class='sub_options'> <a href='#'>Reply</a> <a href='#'>Retweet</a> <a href='#'>Favourite</a></div></div>";
if($img_id!=0)
{
?>
<div class="tweet_image" id="tweetimage<?php echo $tid; ?>">
<center><img src="uploads/<?php echo $image_name; ?>" class="image_show"/></center></div>
<?php
}
echo "</div></div>";
?>
<div class="tweet_reply_box" id="replybox<?php echo $tid;?>">
<div><textarea rel="<?php echo $tid;?>" id="replytext<?php echo $tid;?>" class="reply" name="reply"
maxlength="140">#<?php echo $username;?> </textarea></div>
<div class="reply_button_bar" id="replybutton<?php echo $tid;?>">
<div><input type="submit" value=" Reply " class="reply_btn" id="<?php echo $tid;?>"/></div>
</div>
</div>
<div id="reply_load<?php echo $tid;?>" class="reply_load">
</div>
<?php
}
}
else { }
?>
And this is my HTML page:
Wallpost.php
<!doctype html>
<html>
<head>
<title>Design Modo - Code-pal | eCommerce Website Template - Dead Stocker</title>
<link rel="shortcut icon" href="http://www.code-pal.com/wp-content/themes/codpeal-new/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/check_style.css" />
<link rel="stylesheet" href="css/wallpost/wtfdiary.css">
<link rel="stylesheet" href="css/wallpost/tipsy_title.css">
<script type="text/javascript" src="WallPost/js/jquery.min.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.tipsy.js"></script>
<script src="WallPost/js/twitter.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.form.js"></script>
</head>
<body>
<div class="page-wrap">
<div class="clear"></div>
<?php include("header.php"); ?>
<div class="clear"></div>
<div class="body-contents">
<?php include("left-body1.php"); ?>
<div class="center">
<br>
<div class="txthead"><strong>Share thoughts here</strong></div>
<?php
include("WallPost/index.php");
?>
</div>
</div>
<?php include("right-body.php"); ?>
<div class="clear"></div>
</div>
<!-- eo .body-content -->
<?php include("footer.php"); ?>
</div><!-- eo .page-wrap-->
Here is the code where i post tweet:
index.php under WallPost folder:
<?php
include("includes/db.php");
include("session.php");
include("includes/time_stamp.php");
?>
<html>
<head>
<link rel="stylesheet" href="css/wtfdiary.css">
<link rel="stylesheet" href="css/tipsy_title.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tipsy.js"></script>
<script type="text/javascript" src="js/twitter.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<div id="container">
<div id="sidebar_container">
<div id="sidebar">
<div id='logo'><img src='images/1.png'></div>
<div id="box">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet..."></textarea></div>
<div id='preview'></div>
<div id="button_bar">
<div id="icons">
<div class="filebutton" title="Image Upload">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg"/></span>
</form>
</div>
</div>
<div><input type="submit" value=" Tweet " class="btn" id="tweet_submit"/></div>
</div>
</div>
</div>
</div>
<!-- <div id="main"> -->
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id='heading'>Tweets</div>
<div id='content'>
<?php include("loads_tweets1.php");?>
<!-- </div> -->
</div>
</div>
</body>
</html>
So after i make use of all these code, Post is shown in my page, but the way it is shown is not correct.
The post is inserted at some random place. (I couldn't attach image due to less reputation)
Can someone please tell what is going wrong, and i am not able to get this data in correct place where my other posts are listed.
Thanks in advance!!!
Your input helped me and i was able to solve it. Content was being called at two places, and ajax inserted the data on first location and i was not getting it placed where i needed it.
Thanks.

Ajax Contact Form not showing Success

when I hit the send button on my contact form the form itself just disappears, not showing any kind of success message even though the email does still come threw. Below is the php, javascript and html. Thanks in advance for the help.
<!--[if lte IE 8]>
<script src="js/html5shiv.js"></script><![endif]-->
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.dropotron.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<script src="js/contact.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-noscript.css" />
</noscript>
<!-- Contact Form-->
<div class="content style4 featured">
<div class="container small">
<form id="contact" form method="post">
<div class="row half">
<div class="6u"><input type="text" class="text" name="name" id ="name" placeholder="Name" /></div>
<div class="6u"><input type="text" class="text" placeholder="Email" name="email" id="email"/></div>
</div>
<div class="row half">
<div class="12u"><textarea name="text" placeholder="Message" id="message"></textarea></div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li><input type="submit" class="button" value="Send Message" /></li>
<li><input type="reset" class="button alt" value="Clear Form" /></li>
<p class="success" style="display:none">Your message has been sent successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message must be longer than 100 characters.</p>
</ul>
</div>
</div>
</form>
PHP:
<?php
// Email Submit
// Note: filter_var() requires PHP >= 5.2.0
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if (preg_match( $test, $val ))
exit;
}
//send email
mail( "test#gmail.com", "Contact Form: ".$_POST['name'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
JS:
$('#contact').submit(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
//var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type : "POST",
url : "mail.php",
data : {name:name,email:email,message:message},
cache : false,
success : function() {
$("#contact").fadeOut(300);
$("#notice").fadeIn(400);
}
});
return false;
});
It disappears because you told it to with this code
$("#contact").fadeOut(300);
But I don't see your #notice container anywhere. It should be somewhere outside the #contact container and hidden by default.
Add something like this bellow your contact form:
<div id="notice" style="display:none">Email sent successfully</div>
But in order for it to be correct you should check in php if it is sent and then return something like "OK" like this:
if(mail(...)){
echo "OK";
}
and then in your response in javascript catch that message to see if it is really sent, like this
success : function(message) {
if(message=="OK"){
//then hide and show success
}
}

Categories