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(){});
Related
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;
});
I have a form
<form method="POST" action="qwerty.php" />
<input type="text" name="merchant" />
<input type="text" name="password" />
<input type="submit" value="go" />
</form>
What I am trying to do is post this values into this php and get the result or reponse open up in the modal window it self.Is this possible? Any help?
EDIT :
Using Ajax and jquery this can be achieved like:
var merchant = $('form input:nth-child(1)').val();
var password= $('form input:nth-child(2)').val();
$('form input[type="submit"]').click(function() {
$.post( "qwerty.php", { merchant: merchant, password: password }, function(data) {
// #extraDiv is a div with display:none that will serve as a wrapper for the data
$('#extraDiv').html(data).colorbox();
});
});
Then in qwerty.php pick up the values u sent:
$merchant = $_POST['merchant'];
$password= $_POST['password'];
I am not so familiar with colorbox, but the above might work.
I am using jquery validation 1.9.0. I have used the latest Jquery and on back to 1.6.0. with no change in result
My problem is this: When I deliberately put in the wrong values (not enough characters etc) the validation script rightfully shows the errors yet allows the script to be submitted anyways.
I have tried methods of validation including add rules, rules and the very simple form type below.
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
<script>
$(function() {
$("#comm").validate();
});
</script>
the form
<form action="comm.php" method="post" name="comm" id="comm">
Name: <input type="text" name="name" id="name" minlength="3" class="required" />
Email:<input type="email" name="email" id="email" class="required email" /> <br />
<label for="comment"> Comment </label> <br />
<textarea name="comment" id="comment" cols="80" rows="5" minlength="6" class="required" /></textarea>
<?php
date_default_timezone_set('America/New_York');
$date = date("Y-n-j h:i:s");?>
<input type="hidden" name="date" id="date" value="<?php echo $date; ?>" />
<?php $post_id = $id;?>
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>" />
<?php $ip = $_SERVER["REMOTE_ADDR"]; ?>
<input type="hidden" name="ip" id="ip" value="<?php echo $ip; ?>" />
<input type="submit" value="Post" name="post" id="post" /> <input type="reset" value="Reset Form" name="reset" id="reset" />
</form>
Very simple stuff.
Submission happens on all my forms on the net, and all of them on localhost. I can always detect errors but never stop them. What am I doing wrong?
Firebug shows me submitting properly and no script errors. Also all jquerys are connected. Firebug also shows me this After submission novalidate="novalidate" in the form html. using onsubmit=return false does not change anything
I am using ajax to submit the form, works flawlessly
$(function() {
$("#comm").submit(function() {
var data = $('#comm').serialize();
alert (data); return false;
$.ajax({
url: "comm.php",
data: data,
type: "POST",
success: function(msg){
if(msg){
$('.comme').prepend().html(msg).show();
}else{
$('.comme').text("nothing came back");
}
}
});
return false;
});
});
Thank you
Try to do your Ajax handling after clicking the submit button instead of doing with jQuery form submission perhaps you're submitting the form data through Ajax only.
$(function() {
$("#post").click(function() {
var data = $('#comm').serialize();
// TODO: validate your data - $("#comm").validate();
// TODO: submit your form though ajax
// Other operations on form data
return false;
});
});
Note: If the form submission is happening with page redirection then try with 'onsubmit=return false;'.
Update:
I seems you've to submit the FORM from the validate function's submit callback handler(submitHandler) to avoid the redirection after submission. Please try to check this demo example which is working fine with Ajax form submission, review the source code of this example page and then adjust your code accordingly.
var v = jQuery("#form").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
target: "#result"
});
}
});
If you're usig jquery to receive the form when it is submitted, then then you should specify the php file containing the jquery code as the action of the form, instead of "listening" the submit event. Another option would be letting the 'action' parameter empty. The point here is that you're sending the form twice: when you click summit, the form is automatically sent to the file specified in the 'action' parameter, (that is the submission that is taking place, because it has no validation); and, at the same time when you click submit, it also triggers the ajax request, which will perform the validation and in case of success do the submission again.
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>");
});
I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>
Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.