I have asked before for help to get my php form working inside an phonegap ipa. I did exactly as I was told and everything works just fine, even inside the ipa. Only problem I have is that I get this alert right at the moment when the page loads, obviously it should show up when client forgets to fill in a required field.
Here is what I did:
FORM in contact.html
<form action="http://mobile.alicante-intermedia.com/submit_contact.php" method="get">
<div class="form-element">
<label for="txtfullname">Firstname</label>
<input id="txtfullname" name="FirstName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtemail">Lastname</label>
<input id="txtemail" name="LastName" type="text" placeholder="required" required />
</div>
<div class="form-element">
<label for="txtcontact">Email</label>
<input id="txtcontact" name="Email" type="email" placeholder="optional" />
</div>
<div class="form-element">
<label for="txtmessage">Message</label>
<textarea id="txtmessage" name="MessageText" placeholder="required" rows="5" required ></textarea>
</div>
<input type="button" onclick="submit()" value="submit contact"/>
</form>
Then I created a jquery_form.js file which loads only inside the conatct.html
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
FirstName: $('#FirstName_input').val(),
LastName: $('#LastName_input').val(),
Email: $('#Email_input').val(),
MessageText: $('#MessageText_input').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
And the php looks like this:
<?php
// VARS
$FirstName=$_GET["FirstName"];
$LastName=$_GET["LastName"];
$Email=$_GET["Email"];
$MessageText=$_GET["MessageText"];
$Headers = "From:" . $Email;
//VALIDATION
if(
$FirstName=="" ||
$LastName=="" ||
$Email=="" ||
$MessageText==""
) {
echo "Error";
} else {
mail("myemail#email.com","mobile app message",$MessageText, $Headers);
echo "Success";
}
?>
Everything works fine except the alert screen. Anyone here who has an idea what went wrong?
Your JavaScript code is "bare", not wrapped in any function or attached to any event handler, and therefore executes as soon as it is loaded - so it immediately posts an empty form when the jQuery script is first parsed.
Place it into the onclick event handler for the submit button:
// When the document has loaded...
$(document).ready(function() {
// Bind this action as a function to be executed when the button is clicked...
$('input[type="button"][value="submit contact"]').click(function() {
$.post('http://mobile.alicante-intermedia.com/submit_contact.php', {
// These are the names of the form values
// EDIT: You have the wrong ids on these...
FirstName: $('#txtfullname').val(),
LastName: $('#txtemail').val(),
Email: $('#txtcontact').val(),
MessageText: $('#txtmessage').val()
// HTML function
}, function (html) {
// Place the HTML in a astring
var response=html;
// PHP was done and email sent
if (response=="success") {
alert("Message sent!");
} else {
// Error postback
alert("Please fill all fields!");
return false;
}
});
});
});
Since it is bound in the JavaScript code, remove the onclick from the button in your markup:
<input type="button" value="submit contact"/>
Edit:
The PHP you have is looking for values in $_GET, but you have posted them from jQuery. Look instead in $_POST.
$FirstName=$_POST["FirstName"];
$LastName=$_POST["LastName"];
$Email=$_POST["Email"];
$MessageText=$_POST["MessageText"];
Related
I am using the malsup jquery form plugin to email a form via PHP, my form is in a bootstrap modal.
Everything seems to work fine, I receive success message however the email never shows up. It has something to do with my Ajax because the form works if I dont use AJAX, however, it then sends the user to the PHP url which is why i decided to use the plugin.
I have tried the ajaxForm and ajaxSubmit functions from malsup but with no success, the email just never shows up.
As a note, I am using another form (different name and id) and another AJAX and PHP call, but they work fine. They are completely separate files with different names, etc...
Plugin
http://jquery.malsup.com/form/#getting-started
Live website (select Contact Me button)
http://www.sitesbymiller.com
HTML
<form class="contactModalForm" id="contactModalForm" action="modalForm.php" method="post">
<div class="form-group">
<label for="contactName">Name*</label>
<input type="text" class="form-control" name="modalName" id="contactName" placeholder="Enter Name" required>
</div>
<div class="form-group">
<label for="contactEmail">Email*</label>
<input type="email" class="form-control" name="modalEmail" id="contactEmail" placeholder="Enter Email" required>
</div>
<div class="form-group">
<label for="contactPhone">Phone</label>
<input type="phone" class="form-control" name="modalPhone" id="contactPhone" placeholder="Enter Phone">
</div>
<div class="form-group">
<label for="contactMessage">Message*</label>
<textarea class="form-control" rows="5" name="modalMessage" placeholder="Enter detailed message" required></textarea>
</div>
<input type="submit" name="modalSubmit" class="btn btn-success" id="modalSubmit" value="Submit"/>
<button type="button" class="btn btn-default modalClose" data- dismiss="modal">Close</button>
</form>
Jquery/AJAX/JS file
var optionsB = {
url:'modalForm.php',
type:'post',
clearForm:'true',
resetForm:'true',
cache:'false',
success: function() {
alert('Thanks for your message! I will get back to you shortly.');
}
};
// bind to the form's submit event
$('#contactModalForm').submit(function() {
$(this).ajaxSubmit(optionsB);
return false;
});
PHP modalForm.php
<?php
if (isset($_POST['modalSubmit'])) {
if (!$_POST['modalName']) {
$error="<br />Please enter your name";
}
if (!$_POST['modalEmail']) {
$error.="<br />Please enter your email address";
}
if (!$_POST['modalMessage']) {
$error.="<br />Please enter a message";
}
if ($_POST['modalEmail']!="" AND !filter_var($_POST['modalEmail'],
FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s)
in your form:</strong>'.$error.'</div>';
} else {
if (mail("sitesbymiller#gmail.com", "Message from website modal form!", "
Name: ".$_POST['modalName']."
Email: ".$_POST['modalEmail']."
Phone: ".$_POST['modalPhone']."
Message: ".$_POST['modalMessage']."
On/Off Switch: ".$_POST['onoffswitch']."
Current Website: ".$_POST['modalWebsite']."
Favorite Website: ".$_POST['modalFavorite']."
Website Features: ".$_POST['modalFeatures']."
Website Purpose: ".$_POST['modalPurpose'])) {
$result='<div class="alert alert-success"><strong>Thank
you!</strong> I\'ll be in touch.</div>';
} else {
$result='<div class="alert alert-danger">Sorry, there was
an error sending your message. Please try again later.</div>';
}
}
}
?>
HTML and PHP files were good. Just had to make an adjustment to the JS/AJAX. I used the ajaxForm method instead of the ajaxSubmit and renamed my options variable as well as removed the url option, type option and cache option, and perfecto!
Big shoutout to http://jquery.malsup.com/form/#getting-started for creating such a great plugin that is user friendly and easy to use!
JS/AJAX
var options = {
clearForm:'true',
resetForm:'true',
success: function() {
alert('Thanks for your message! I will get back to you shortly.');
}
};
// pass options to ajaxForm
$('#contactModalForm').ajaxForm(options);
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(){});
I have a contact form with a few input fields and a div that acts as a button - when I click on it, it calls for a function that validates the form and if everything is OK it submits it. The function sends the data from the inputs to a API.php file, which calls for a sending function in the BusinessLogic.php file. Once the form is submitted - a callback function should be activated and it should animate a confirmation div.
The HTML of the inputs:
<div id="contact_inputs_block">
<div class="div_contact_form_input_box div_input_name">
<input type="text" name="Name" placeholder="* Name" id="name">
</div>
<div class="div_contact_form_input_box div_input_phone">
<input type="tel" name="Phone" placeholder="* Phone" id="phone">
</div>
<div class="div_contact_form_input_box div_input_email">
<input type="email" name="Email" placeholder="* Email" id="email">
</div>
</div>
<div class="form_confirmation_wraper">
<div id="div_form_confirmation">
Message sent.
</div>
<div class="div_send_form">
</div>
</div>
Here's my function:
function submit_form(language)
{
var email_str = $("#email").val();
var errors = new Array();
$("#contact_inputs_block>div:not(:last-child)").css({'border-color' : '#a5957e', 'background-color' : '#f8f8f8'});
if ($("#name").val()=="")
{
errors.push(".div_input_name");
}
if(!validate_email(email_str))
{
errors.push(".div_input_email");
}
if ($("#phone").val()=="")
{
errors.push(".div_input_phone");
}
if (errors.length == 0)
{
$.getJSON("inc/API.php",
{
command : "send_contact_form",
name : $("#name").val(),
email : email_str,
phone : $("#phone").val(),
message : $("#message").val().replace(/\n/g, '<br>'),
form_language: language
} ,function(){
alert("sent");
$("#div_form_confirmation").animate({opacity:1}, 1000, function(){
setTimeout($("#div_form_confirmation").animate({opacity:0}, 3000, function(){location.reload()}),6000);
}); // end callback function
}); // end getJSON
} // end if
else
{
for (var i = 0; i <= errors.length; i++)
{
$(errors[i]).css({'border-color' : '#E60005', 'background-color' : '#ffc4c9'});
}
}
}
this is the function in API.php:
include_once 'BusinessLogic.php';
session_start();
$command = $_REQUEST["command"];
switch($command)
{
case "send_contact_form" :
send_contact_form($_REQUEST["name"], $_REQUEST["email"],
$_REQUEST["phone"], $_REQUEST["message"], $_REQUEST["form_language"]);
break;
}
and the BusinessLogic.php actually sends the mail.
The mail is being sent, everything is OK there. The problem is the callback of submit_form() function is never fired and I don't see the confirmation that the mail was sent.
Why is it happening and how do I fix it? Thanks!
A different approach could be using $.post instead of $.getJSON (everything else will remain the same). It will make the desired ajax call. Parameters defined will be in $_POST array ($_REQUEST is fine)
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;
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);