So I've read the jQuery AJAX pages, and a bunch of tutorials, but am having a slight problem over here.
There are no errors, or warnings, just a blank page.
I am trying to send an email when the user fills in the newsletter subscription test field with their email address, and when you click submit, the page refreshes! (1st problem) and it fails to display anything on the page (second problem), all you see is just a blank page. No emails were received.
I've tested the email script separately, which works fine. I've been using for months with different sites so I know it works.
I've tried changing things around in jQuery etc but nothing has helped fix this problem.
jQuery:
$(function () {
var txt = $('.email').val();
$.ajax({
url: 'index.php',
type: 'post',
data: {
email: txt
},
success: function (data) {
alert(data);
},
error: function (err, req) {
$('#Response').html({
"Somethin' got broked. Please try again."
});
}
});
});
PHP:
<?php
if($_POST["email"] != null)
{
require_once "Mail.php";
$email = $_POST["email"];
// Send it.
$from = "X#X.com.au";
$to = $email;
$subject = "Newsletter Subscription Request.";
$body = "Thank you for subscribing to our newsletter!";
$host = "mail.X.com.au";
$username = "no-reply#X.com.au";
$password = "X";
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
}
?>
HTML:
<h4 id="Response">Stay informed. Subscribe to our Newsletter!</h4>
<form class="newsletterForm" action="index.php" method="post">
<input type="text" class="email" name="email" />
<input type='submit' class="btn" value="Subscribe" />
</form>
Can someone please help me figure out why this won't work?
Thank you
The 1st thing I do when stuff like this isn't working is to watch the page calls in the Chrome Developer Tools window.
As far as your code goes, the reason the page is refreshing is because the form submit is going through. To keep that from happening, you have to trap the form submit:
$("form").submit(function() {
// Do ajax
return false; // Keeps the form from submitting
});
Once you have that in place, you should be getting better results.
I would caution, however, that it is much easier to get the PHP email sending form working without using ajax at first by just having it handle the regular form submit. Once that works, then tie in the ajax on top of it.
With the following line you suppose to receive an answer from the PHP Script
success: function(data) {
alert(data);
}
But in the PHP script you don't output anything...Try writing something like
//[...]
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
die(1);
please try this surely you can get the problem solve.
function FormSubmit()
{
$.ajax({
type: "POST",
url: 'index.php',
data: $("#form_main").serialize(),
async: false
}).done(function( data ) {
$("#Response").hide();
if (isNaN(data))
{
dispmsg = "<div class='alert alert-danger' role='alert'>Oops..Something had gone wrong! Please try again!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('ResetForm();',3000);
}
else
{
dispmsg = "<div class='alert alert-success' role='alert'>Thank you for sharing the details. Our Consultant will contact you shortly!</div>";
$("#assess_me_response").html(dispmsg);
setTimeout('Redirect();',3000);
}
return true;
});
}
make your php as this..
<?php
$to = "xxxx#some.com";
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$phone = $_POST['phone'];
$subject = "Entry received";
$msg = "\n Name:" . $name . "\n Email id:" . $email ."\n Age:". $age . "\n Contact number: " . $phone;
$headers = "From:xxx#yyy.com";
mail($to,$subject,$msg,$headers);
echo "<div align='center'>Thank you " . $name . "!, we will contact you shortly.</div>";
?>
try this you can solve.
Related
I decided to ask this question because there is no simple answer to it.
I have a contact form in my home.php which looks like:
HTML:
<form id="js-calculator" name="calculator" action="" method="post">
<input type="email" name="email" id="email" placeholder="E-mail" />
<input type="tel" name="phone" id="phone" placeholder="Phone" />
<textarea name="message" id="message" placeholder="Message"></textarea>
<label for="accept"><input class="" type="checkbox" id="accept" name="accept" /> I agree to terms and conditions</label>
<button type="submit" id="send__btn">Wyślij wycenę</button></p>
</form>
JavaScript:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
PHP in functions.php
// Function to send emails
function sendMail () {
$subject = 'Automatic evaluation';
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $_POST['email'];
$subject = "Evaluation for ". $_POST['name'];
$message = "Message from ".$_POST['message'];
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
add_filter( 'wp_mail_content_type', 'set_content_type' );
function set_content_type( $content_type ) {
return 'text/html';
}
// Function to update DB
function addCustomer(){
global $wpdb;
$phone = $_POST['phone'];
$email = $_POST['email'];
$accept = $_POST['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
echo "Error";
} else {
$wpdb->insert_id;
}
die();
}
add_action('wp_ajax_addCustomer', 'addCustomer');
add_action('wp_ajax_nopriv_addCustomer', 'addCustomer');
What I would like to achive is:
1. Send an HTML email to client and to website admin,
2. Add client details to Database, check if email exists,
3. Have a secure connections and data flow;
Right now I have no idea what I`ve done wrong... Any help will be much appreciated.
You are almost there, couple of things:
In your JS ajax call, you need to specify the action to call, here's modified call:
jQuery(document).ready(function ($) {
$('#js-calculator').submit(function (e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: '<?php echo admin_url("admin-ajax.php?action=sendhtmlmail") ?>',
type: 'post',
dataType: 'JSON',
data: $this.serialize()
}
});
});
});
Now, lets look at the php functions:
// Function to send emails
function sendMail () {
$data = array(
'email' = sanitize_email($_POST['email']),
'name' = sanitize_text_field($_POST['name']),
'message' = sanitize_text_field($_POST['message']),
);
$subject = 'Automatic evaluation;
$headers = 'From: My Website Contact Form <contact#mysite.com>';
$send_to = "office#mysite.com, ". $data['email'];
$subject = "Evaluation for ". $data['name'];
$message = "Message from ".$data['message'];
wp_mail($send_to, $subject, $message, $headers);
addCustomer($data);
// TODO: Fill in this $response array with meaninfull data (check output from wp_mail and addCustomer)
$response = array(
'success' => true
);
wp_send_json($response);
}
add_action('wp_ajax_sendhtmlmail', 'sendMail');
add_action('wp_ajax_nopriv_sendhtmlmail', 'sendMail');
Just missing the wp_mail call, and the cleanup of the inputs, I removed your other ajax call, and have the sendMail function just pass the data to the addCustomer function. You'll notice a wp_send_json call, this is to send the response to the JS. https://codex.wordpress.org/Function_Reference/wp_send_json
Now lets look at your addCustomer function:
// Function to update DB
function addCustomer($data){
global $wpdb;
$phone = $data['phone'];
$email = $data['email'];
$accept = $data['accept'];
if($wpdb->insert('customers',array(
'phone'=>$phone,
'email'=>$email,
'accept'=>$accept
))===FALSE){
return false;
} else {
return $wpdb->insert_id;
}
}
The only thing that change here, is the return, so that the caller knows if it failed.
To handle inputs from user, check this doc from wordpress and core functions:
https://codex.wordpress.org/Validating_Sanitizing_and_Escaping_User_Data
Or you could use the following plugins together:
https://wordpress.org/plugins/contact-form-7/
https://wordpress.org/plugins/flamingo/
Here's how to use it: https://contactform7.com/save-submitted-messages-with-flamingo/
I hope this helps you!
Regards,
P.S wordpress questions are better suited here: https://wordpress.stackexchange.com/
I am using ajax to submit a form using swiftmailer. I'm getting an error when I try to submit the form. I think it has something to do with the "data" setting in the ajax call. I can get the swiftmailer mailing script to work fine when submitting a form not using ajax. You can see my work here, http://wickbuildings.com/form. I'm stuck and any help would be appreciated!
Here is my javascript:
$(document).ready(function () {
$("button#send_btn").click(function(){
$.ajax({
type: "POST",
url: "/assets/js/mailers/become-a-builder.php",
data: $('form[name=BecomeBuilderForm]').serialize(),
success: function(msg){
$("#thanks").html(msg) //hide button and show thank you
$("#form-content").modal('hide'); //hide modal
},
error: function(){
alert("failure");
}
});
});
});
and my swiftmailer mailing script:
<?php
//grab named inputs from html then post to #thanks
if (isset($_POST['name'])) {
$email_dsm = strip_tags($_POST['email_dsm']);
$name = strip_tags($_POST['name']);
$business_name = strip_tags($_POST['business_name']);
$address = strip_tags($_POST['address']);
$city = strip_tags($_POST['city']);
$state = strip_tags($_POST['state']);
$zip = strip_tags($_POST['zip']);
$phone = strip_tags($_POST['phone']);
$email = strip_tags($_POST['email']);
$comments = strip_tags($_POST['comments']);
// create message that fills #thanks container
echo "<div class=\"alert alert-success\" >Thank you for your inquiry. " . $email_dsm . " will be following up with you shortly.</div>";
// Create message of email to recipient
$body = "the contents of the email here";
require_once '../plugins/swiftmailer/swift_required.php';
// Create the mail transport configuration
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
// Create the message
$message = Swift_Message::newInstance();
$message->setTo(array(
'user#somedomain.com'
));
$message->setSubject('my email subject here');
$message->setBody($body, 'text/html');
$message->setFrom($Email);
// Send the email
$mailer = Swift_Mailer::newInstance($transport);
$mailer->send($message);
}
?>
Forms don't need names. give it an ID.
<form id="BecomeBuilderForm">
then use:
$('#BecomeBuilderForm').serialize()
or if you really want to use the name add double quotes around BecomeBuilderForm
$('form[name="BecomeBuilderForm"]').serialize()
if you really get stuck make sure your form is serializing using console.log()
$(document).ready(function () {
$("button#send_btn").click(function(){
console.log($('form[name="BecomeBuilderForm"]').serialize());
});
});
So I submit my form with Ajax like so
$("#submitform").click(function(e){
e.preventDefault();
var form_data = $("#contactfrm").serialize();
$.ajax({
type: "POST",
url: "/ltlcreation-new/wordpress/wp-content/themes/LTLCreation/includes/form-handler.php",
data: form_data,
error: function(){
alert("failed");
},
success: function(json_data){
console.log(json_data);
alert("success");
},
})
});
In my form-handler.php i catch the from errors
<?php
if(isset($_POST['submit'])) {
//include validation class
include 'validate.class.php';
//assign post data to variables
$name = #($_POST['name']);
$email = #($_POST['email']);
$message = #($_POST['message']);
$phone = #($_POST["phone"]);
//echo $name, $email, $message, $phone;
//start validating our form
$v = new validate();
$v->validateStr($name, "name", 3, 75);
$v->validateEmail($email, "email");
$v->validateStr($message, "message", 5, 1000);
$v->validateStr($phone, "phone", 11, 13);
if(!$v->hasErrors()) {
$to = "lukelangfield001#googlemail.com";
$subject = "Website contact form ";
$mailbody = $message . "\n" . "from " . $name . "\n" . $phone;
$headers = "From: $email";
mail($to, $subject, $mailbody, $headers);
echo "success";
} else {
//set the number of errors message
$message_text = $v->errorNumMessage();
//store the errors list in a variable
$errors = $v->displayErrors();
//get the individual error messages
//$nameErr = $v->getError("name");
//$emailErr = $v->getError("email");
//$messageErr = $v->getError("message");
//$phoneErr = $v->getError("phone");
echo $message_text; echo $errors;
$output = array($message_text);
echo json_encode($output);
}//end error check
}// end isset
These errors usually look like something like this
There were 4 errors sending your message!
Name must be at least 3 characters long.
Please enter an Email Address.
Message must be at least 5 characters long.
Phone must be at least 11 characters long.
["There were 4 errors sending your message!\n"]
I've tried to jSon encode the output and the in the success in ajax pull the json data out, however it just keeps returning an empty string like so
(an empty string)
My question is can you send data back from PHP to Ajax, if so I am doing this completely wrong?
You can output anything other than the json string so echo "success"; would make t. Use your debuggers Network response output tab to see that this is properly encoded.
Also don't use
$name = #($_POST['name']);
use instead
$name = isset($_POST['name']) ? $_POST['name'] : '';
If you still have a blank page make sure you have display errors set.
error_reporting(E_ALL);
ini_set('display_errors', 1);
I am an idiot I still had this in my PHP file which means the form wasn't firing or returning a response, silly me, glad i finally figured it out though
if(isset($_POST['submit'])) {
Thanks for the help guys
Here is an example of an Ajax contact form you can use:
Ajax.js
$(document).ready(function(){
$("#btn").click(function(){
var username=$("#name").val();
var email=$("#email").val();
var dis=$("#dis").val();
var process=true;
if(username=="")
process=false;
if(email=="")
process=false;
if(dis=="")
process=false;
if(process){
var dataString="name="+username + "&email="+email+ "&message="+dis;
$("#res").html('<span>Sending...</span><img src="a.gif">');
$.ajax({
url:"b.php",
type:"POST",
data:dataString,
success:function(data){
document.getElementById("name").value='';
document.getElementById("email").value='';
document.getElementById("dis").value='';
$("#res").html(data);
}
});
}else{
alert("fill all fields");
}
});
});
and b.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("ajax") || die("erro");
if(isset($_POST['name'])){
mysql_real_escape_string(htmlentities($name=$_POST['name']));
mysql_real_escape_string(htmlentities($email=$_POST['email']));
mysql_real_escape_string(htmlentities($message=$_POST['message']));
if(!empty($name) && !empty($email) && !empty($message)){
if(mysql_query("INSERT INTO `users` (name,email,message) VALUES('$name','$email','$message') ")){
echo 'The massage has been send';
}else{
echo mysql_error();
}
}
}
?>
enjoy that....
You have the following:
success: function(json_data){
While json_data is simply nothing. It should be
success: function(data){
I know I can use the form validation plugin with jQuery UI but for the sake of teaching myself some new tricks I'm taking this approach.
I have a jQuery script that posts a form to a PHP script via Ajax. The script then validates the input and sends a JSON encoded string back to the script. At this point, based on the status a validation message should be placed into a modal dialog and then opened to tell the user what happened.
Issue
It seems the script is returning a "null" status. In Chrome's JavaScript console the following line appears after clicking on the submit button of the form:
Uncaught TypeError: Cannot read property 'status' of null
Here's my validate_form.js
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.status > 0){
$("#response").dialog({
autoOpen: false,
modal: true,
height: 240,
width: 320
});
$("#response").dialog("open");
};
}
});
});
});
And here is contact.php
<?php
if(isset($_POST['contact_submit'])){
$name = trim($_POST['contact_name']);
$name = ucwords($name);
$email = trim($_POST['contact_email']);
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim($_POST['contact_notes']);
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($name_pattern, $name)){
$resp = array("status"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("status"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("status"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$to = "info#mydomain.com";
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("status"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("status"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
}
echo json_encode($resp);
?>
UPDATE 1
Adding console.log(dataString); yields the following in the console:
contact_name=Test&contact_email=testaccount%40mydomain.com&contact_dept=general&contact_notes=this+is+a+test+
As you can see it should've failed on the notes not being between 25 and 500 characters and returned the proper error message. Instead I still see the "cannot read property 'status' of (null)"
UPDATE 2
Here is exactly what I see in the JavaScript Console
UPDATE 3
I decided to remove the prevent default and actually post directly to the contact page through a traditional <form> statement that includes the method="post" action="contact.php" to see if the script itself was properly generating the JSON string and it is; here's what it generated on my most recent test:
{"status":4,"message":"Comments must be between 25 and 500 characters"}
So either it's not sending it back to the ajax handler or something else is missing.
UPDATE 4
I modified the script to handle a null value and alert me if no value was passed. So it's obvious now that the script isn't passing a json string back to the ajax call even though in update 3 I've verified that it's echoing one to the screen. I'm at a loss... (Update script above)
UPDATE 5
So I've made some progress. It turns out that the null was being returned because in my PHP script I was checking if the submit button was set and part of the $_POST array. But, because I'm preventing the default action of the form through jQuery it's not being passed. Only the form values that are serialized are being sent in the dataString. So now I'm getting the errors back in the console that I expect but I'm not getting the modal dialog to show up. The drama continues.
Most browsers support JSON.parse(), which is defined in ECMA-262 5th Edition (the specification that JS is based on). Its usage is simple:
var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
For the browsers that don't you can implement it using json2.js.
As noted you're already using jQuery, there is a $.parseJSON function that maps to JSON.parse if available or a form of eval in older browsers. However, this performs additional, unnecessary checks that are also performed by JSON.parse, so for the best all round performance I'd recommend using it like so:
var json = '{"result":true,"count":1}',
obj = JSON && JSON.parse(json) || $.parseJSON(json);
This will ensure you use native JSON.parse immediately, rather than having jQuery perform sanity checks on the string before passing it to the native parsing function.
Below i've mentioned some points try this to sort out your problem
1.change your method to get and try.
2.put die() after last echo and check what the exactly output.
So after more hours tweaking, testing, and pulling my hair out, here's the working script.
jQuery
$(document).ready(function() {
$("#contact_submit").on("click", function(e){
e.preventDefault();
var dataString = $("#frm_contact").serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
console.log(data);
if(!data){
alert("null value returned");
}else if(data.err > 0){
var $response = $("<div></div>")
.dialog({
resizable: false,
autoOpen: false,
modal: true,
height: "auto",
width: "auto",
buttons: { "ok": function() { $(this).dialog("close"); } }
});
$response.html("Error:");
$response.html(data.message);
$response.dialog("open");
$(".ui-dialog-titlebar").hide();
};
}
});
});
});
And for the PHP script I had to tweak it slightly as well to process it properly.
<?php
$name = trim(urldecode($_POST['contact_name']));
$name = ucwords($name);
$email = trim(urldecode($_POST['contact_email']));
$email = strtolower($email);
$dept = trim($_POST['contact_dept']);
$dept = ucwords($dept);
$notes = trim(urldecode($_POST['contact_notes']));
// Patterns and Comparison Qualifiers
$name_pattern = "/^[a-z][a-z ]*$/i";
$email_pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/";
$avail_depts = array("General", "Sales", "Support");
$notes_minlength = 25;
$notes_maxlength = 500;
if(!preg_match($name_pattern, $name)){
$resp = array("err"=>1, "message"=>"Names may only contain letters and spaces");
}else{
if(!preg_match($email_pattern, $email)){
$resp = array("err"=>2, "message"=>"Invalid e-mail address");
}else{
if(!in_array($dept, $avail_depts)){
$resp = array("err"=>3, "message"=>"Please select a department");
}else{
if(strlen($notes) < $notes_minlength || strlen($notes) > $notes_maxlength){
$resp = array("err"=>4, "message"=>"Comments must be between 25 and 500 characters");
}else{
// Build the message and e-mail it
$headers = "From: ".$name." <".$email.">";
$message .= "Contact Form Submission\n";
$message .= "==========================\n\n";
$message .= "Contact Name: ".ucwords($name)."\n\n";
$message .= "Contact E-mail: ".$email."\n\n";
$message .= "Category: ".$dept."\n\n";
$message .= "Comments: ".$notes."\n\n";
$message .= "\n";
if(mail($to, $subject, $message, $headers)){
$resp = array("err"=>5, "message"=>"Thanks! We'll be in touch soon!");
}else{
$resp = array("err"=>6, "message"=>"Something went wrong, please try again");
}
}
}
}
}
echo json_encode($resp);
?>
Everything works perfectly, modal alerts and all to the user. Thanks to those who attempted to help!
So I have a contact field which sends an email when submitted, I want to have the javascript alert when complete but am returning issues.
The javascript:
jQuery(document).ready(function() {
$.ajax({
url: './contactengine.php',
type: 'GET',
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
});
The php:
<?php
$EmailFrom = "emailname#gmail.com";
$EmailTo = "emailto#gmail.com";
$Subject = "new contact from website";
$Name = Trim(stripslashes($_POST['Name']));
$company = Trim(stripslashes($_POST['company']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "company: ";
$Body .= $company;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success)
{
$result = array('success' => true);
}
else
{
$result = array('success' => false, 'message' => 'Something happened');
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
echo json_encode($result);
?>
When I submit the form I get redirected to a page which says the following:
{"success":true}
When I should be staying on the same page and just alerting good.
The problem here is in your script I think, from the behaviour you describe it sounds like your PHP is doing the job.
I've made a few corrections to the ajax call based on the PHP code, try this and see if it helps.
$.ajax({
url: 'contactengine.php', //removed ./ - that's wrong I think
type: 'POST', //you are accessing $_POST not $_GET in the PHP file
data: $('myform').serialize(), //you need to send some data atleast
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
What I've done is removed ./ from the front of your URL - it should be either nothing, / for the root directory, or ../ for one directory up from the current directory. If the file is in the same directory as your page, keep it like I've done.
I've changed type from GET to POST - you are accessing the PHP $_POST global in your script, so the PHP would have been looking in the wrong place for variables.
Last but not least, I've put some data in. You need to pass in those variables that the PHP expects - so I've used a serialize() call. Replace the jQuery selector so that it will target your form, and it should pass in everything in your form to the PHP.
For more detail on the jQuery ajax function, see here: http://api.jquery.com/jQuery.ajax/
Hope this helps
Where is the data?
Plus You defined the request type as GET, but reading them as POST too. Send datas like this inside and change the request type to post
$.ajax({
url: './contactengine.php',
type: 'POST',
data: { variable1: "value1", .... }
dataType: 'JSON',
success: function(response) {
alert("GOOD");
},
error: function() {
alert("BAD");
}
});
Is your code that is calling the ajax function attached to a button on a form? It sounds like you are doing a regular non-ajax form submit right after the ajax call. You can try changing the onsubmit or onclick function that is running the ajax request to return false, and I think that should fix it.