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
Related
So I'm making a very small, very simple chat application using mostly JQuery / AJAX.
Here is my HTML form.
<form class="chat_form" method="post" id="chat_form" autocomplete="off">
<input class="form-control" type="text" name="chatMe" placeholder="Type here..." autocomplete="off">
<input type="submit" value="Submit" name="submit">
</form>
Here is my script:
<script type="text/javascript">
$('.chat_form').submit(function(){
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
});
</script>
To my understanding, that's supposed to submit all the form information to my action page then clear the input - and it does. That part works fine. I'm getting my data.
But whenever I submit the form, the entire page reloads as if it's ignoring a key part of my code.
Any help on that part? Thanks.
Solution 1:
By adding e.preventDefault();
Example:
$('.chat_form').submit(function(e){
e.preventDefault();
//ajax code here
});
Solution 2
Alternatively, by adding little javascript onsubmit="return false" code in form tag:
Example:
<form class="chat_form" method="post" id="chat_form" autocomplete="off" onsubmit="return false">
You need to call e.preventDefault() for can submit the form only from the javascript code.
$('.chat_form').submit(function(e){
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
e.preventDefault() // put that line of code here or on last line on success function
});
You have propagation of the event by default, you probably need one or both of these calls:
e.preventDefault();
e.stopPropagation();
When the submit() is called on your object, it won't stop there. It will call the default afterward, so you want to add a parameter and then do those calls as in:
$('.chat_form').submit(function(e){ // <- add parameter here
e.preventDefault();
e.stopPropagation();
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
});
This is my form html in my Laravel application:
<button onclick="submitForm()">submit form using jquery ajax</button>
<form name="fbCommentCountform" action="{{ route('blogs.update', ['id'=>$id]) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PUT">
<input type="text" name="commentCount" id="fbFormCommentCount">
</form>
This is the ajax Javascript code I am trying to use:
function submitForm() {
var http = new XMLHttpRequest();
http.open("POST", "{{ route('blogs.update', ['id'=>$id]) }}", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "search=";
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I'm a little confused on how I define my params to make it send the data in my id #fbFormCommentCount input box. I simply want the form to submit on button click without reloading the page and using a PUT method because it is for a update request in the controller. Any guidance would be greatly appreciated!
You can do this pretty easily using jQuery's .ajax() like this:
$('form').on('submit', function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.prop('action'),
method: 'PUT',
data: $this.serialize(),
}).done(function(response){
}).error(function(err){
});
});
The e.preventDefault() will keep the form from submitting and causing the page refresh.
Then just move your button into the form and give it a type of submit
<button type="submit"> Submit form using jquery ajax </button>
You need to prevent the default event of the form submission.
Here's a minimal example of how to do it
https://jsfiddle.net/w208gsj7/1/
HTML
<form>
<button type="submit"id="submit">
Submit
</button>
</form>
JS
document.getElementById('submit').addEventListener('click', submitForm);
function submitForm(ev) {
ev.preventDefault();
// ... code
}
You need to grab the values from your form, like so:
var commentCount = document.getElementById('fbFormCommentCount').value,
params = "commentCount=" + commentCount;
You'll also need to grab and append your _method field, and the csrf token. If they don't have IDs, you can grab them by name:
var method = document.getElementsByName('_method')[0].value,
token = document.getElementsByName('_token')[0].value;
For those interested I was able to submit a form in Laravel without reloading the page. I did this while using AngularJs and so had to put everything in a $(function(){}); like so:
$(function()
{
$('form').on('submit', function(e)
{
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.prop('action'),
method: 'POST',
data: $this.serialize(),
success: function(result)
{
console.log(result);
}
});
});
});
Note: Newer versions of JQuery use "success:" instead of ".done". Hope this helps someone using a newer version.
I am submitting a form like this:
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="document.getElementById('form94').submit();" value="Opdater">
That for some reason doesn't trigger my jQuery .submit() function.
$("#form94").submit(function() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
});
Because you use different selectors
document.getElementById('form94'); //returns a HTML DOM Object
$('#form94'); //returns a jQuery Object
You can try next code, it works fine
<form id="form94">
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="$('#form94').submit();" value="Opdater">
</form>
<script type="text/javascript">
$("#form94").submit(function(e) {
e.preventDefault();
alert('test');
});
make a function out of it and trigger it with onclick like this:
<input id="submitBtn" style="margin-top:20px;" type="button" onclick="myfunction()" value="Opdater">
function myfunction() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
}
Is the javascript running after the form has been rendered? If not, either make sure that your javascript is after the form or try to have it run after the document has loaded.
$(document).ready(function() {
$("#form94").submit(function() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
});
});
Another way to go about having the form submit is to add the onsubmit attribute to your form and have it return a function. You could also change your button type to submit and remove the onclick attribute.
<form id="form94" name="form94" onsubmit="return SubmitMyForm();">
<input type="submit" value="Opdater">
</form>
<script>
function SubmitMyForm() {
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
$("#showFancyBoxThankYouLink").click();
}
});
return false;
}
</script>
Without a code example, it is hard to tell. But also, some browsers only submit a form when a user clicks a submit button, you cannot submit via script.
There are also a ton of other SO posts around this topic and they all either boil down to the form not existing when the submit event is attached (is your script executing at the top of the document or on the document's ready event?).
Form doesn't exist yet:
Why Jquery form submit event not firing?
Jquery .Submit() is not triggering submit event
Submitting via script:
Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?
Not using a submit button:
jQuery submit not firing
replace this
onclick="document.getElementById('form94').submit();"
with onclick="$( "#form94" ).submit();"
The javascript submit() is not bubbling in IE and they might be other gotchas.
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;
});
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'
});