JavaScript form submits, but post data not available in PHP - php

It seems the form submits (to the same page - contact.php), but I can not use posted data, for example $_POST["message"] . seems they are empty (I tried to echo them and nothing printed out).
This is JavaScript (in head section of page):
$(document).ready(function (){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$.post("contact.php", {
name: $('#name').val(),
email: $('#email').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
}, function(data,status){
alert("status = " + status);
$('#contactform #submit').attr('disabled','');
if(data=='Message sent!') $('#contactform').slideUp();
});
return false;
});
});
this is form:
<form action="contact.php" method="post" id="contactform">
<ol>
<li>
<label for="name">First Name *</label>
<input name="name" id="name" class="text">
</li>
<li>
<label for="email">Your e-mail *</label>
<input id="email" name="email" class="text">
</li>
<li>
<label for="company">Company Name</label>
<input id="company" name="company" class="text">
</li>
<li>
<label for="subject">Subject<br>
</label>
<input id="subject" name="subject" class="text">
</li>
<li>
<label for="message">Message *</label>
<textarea id="message" name="message" rows="6" cols="50"></textarea>
</li>
<li class="buttons">
<input type="image" name="submitbtn" id="submitbtn" src="images/but_send_message.gif">
</li>
</ol>
</form>
The alert("status = " + status); section on javascript pops up the status as sucess.
UPDATED
And this is PHP part at the top of contact.php
<?php
if(isset($_POST["message"])){
echo '<script>alert("some dummy text");</script>';
};
?>
It is not just that echo does not print anything, but I can not access values from posted data. PHPMailer works fine with manually assigned text to parameters.

If $_POST returns empty data. Make sure that you don't have any htaccess causing this.
I had this problem once. My htaccess always emptied the post data. After modifying the htaccess I got my problem solved.

Just try this code to post the form and check will getting $_POST on contact.php or not
<script type="text/javascript">
$(document).ready(function (){
$("#submitbtn").click(function(){
$("#contactform").attr("action" , "contact.php");
$("#contactform").submit();
});
</script>
If in contact.php if you get $_POST then show success message
<?php
if(isset($_POST["message"])){
echo '<script>alert("some dummy text");</script>';
};
?>

Since you asked for the answer that was a comment
Well, it seems fine, but alternatively you can try
$('#contactform').serialize();
to get all the form values for you and since you asked that, what is the better way to determine that the form has been submitted, well, in this case you can check the submit button instead of a text box or other form fields that could be left empty, so you can ue
if( isset( $_POST['submitbtn'] ) ) {
// process the form
}

Do the Following:
1) provide an id or a class to the li class button's child's input tag
2) Then in jquery write a code to handle :
$('.inputButton').click(function(){
var data = $('#contactform').serializeArray();
$.each(data, function(key, field) {
// Perform your validations over the data here
console.log('field Name == '+field.name+', field value == '+field.value);
});
// Make an ajax call using this data
$.post("contact.php", data, function(returnData) {
// Handle your code for after form submission response
});
});
3) Then in PHP you can get values as :
$name = $_POST["name"]; // and so on...
Hope this helps you solve your problem

as Sheikh heera mentioned in his comment on my question, I tried this:
$(document).ready(function (){
$('#contactform').serialize(function(){
var action = $(this).attr('action');
$.post("contact.php", {
name: $('#name').val(),
email: $('#email').val(),
company: $('#company').val(),
subject: $('#subject').val(),
message: $('#message').val()
}, function(data,status){
$('#contactform #submit').attr('disabled','');
if(data=='Message sent!') $('#contactform').slideUp();
});
return false;
});
});
and it works fine now! thanks to other users that suggested alternate solutions which may be working on this case but as I found the solution, there is no need to check them.

Save your post values in a variable. For example:
$name = $_POST["name"];
You can echo this variable in your script:
var name ="<?php echo $name; ?>";

Related

AJAX code not working on button click

Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});

AJAX/PHP/JQUERY mailing contact form gives correct error message when nothing is in form but fails to run Ajax

I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']

Ajax Data Posting

Hello im trying to implement an ajax invitation script which will let the user to invite his/her friends to that event. I use the mostly same javascript in the other parts of the website and they work perfect, but in this case, it doesn't work, i'm sure that the problem persists because of the javascript part, because as i said, i use the nearly exact script and it works perfect, when i post the data, it doesn't send the email, my mail function works good ( in other pages i use the same without ajax and it works ) but i think the javascript part can't post the data in this case.
By the way there is not any problem with getting the values in the hidden parts.
Hope you can help.
the javascript part :
<script type=\"text/javascript\">
$(document).ready(function() {
$('.error').hide(); //Hide error messages
$('#MainResult').hide(); //we will hide this right now
$(\"#button\").click(function() { //User clicks on Submit button
var js_name = $(\"#name\").val();
var js_message = $(\"#message\").val();
var js_username = $(\"#username\").val();
var js_useremail = $(\"#useremail\").val();
var js_eventname = $(\"#eventname\").val();
if(js_name==\"\"){
$(\"#nameLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
if( js_message==\"\"){
$(\"#messageLb .error\").show(); // If Field is empty, we'll just show error text inside <span> tag.
return false;}
var myData = 'postName='+ js_name + '&postMessage=' + js_message + '&username=' + js_username + '&useremail=' + js_useremail + '&eventname=' + js_eventname;
jQuery.ajax({
type: \"POST\",
url: \"invite.php\",
dataType:\"html\",
data:myData,
success:function(response){
$(\"#MainResult\").html('<fieldset class=\"response\">'+response+'</fieldset>');
$(\"#MainResult\").slideDown(\"slow\"); //show Result
$(\"#MainContent\").hide(); //hide form div slowly
},
error:function (xhr, ajaxOptions, thrownError){
$(\"#ErrResults\").html(thrownError);
}
});
return false;
});
$(\"#gobacknow\").live(\"click\", function() {
$(\"#MainResult\").hide(); //show Result
$(\"#MainContent\").slideDown(\"slow\"); //hide form div slowly
//clear all fields to empty state
$(\"#name\").val('');$(\"#message\").val('');
});
$(\"#OpenContact\").live(\"click\", function() {
$(\"#form-wapper\").toggle(\"slow\");
});
});
</script>
the html part:
<div id="form-wapper">
<div id="form-inner">
<div id="ErrResults"><!-- retrive Error Here --></div>
<div id="MainResult"><!-- retrive response Here --></div>
<div id="MainContent">
<fieldset>
<form id="MyContactForm" name="MyContactForm" method="post" action="">
<label for="name" id="nameLb">Email : <span class="error" style="font-size:10px; color:red;">Error.</span></label>
<input type="text" name="name" id="name" />
<label for="message" name="messageLb" id="messageLb">Message : <span class="error" style="font-size:10px; color:red;">Error.</span></label><textarea style="resize:vertical;" name="message" id="message" ></textarea>
<input type="hidden" name="username" id="username" value="<?php echo get_username($userid); ?>">
<input type="hidden" name="useremail" id="useremail" value="<?php echo get_email($userid); ?>">
<input type="hidden" name="eventname" id="eventname" value="<?php echo $eventname; ?>">
<br><button id="button">Send</button>
</form>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
invite php file :
$postName = filter_var($_POST["postName"], FILTER_SANITIZE_STRING);
$postMessage = filter_var($_POST["postMessage"], FILTER_SANITIZE_STRING);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$useremail = filter_var($_POST["useremail"], FILTER_SANITIZE_STRING);
$eventname= filter_var($_POST["eventname"], FILTER_SANITIZE_STRING);
invite($useremail, $postMessage , $username, $eventname, $postName); // this is a functipon that i use, it works in other cases, but not working in here
Rather than trying to debug that javascript, here is a much much easier / cleaner way to do this for the javascript AJAX post:
$.post('invite.php',$('#MyContactForm').serialize(),function(data){
if(data.success){
// all your on success stuff here
alert('success!');
}else{
// show error messages
alert(data.e);
}
},'json');
For your PHP part, echo a JSON response array, eg:
$data['success']=false;
$data['e']='Some error';
echo json_encode($data);

submit form on click of a link and send to multiple email ids

I have formatted my form using uniform jquery plugin. Also for submitting the form i am using a link as i have added some effect to it and if I use input type submit for this it will get formatted with uniform .
<form>
<ul>
<li><label>Your Name:</label><input type="text" name="name" size="40"/></li>
<li><label>Your Email:</label><input type="email" name="email" size="40"/></li>
<li>
<label>Gender:</label>
<select name="gender">
<option>Male</option>
<option>Female</option>
</select>
</li>
<li><label>Subject:</label><input type="text" name="subject" size="40"/></li>
<li><label>Write your letter here:</label><textarea name="message" cols="60" rows="15"></textarea></li>
OR ELSE<br/><br/>
<li>
<label>Upload your letter:</label>
<input type="file" />
</li>
<li>
<a id="mylink" class="button" href="#">
<img src="button.png" alt="" />Send</a>
</li>
</ul>
</form>
Now i want to submit this form using the link and also want to email it to two email ids simultaneously. What javascript code can i use. I am using the following code to submit the form and then in send.php I am sending the mail.
a.onclick = function() {
$(this).parents('form:first').submit();
send.php;
return false;
}​
Is it possible to call send.php like this?
Do you mean:
If you have action="send.php" in your form, then
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$(this).closest('form').submit();
});
});
Or, you can set action for the form and submit, like
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
var myFrm = $(this).closest('form');
myFrm.get(0).setAttribute('action', 'send.php');
myFrm.submit();
});
});
OR, using ajax
$(document).ready(function() {
$("#mylink").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "send.php",
data: {your data to post here},
succes: function(resp) {
//your response here
}
});
});
});
Is it possible to call send.php like this?
Like this? No, you need to use ajax request:
$.ajax({
url :"send.php"
});
Extra tip: change:
$(this).parents('form:first').submit();
To:
$(this).closest('form').submit();

jQuery - replace contact form with 'thanks message'

I have a contact form which performs a PHP action. The contact form is connected with validation engine in jQuery. If messege is sent correctly I simply include PHP file with thanks message - require_once('success.php');. After sending message I would like to replace contact form with thanks message without reloading the whole page. Please give me some advices how to do it.
Here is my html:
<div id="contactForm">
<form id="expertForm" class="formular" method="post" action="send.php">
<fieldset>
<label>
<input name="email"
id="email"
class="required email"
type="text"
size="40"/>
</label>
<p>
<textarea name="body" id="body" rows="5" cols="50" class="required"></textarea>
</p>
</fieldset>
<input class="submit"
type="image"
src="../images/btn-send.png"/>
</form>
</div>
<script type="text/javascript">
$("#expertForm").validate();
</script>
In send.php I have:
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
require_once('success.php');
}
You can see an almost working demo here http://jsfiddle.net/v7MJA/1/
$(function(){
$("#expertForm").submit(function(e){
e.preventDefault();
if(!$(this).validate().form()) return false;
$.ajax({
url:$(this).attr('action'),
data:$(this).serialize(),
type:'post',
success:function(msg){
$("#expertForm").replaceWith(msg);
}
});
});
});
You'd better give us some code so that we could help.
Here is the theorical way: use the success event of the jquery ajax[ref] call:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$("#myformdiv").html("Thanks!");
}
});
assuming that your HTML markup is something like:
<div id="myformdiv">
<form>
<!-- form code here -->
</form>
</div>
Assuming I've understood your question correctly, you can use the replaceWith method to replace the matched elements with the specified content:
$("#yourForm").replaceWith("<p>Thanks!</p>");
I'm assuming that you're doing something asynchronously to send the form data to the server, so you can just run the above code in the callback:
$.post("yourScript.php", function() {
$("#yourForm").replaceWith("<p>Thanks!</p>");
});

Categories