Jquery Ajax Form Using Mail() PHP Script Sends Email, But Post Data from HTML Form Is Undefined

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

There is no need to make a query string. Just put your values in an object and jQuery will take care of the rest for you.

var data = {
name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});

jQuery AJAX form using mail() PHP script sends sometimes email, and the POST data from HTML is white

Also html5 input type='email' to perform simple browser validaion of the address given ( just checks conforms to email standards and for an @ and .)

Data send to ajax by php are undefined after ajax success call

You send the email, you create the response Array but you don't pass it to the ajax call.
Where is the echo of the responseArray?
The best way I suggest you is to pass it as a json data:

echo json_encode($responseArray);

And then read in the javascript function

var json = $.parseJSON(data);

Sending e-mail using PHP and AJAX not working

When you submit the form in JavaScript, it's send with the form method (POST) to the server. The data includes all of your input values. In this case, the 'submit' input is not "clicked" and therefore not send with the request. So you don't have to check for the submit, means:

<?php
if($_SERVER["REQUEST_METHOD"] == "POST"){ // <-- remove '&& isset($_POST["ContactNow"])'

jQuery .ajax success response returning undefined - PHP script doesn't seem to be executed?

I finally figured this out.

At the top of all of my PHP scripts, I was calling:

session_start();

However, we were making use of google workbox on the front end for caching.There's an occurence where the user PHP session has actually expired (due to being inactive) but the google workbox had cached the page and showed them logged in (a further refresh would have shown them logged out) so when the script is called, the session was empty.

My script was running this check:

if (!isset($_SESSION['loggedin'])) {
$hostname = getenv('HTTP_HOST');
header('Location: https://'.$hostname.'/login.php');
exit;
}

It only occurred to me last night that this makes no sense. The script redirects itself to the login.php file which results in a HTTP code 200 which the ajax call is seeing and then firing the success function.

My website also makes use of a "remember me" function which my script wasn't utilizing. So, to "fix" my issue I have:

  1. Include the remember me function on my script calls so that the script itself can regenerate the session if they have checked remember me.
  2. Instead of redirecting to the login file, just fire back a message telling the user they need to log in.

Undefined data in the email of my contact form

Your issue is your selectors. You only use classes name and email for all your inputs.

<input type="text" name="phone" class="form-control name" ...>

should actually be:

<input type="text" name="phone" class="form-control phone" ...>
and so on for all the other inputs. Change your selectors to the appropriate classNames.

Also, never just use i.e: $(".name");, $(".email"); etc. as your selectors. As you know already $(".name"); will get every class="name" in your document. Same goes for all the other selectors. Instead, use the second argument (ParentElement) that will limit the search only to the children elements of the provided parent:

var name = $(".name", this);

or rather, use attribute selectors like:

var clinic = $(`[name="clinic"]`, this);

IMPORTANT NOTE about validation:

never trust the client.

JS validation should be used minimally, just as a UX tool to help, inform the user about basic errors/typos. The real validation, as well as all the related error responses, should be handled on the backend side.

Currently your PHP seems quite open to XSS attacks.

You don't need a HTML <form> in order to send data to the server. All it takes to an attacker is to find your route/path (usually exposed via the form's action attribute), take a look at the names in the source and manually construct a HTTP request, and send dangerous arbitrary data to your server. Just so you keep in mind.

How to send an email using jQuery and POST

You have multiple errors, first of all you are using element ids to pick up the data:

name: $("#form_name").val(),
email: $("#form_email").val(),
message: $("#msg_text").val()

but the input elements themselves have no id attribute defined.

Secondly, you are passing name, email and message, but in your PHP you are using name, email and text:

$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];

However, even if correct all this is unnecessarily complicated, you can instead just serialize the form:

In the HTML, add an id to the form:

<form enctype="multipart/form-data" id="frmemail">

In JS, pick up the form and serialize it:

$(document).ready(function(){
$("#frmemail").submit(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "email-php.php",
data: $("#frmemail").serialize(),
success: function(){
$('.success').fadeIn(1000);
}
});
});
});

And in PHP simply use the element names, you don't need ids for them:

$name = $_POST['form_name'];
$email = $_POST['form_email'];
$message = $_POST['form_msg'];

Sending e-mail form using PHP and AJAX

Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).

Then, when submitting a form with AJAX, the tag action="" is not needed.

Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.

I have improved your code to be more realistic about the latest standards.

HTML :

<form name="freeCall" method="post" class="popover-form" id="free-call-form">  
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >

JS :

$(function () {    
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});

And PHP :

if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){ 
$to = 'test@gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info@mail.com>\r\n";
mail($to, $subject, $message, $headers);

echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}

With echo json_encode, you know what is the return of your AJAX call. It is better

PHP Forms and Ajax calls, reports undefined index error after form submit

Two Possible Reasons

  1. Missing name attribute in form fields
  2. Data not being sent from AJAX submit call

Address missing name attribute in form fields

name attribute missing from form fields. I have updated your form fields with name attribute. Update your form to the below form and check your ajax calls.

<form id="ajax-contact" method="post" action="php/mailer.php" role="form">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" id="email" name="email" class="form-control" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" rows="5" name="message" class="form-control" required></textarea>
</div>
<button type="submit" name="submit" class="btn">Submit</button>
</form>

send data in ajax Calls

After your form field has name attribute, update your ajax call to utilize those name. During ajax request also include the form fields as follows. By using $('#ajax-contact').serialize() it will send all the information to the server. Play with it if its your first time with serialize.

Example Ajax Call

$.ajax({
url: 'yourdomain.com/php/mailer.php',
method: 'POST',
data: $('#ajax-contact').serialize(),
dataType: 'json',
success: function() {
// Your success callback
},
error: function() {
// Your error callback
}
});

Suggestions

Also like other suggested, implement the strict check of the values with isset(), empty(). It's a good practice. If you still have problem after it please update your question with AJAX calls and we'll try to help you. Please let us know whether it worked for you or not.



Related Topics



Leave a reply



Submit