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>");
});
Related
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
Using the jQuery form plugin, I just want to submit the visible fields (not the hidden ones ) of the form.
HTML:
<div class="result"></div>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<div style="display:none;">
<input type="text" value="" name="name_1" />
</div>
<input type="submit" value="Submit Comment" />
</form>
I cannot find a way to submit only the visible fields using any of the methods below:
ajaxForm:
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
ajaxSubmit:
$('#myForm').ajaxSubmit({
target: '.result',
success: function(response) {
alert("Thank you for your comment!");
}
});
There is another method formSerialize but found no way to use it with the 2 methods mentioned above (usable with $.ajax however).
How to submit only the visible fields using any of the two methods ?
$("#myForm").on("submit", function() {
var visibleData = $('#myForm input:visible,textarea:visible,select:visible').fieldSerialize();
$.post(this.action, visibleData, function(result) {
alert('Thank you for your comment!');
});
// this is needed to prevent a non-ajax submit
return false;
});
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(){});
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; ?>";
I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!
## index.php ##
<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
<form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<legend><h2 style="align:center;">Enter Your Email Address</h2></legend>
<div class="row">
<div class="offset4 span3">
<input class="email" type="text" name="email" id="email" />
</div>
<div class="span1">
<input type="submit" name="submit" value="Join" class="btn btn-large btn-primary" />
</div>
</div>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
</div>
## and mailing-list.js ##
$(document).ready(function() {
$('#signup-form').submit(function() {
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
$(document).ready(function() {
$('#signup-form').submit(function(e) {
e.preventDefault();
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.
$(function(){
$('#signup-form').submit(function(e) {
e.preventDefault();
//your existing code goes here
});
});
You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();
Try
...
$('#signup-form').submit(function(event) {
event.preventDefault();
// update user interface
...