Ajax Data Posting - php

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);

Related

Submit form with AJAX to php api

I have a form that is posting data to a php api file. I got the api working and it creates an account but want to use AJAX to send the data so I can make the UX better. Here is what the PHP sending script is expecting:
<form id="modal-signup" action="/crowdhub_api_v2/api_user_create.php" method="post">
<div class="modal-half">
<input type="text" placeholder="First Name" name="user_firstname"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Last Name" name="user_lastname"></input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="male" name="user_gender">Male</input>
</div>
<div class="modal-half">
<input type="Radio" placeholder="Gender" value="female" name="user_gender">Female</input>
</div>
<div class="modal-half">
<input type="date" placeholder="DOB" name="user_dateofbirth"></input>
</div>
<div class="modal-half">
<input type="text" placeholder="Zip Code" name="user_zip"></input>
</div>
<input class="end" type="email" placeholder="Email" name="user_email"></input>
<input type="password" placeholder="Password" name="user_password"></input>
<input type="submit"></input>
</form>
PHP
$user_firstname = $_REQUEST['user_firstname'];
$user_lastname = $_REQUEST['user_lastname'];
$user_email = $_REQUEST['user_email'];
$user_password = $_REQUEST['user_password'];
$user_zip = $_REQUEST['user_zip'];
$user_dateofbirth = $_REQUEST['user_dateofbirth'];
$user_gender = $_REQUEST['user_gender'];
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
How would I send this via ajax? I found this script that says it worked, but it did not create a user. I imagine its sending the data not the right way.
Ajax
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/api_v2/api_user_create.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
First, let's get ajax in order:
$(function () {
$('#modal-signup').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
//same url as the form
url: '/crowdhub_api_v2/api_user_create.php',
data: $('form').serialize(),
//we need a variable here to see what happened with PHP
success: function (msg) {
//output to the page
$('#output').html(msg);
//or to the console
//console.log('return from ajax: ', msg);
}
});
});
});
Somewhere on the form page, add a div with id output:
<div id="output></div>
Finally, in api_user_create.php, there is an error:
$user_gender = $_REQUEST['user_gender'];
//these last two do not exist on the form
$user_phone = $_REQUEST['user_phone'];
$user_newsletter = $_REQUEST['user_newsletter'];
I'd recommend some error-checking on the PHP side, like this
if(!empty($_REQUEST)){
//For developing, you may want to just print the incoming data to see what came through
//This data returns into the msg variable of the ajax function
print_r($_POST);
//once that's good, process data
if(isset($_REQUEST['user_gender'])){
$user_gender = $_REQUEST['user_gender'];
}
//etc... as before
} else {
echo 'no data received';
}

No alert in success function

I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>

newbie ajax (jquery) issue

I'm pretty strong with PHP, but javascript is totally new to me.
I need to add various ajax functionality to my projects, for example for form validation etc.
I've done some searching, watched some tutorials, and come up with a basic working example as follows:
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax form test</title>
<style>
form input, form textarea {
display:block;
margin:1em;
}
form label {
display:inline;
}
form button {
padding:1em;
}
</style>
</head>
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js:
$('form.ajax').on('submit', function() {
console.log('trigger');
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#form_content').load('server.php', data);
}
});
return false;
});
and finally, server.php:
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='')
{
?>
<h4>Your data was submitted as follows</h4>
<br />name: <?=$_POST['name']?>
<br />email: <?=$_POST['email']?>
<br />message: <?=$_POST['message']?>
<?php
} else {
?>
<h3>please fill in all form data correctly:</h3>
<form method="post" action="server.php" class="ajax">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="submit" value="send">
</form>
<?php
}
This all works fine, in that if I enter all form data and click submit, the ajax magic happens and I get a confirmation of the data. Also if not all data is loaded, the form is re-presented on the page. The problem is that in such a case, continuing to fill out the form data and then submit it loads the server.php page instead of repeating the ajax call until the form data is valid..
I'm sure there's a better way to do this as it's my first attempt, but I haven't been able to find any solution by searching either here or on google, but that's probably mostly because I don't really know what to search for. how can I make the behaviour in the first instance repeatable until the form is submitted correctly ?
This happens because you are removing your form element during your load() call and overwrite it with a new version of the form. Therefore all attached event handlers will vanish along with it.
You will need to use a delegate on an element that does not change:
$('#form_content').on('submit', 'form.ajax', function() {...});
Explanation:
In the above example, you attach the event listener to the #form_content element. However, it only listens to events that bubble up from the form.ajax submit event. Now, if you replace the form with a new version, the existing handler is attached higher up in the chain (on an element that doesn't get replaced) and continues to listen to events from lower elements, no matter if they change or not... therefore it will continue to work.
Your primary problem is that you are validating the form on the PHP side, when you should really validate it on the client side - THEN, instead of returning an appropriate response and continuing processing on the client side, you are finishing processing on the PHP side. Steve's answer (above) applies to what you are seeing.
As to the approach you have taken, it might be better to not use a <form> construction at all, because with AJAX you often don't need to. In my opinion, <form> is an archaic structure, not often needed in the age of AJAX. Notice how you had to add return false following the AJAX block to abort the default form functionality -- to stop it from sending the user over to server.php? That should tell you something.
Here is another way to structure it:
HTML:
<body>
<h2>CONTACT FORM</h2>
<div id="form_content">
<label for="name" value="name">name:</label>
<input type="text" name="name" placeholder="name" />
<label for="email" value="email">email:</label>
<input type="email" name="email" placeholder="email" />
<label for="message" value="message">message:</label>
<textarea name="message" placeholder="message"></textarea>
<input type="button" id="mybutt" value="send">
</div>
<div id="responseDiv"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
JAVASCRIPT/JQUERY:
$(document).ready(function() {
//Next line's construction only necessary if button is injected HTML
//$(document).on('click', '#mybutt', function() {
//Otherwise, use this one:
$('#mybutt').click(function() {
console.log('trigger');
var valid = "yes";
var that = $(this),
url = "server.php",
type = "POST",
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (value=="") valid = "no";
data[name] = value;
});
if (valid == "yes") {
$.ajax ({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
$('#responseDiv').html(response);
/* OPTIONALLY, depending on what you make the PHP side echo out, something like:
if (response == "allgood") {
window.location.href = "http://www.google.com";
}else{
//this is how you would handle server-side validation
alert('Please complete all fields');
}
*/
}
}); //END AJAX
}else{
alert('Please complete all fields');
}
}); //END button.click
}); //END document.ready
PHP Side: server.php
<?php
if (isset($_POST) AND $_POST['name'] !='' AND $_POST['email'] !='' AND $_POST['message'] !='') {
$r = '';
$r .= "<h4>Your data was submitted as follows</h4>";
$r .= "<br />name: " . $_POST['name'];
$r .= "<br />name: " . $_POST['email'];
$r .= "<br />name: " . $_POST['message'];
} else {
$r = "Please complete all form fields";
}
echo $r;

JavaScript form submits, but post data not available in 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; ?>";

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']

Categories