How can I calling popup jquery from php form submit? - php

I've coded a contact form. If the mail() succeed, i would like to call my jquery popup.
How can I do this?
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
});
if(mail($address, $e_subject, $msg))
{
//?????
} else
{
echo 'ERROR!';
}/**/
I only want to show the popup if mail function succeed.
Both didn't work for me... sry .. maybe i'm too stupid.
here is my complete code:
file: popup.js
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
$(".schliessen").click(function() {
if(popup_zustand == true) {
$("#faq").fadeOut("normal");
$("#kontakt").fadeOut("normal");
$("#imprint").fadeOut("normal");
$("#hintergrund").fadeOut("normal");
popup_zustand = false;
}
});
});
file: contact.php
<?php>
if(mail($address, $e_subject, $msg))
{
//?????
} else
{
echo 'ERROR!';
}
?>
file: contact_inc.php
<form method="post" action="classes/contact.php" name="contactform" id="contactform" autocomplete="on">
<input name="name" type="text" id="input_text" required="required" size="24" maxlength="30"/>
<input name="email" type="email" id="input_text" pattern="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" required="required" size="24" maxlength="30">
<input name="phone" type="tel" id="input_text" size="24" />
<input name="company" type="text" id="input_text" placeholder="Firma..." size="24" maxlength="30">
<textarea style="height:100%" name="comments" cols="30" rows="10" id="input_text" spellcheck="true" required="required"></textarea>
<input type="submit" id="SubmitButton" value="Absenden" />
</form>
if I add to my button classes="kontakt_oeffnen" it will always popup ... without sending the email.
But I should only popup if the email would be sent correctly.
Can't I just call the jquery function from php (where the questions marks are...)

i would change the source a lil bit
HTML
<form>
<input name="name" type="text" id="input_text" required="required" size="24" maxlength="30" />
<input name="email" type="email" id="input_text" pattern="^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$" required="required" size="24" maxlength="30" />
<input name="phone" type="tel" id="input_text" size="24" />
<input name="company" type="text" id="input_text" placeholder="Firma..." size="24" maxlength="30" />
<textarea style="height:100%" name="comments" cols="30" rows="10" id="input_text" spellcheck="true" required="required"></textarea>
<input type="submit" id="SubmitButton" value="Absenden" />
</form>
jQuery
$(document).ready(function () {
$('#SubmitButton').on('click', function () {
var formData = $('form').serializeArray();
var fData = Array();
var postActive = false; // only because i dont have the contact.php (denie error)
$(formData).each(function(){
//console.log(this.name + ":" + this.value);
fData[this.name] = this.value;
});
if(postActive)
{
//now submit data to php file
$.post('classes/contact.php', {
data: fData // deal with info in phpfile, $_POST['data']['name'] or
// $_POST['data']['email'] .. return your mail result with a echo.
// lets say echo 1; for true or echo 0 for false
// because true and false in php is not the same as in js
}).done(function (response) {
//response contains 1 (mail was send!)
// by the way... you have a function befor/complete/error for handeling results...
// check out jquery.com
alert(response);
/* CANT find this in your "ALL MY SOURCE" post :)
if (response === false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
*/
});
}
console.log(fData); // open console to browse the array
});
});
PHP File (classes/contact.php)
<?php
//some source
// Data from Form is available like next row
$recipient = $_POST['data']['email'];
$name = $_POST['data']['name'];
....
$result = 0;
if(mail($rescipient, ... ))
$result = 1;
echo $result;
?>
of course you can work with JSON for better usage :)
in this way everything is clean, you have your HTML, your PHP and your jQuery source separated :)
PS: Check out the FIDDLE

You can try to mix it like this:
<?php
if(mail($address, $e_subject, $msg)) {
?>
<script>
jQuery(function($) {
var popup_zustand = false;
$(".kontakt_oeffnen").submit(function() {
if(popup_zustand == false) {
$("#kontakt").fadeIn("normal");
$("#hintergrund").css("opacity", "0.7");
$("#hintergrund").fadeIn("normal");
popup_zustand = true;
}
return false;
});
});
</script>
<?
} else {
echo 'ERROR!';
}/**
?>

Related

how do I make two phpmailer contact forms work on the same page

using code from here
https://www.codingsnow.com/2021/01/create-php-send-email-contact-form.html
<h4 class="sent-notification"></h4>
<form id="myForm">
<h2>Send an Email</h2>
<label>Name</label>
<input id="name" type="text" placeholder="Enter Name">
<br><br>
<label>Email</label>
<input id="email" type="text" placeholder="Enter Email">
<br><br>
<label>Subject</label>
<input id="subject" type="text" placeholder=" Enter Subject">
<br><br>
<p>Message</p>
<textarea id="body" rows="5" placeholder="Type Message"></textarea><!--textarea tag should be closed (In this coding UI textarea close tag cannot be used)-->
<br><br>
<button type="button" onclick="sendEmail()" value="Send An Email">Submit</button>
</form>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function sendEmail() {
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val()
}, success: function (response) {
$('#myForm')[0].reset();
$('.sent-notification').text("Message Sent Successfully.");
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
what do i need to change in both the files for it to work
right now when i put two contact forms on one page, both top working even though individually both of them are working..I have tried changes variable names and function names but cant figure out the error. in the network tab it says "failed, something went wrong"
I'll explain it with an example. Let's say you have a function to add up two numbers:
function add() {
return 3 + 5;
}
If you ever need to add a different set of numbers, this function is useless. However, if you pass variable information as function argument you have a multiple purpose function:
function add(a, b) {
return a + b;
}
As about assigning IDs in HTML, it adds more burden than benefits. Compare these two snippets and figure out which one is easier to use and extend:
jQuery(function ($) {
$("#input1, #input2, #input3").each(function (index, input) {
console.log(input.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input id="input1" value="One">
<input id="input2" value="Two">
<input id="input3" value="Three">
</form>
jQuery(function ($) {
$("input").each(function (index, input) {
console.log(input.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input value="One">
<input value="Two">
<input value="Three">
</form>
This is just an example to illustrate the point. The usual way to handle a form element is to assign it a name rather than an ID.

How to download PDF after fadeout the success message?

I am using a form to submit email and name to the user. After submitting the form email triggered and success message displaying. Success message fade-out after 10 seconds i.e. fine. Now I want to download a pdf also after fadeout success message.
I am achieving this via action.
I am using below code:
<form class="brochure brochure_1" method="post" id="custom_contact_form" action="http://example.com/contact/index/contact" onsubmit="return validateForm();" name="myForm">
<div class="input-box">
<input type="hidden" readonly="readonly" class="input-text required-entry toname" value="" name="toname"/>
<input type="hidden" value="<?php echo $this->getFromUrl(); ?>" name="submiturl" class="submiturl" />
</div>
<input type="text" class="input-text required-entry" value="" name="name" placeholder="Name"/>
<input type="text" class="input-text required-entry" value="" name="email" placeholder="Email"/>
<span><input type="submit" value="Download" /></span>
</form>
<script>
function validateForm() {
var name = document.forms["myForm"]["name"].value;
if (name == "") {
alert("Name must be filled out");
return false;
}
var email = document.forms["myForm"]["email"].value;
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (email == "") {
alert("Email must be filled out");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
jQuery('.success-msg').insertBefore(jQuery( ".breadcrumbs" ));
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
});
</script>
Replace the document ready like this,
jQuery(document).ready(function(){
setTimeout(function() {
jQuery('.success-msg').fadeOut('fast');
}, 10000); // <-- time in milliseconds
window.location.href = href; //causes the browser to refresh and load the requested url, Put the url to download pdf here.
});

How to return PHP response to HTML page using AJAX

I am trying to learn web applications, here I have my client side using HTML and server is PHP based.
I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX.
So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".
So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.
I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.
Here is the code
PHP:
<?php include ( "./inc/connect.inc.php" );
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");
session_start();
if (isset($_SESSION['user_login'])) {
$user = $_SESSION["user_login"];
}
else
{
$user = "";
}
?>
<?php
$registration = #$_POST['signup-submit'];
$fname = #$_POST['fname'];
$lname = #$_POST['lname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');
//Sign-Up form validation
if ($registration) {
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" );
echo json_encode($siginup_sucess_array);
}
else {
if ($usernamecount == 1) {
echo json_encode($ucheck_array);
}
else if ($emailcount == 1) {
echo json_encode($echeck_array);
}
}
}
HTML Form:
<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
<div class="form-group">
<input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
</div>
<div class="form-group">
<input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
</div>
<div class="form-group">
<input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
</div>
<div class="form-group">
<input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
</div>
<div class="form-group">
<input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
</div>
<div class="form-group">
<input type="email" name="email" id="email" placeholder="Email" value="">
</div>
<div class="form-group">
<input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
</div>
<div class="form-group">
<input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
</div>
<div class="form-group dob">
<input type="text" name="date" id="date" placeholder="Date" value="">
</div>
<p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
<div class="form-group">
<div class="row">
<div id="btn_signin" class="col-sm-6 col-sm-offset-3">
<input type="submit" name="signup-submit" id="signup-submit" value="SIGN UP">
</div>
</div>
</div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here
JS:
$("#signup-submit").click( function() {
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
$("#register-form").submit( function() {
return false;
});
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
To be clear I tried e.preventDefault, return false and many other scripts,
and my PHP and HTML are not in the same folder or directory.
Thanks.
Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:
<script>
function clearInput() {
$("#register-form :input").each( function() {
$(this).val('');
});
}
$(document).ready(function() {
$("#register-form").submit(function(e) {
//console.log($(this).attr("action"));
$.ajax({
url: $(this).attr("action"),
type: 'post',
data: $(this).serialize(),
success: function(response)
{
// console.log(response);
$("#signin-test").html(response);
clearInput();
},
error: function(response)
{
console.log(response);
}
});
e.preventDefault();
});
});
</script>
This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.
$("#register-form").submit( function( e ) {
e.preventDefault();
$.post( $("#register-form").attr("action"),
$("#register-form :input").serializeArray(),
function(signup_data){
$("#signup-test").html(signup_data);
});
clearInput();
});
I solved it with the following script, hope it would help someone.
The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).
So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".
Script :
function signup(){
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
var uname = document.getElementById("uname").value;
var email = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password = document.getElementById("password").value;
if (fname == "") {
document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";
}
else if (email != email_repeat){
document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
alert("Your email fields do not match");
}
else {
var signup_ajax = new XMLHttpRequest();
signup_ajax.open("POST", "URL which you want to post data", true);
signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
signup_ajax.onreadystatechange = function () {
if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
if (signup_ajax.responseText = "Success"){
alert("Account created");
}
else if (signup_ajax.responseText = "Try again.") {
window.scrollTo(0,0);
alert("Try again.");
}
}
}
signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
}
}
PHP(I'm just posting the basic php, you can always add as may validations as you need) :
if(isset($_POST["uname"])) {
$fname = #$_POST['firstname'];
$lname = #$_POST['lastname'];
$uname = #$_POST['uname'];
$email = #$_POST['email'];
$email_repeat = #$_POST['email_repeat'];
$password = #$_POST['password'];
//Sign-Up form validation
if($_POST) {
$squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" );
echo 'Sucess';
}
else
echo 'Try again.';
}
Only change what I did to my HTML Form is :
<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">

In html posting a form with javascript and php validation.. one fault- return true or false goes into text box of form

The form works, except, the value of true or false, gets put into the 'messagetxt' and that is the message I receive through email. I found the easiest way to create a continual alert box for invalid data, was to create a second contact page with an automatic alert upon loading.
//this is on page contact.html
//head etc..
<body>
<form action="email.php" method="post" name="contact" >
First Name:
<input type="text" placeholder="First Name" name="fname" id="fname" />
Last Name:
<input type="text" placeholder="Last Name" name="lname" id="lname"/>
Email Address:
<input type="email" placeholder="Email Address" name="email" id="email"/>
Message:
<input type="text" placeholder="Message" name="messagetxt" id="messagetxt"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var inputElem = document.getElementById('fname');
var inputElem = document.getElementById('lname');
var inputElem = document.getElementById('email');
var inputElem = document.getElementById('messagetxt');
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function (){
if (inputElem.value = '' || inputElem.value.length < 1){
alert('Please complete all fields');
return false;
}
};
</script>
</body>
</html>
//===
//this is on a page contacterror.html
//head etc..
<body>
<form action="email.php" method="post" name="contact" >
First Name:
<input type="text" placeholder="First Name" name="fname" id="fname" />
Last Name:
<input type="text" placeholder="Last Name" name="lname" id="lname"/>
Email Address:
<input type="email" placeholder="Email Address" name="email" id="email"/>
Message:
<input type="text" placeholder="Message" name="messagetxt" id="messagetxt"/>
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var inputElem = document.getElementById('fname');
var inputElem = document.getElementById('lname');
var inputElem = document.getElementById('email');
var inputElem = document.getElementById('messagetxt');
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function (){
if (inputElem.value = '' || inputElem.value.length < 1){
alert('Please complete all fields');
return false;
}
};
</script>
<script type="text/javascript">
alert("Please complete all fields");
</script>
</body>
</html>
//===
//this is my email.php
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//process form data
//check if the email address is invalid
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==FALSE)
{
header ("Location:contacterror.html");
}
else
{
//send email
$email=$_POST['email'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$message = $_POST['messagetxt'] ;
$subject="website contact";
mail("contact#yve3.com", $subject ,$message , "From: $email");
echo "Thank you for using our mail form.";
}
}
else
{//if "email" is not filled out, display the form
header ("Location:contacterror.html");
}
include ("contact.html");
?>
</body>
Is anybody able to help?
You want to take a look at your javascript. It seems to be causing the message textbox to return false upon reloading the page. If you remove the javascript or place it in the head of your page, this should take care of the issue. Also, the variable inputElem should be changed for each element that you want to retrieve. Your variable is overwriting itself everytime you call getElementById(). Try something like this:
<!doctype>
<html>
<head>
<meta charset='utf-8'>
<script type="text/javascript">
function Validate()
{
// create array containing textbox elements
var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email'), document.getElementById('messagetxt')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
}
}
if(error)
{
alert(error);
return false;
}
}
</script>
</head>
<body>
<form action='email.php' method="POST" name="contact" >
First Name:
<input type="text" placeholder="First Name" name="fname" id="fname" />
Last Name:
<input type="text" placeholder="Last Name" name="lname" id="lname"/>
Email Address:
<input type="email" placeholder="Email Address" name="email" id="email"/>
Message:
<input type="text" placeholder="Message" name="messagetxt" id="messagetxt"/>
<input type="submit" value="submit" onClick="return Validate();"/>
</form>
</body>
</html>
use <input type="submit" value="submit" name="submit"/>
and also replace
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
with
if (isset($_POST['submit'])) {
First if check if your form method is POST. it does not necessary mean if the user submit the form with pressing submit button.but the second if check if the user really submit the form with pressing submit button
I rectified my code, with thanks to Steel and Amir, this is neater, less complicated and works.
I thought I'd post this, as it is useful for others.
This provides a client and server side check against spamming the email address.
I've removed excess error handling, removed the extra html, forcing an error alert.
//javascript in head with loop to check fields
<script type="text/javascript">
function Validate()
{
// create array containing textbox elements
var inputs = [document.getElementById('fname'), document.getElementById('lname'), document.getElementById('email'), document.getElementById('messagetxt')];
var error;
for(var i = 0; i<inputs.length; i++)
// loop through each element to see if value is empty
{
if(inputs[i].value == '')
{
error = 'Please complete all fields.';
}
}
if(error != null)
{
alert(error);
return false;
}
}
</script>
</head>
//amended form
<body>
<form action="email.php" method="post" name="contact" >
First Name:
<input type="text" placeholder="First Name" name="fname" id="fname" />
Last Name:
<input type="text" placeholder="Last Name" name="lname" id="lname"/>
Email Address:
//===
// input type 'email' - client side check for spam
<input type="email" placeholder="Email Address" name="email" id="email"/>
Message:
<input type="text" placeholder="Message" name="messagetxt" id="messagetxt"/>
<input type="submit" value="submit" name="submit" onclick="Validate ()" />
</form>
</body>
</html>
//amended php
<body>
<?php
//==
//server side check for spam
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_POST['submit'])) {
//process form data
//check if the email address is invalid
$mailcheck = spamcheck($_POST['email']);
if ($mailcheck==TRUE){
//send email
$email=$_POST['email'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$message = $_POST['messagetxt'] ;
$subject="website contact";
mail("contact#yve3.com", $subject ,$message , "From: $email");
echo "Thank you for using our mail form.";
}}
include ("contact.html");
?>
</body>
</html>

jquery ajax form success message not working

jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.

Categories