I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});
Related
I'am trying to use google invisible reCAPTCHA with AJAX. But returne false is not working.
JS:
function onSubmit(token) {
var siteurl= 'http://localhost/test/';
document.getElementById("register").submit();
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
return false
}
HTML:
<form id="register" action="" method="post" class="register">
<input class="for-1" type="text" name="field" >
<input class="g-recaptcha" data-sitekey="6LfCqCAUAAAAAAjaAg5w_mHK" data-callback='onSubmit' type="submit" value="Submit">
</form>
this codes working well but not returning false.
iam waiting help,
thanks.
Well if you wan't to avoid your page from reloading when form is submitted
I suggest you use this flow
1 -> data-callback='onSubmit' attribute is no longer need
2 -> remove function onSubmit and replace it with event listener
this code will listen if your form register is being submitted
$(document)
.off('submit', '.register')
.on('submit', '.register', function(e) {
/** Do what you want when submitting the form **/
var siteurl= 'http://localhost/test/';
var formdata = $('.register').serialize();
$.ajax({
method: "POST",
url: siteurl+"app/ajax/test.php",
data: formdata
})
.done(function( msg ) {
alert(msg);
});
/** prevent form from submitting to your form action page **/
e.preventDefault();
});
3 -> also document.getElementById("register").submit(); remove this since your form is already been submitting
e.preventDefault(); what this line do is it will prevent form from submitting to your form action page
My form
<form id="reservationForm" action="sendmail.php" method="post">
...
.
.
.
.
<input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px">
My javascript
$("#reservationForm").submit(function () {
e.preventDefault();
var $form = $(this);
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: $('#form').serialize(),
success: function(response) {
alert("Success");
$('#reservationForm').fadeOut("slow");
}
});
return false;
});
i don't want to run any validation because i have user 'required' in all types. i just want to send data to my php while staying at the same contact form. but this only load my php file and send the e-mail. looks like it dosen't run my javascript. please help
You haven't defined the event argument in the callback. Change this line as follows and it should work:
$("#reservationForm").submit(function (e) {
...
EDIT: BTW: The .submit event handler of jQuery short hand is deprecated. You should be using .on('submit', ...instead.
i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
I have an HTML form as follows:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
and then a submit button that calls verify():
Send
verify is defined as such:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
Currently, when I click the submit button, the browser redirects to emailinfo.php, which is just a blank white screen because that php file just sends off an email and does nothing else. How can I run that php file without redirecting to it?
What you want to do is use AJAX to send a request to the emailinfo.php file when the button is clicked. Making the form action blank will cause the form to post to the same page you're on.
If you're using jQuery, it's pretty easy to submit the form via ajax:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
Send
</form>
ContactFormFirst change that a tag to a button, then assign that verify() to its onclick. then in verify(). use ajax to post the values from your form to emailinfo.php.
u can use
$.post(
"emailinfo.php",
$( "#ContactForm" ).serialize(),
function( data ) {
/* do things with responce */
} );
What I usually do in this scenario is ajax, but if you do not want to use ajax, you can simply add 'return false' for it not to be redirected when using form submit:
function verify()
{
if(document.getElementById("name").value=="" ||document.getElementById("email").value=="")
{
alert("Please enter a name and an email.");
}
else
{
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
return false;
}
}
Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});