Why JavaScript onClick doesn't trigger jQuery submit function? - javascript

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.

Related

Submit form input value on page load with ajax

I have form and a input in it and I want to send its value to my controller.I wanna send its value when a page load or refresh current page using ajax and jquery because my page reload when I write submit function in body tags onload event.
Here is my code:
<form method="post" id="counterForm" name="counterForm">
#csrf
<input type="number" name="count" id="count" value="{{ $visit->counts }}">
</form>
Script code:
$(window).load(function(){
var n=document.getElementById("count").value;
$.ajax({
type:'POST',
url:'/count',
data:n,
});
});
My controller file :
public function count(Request $request)
{
$value=($request->count)+1;
DB::table('visitorcounter')->update(['counts'=>$value]);
}
That was my code but its not working...Thanks.
you can use .submit() :
Bind an event handler to the "submit" JavaScript event, or trigger
that event on an element.
you code would be like :
$(window).load(function() {
$('#counterForm').submit(function(){return true;});
});
Check out this example: :
$(window).load(function(){
// this is the id of the form
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data:$( "#myformR" ).serialize(),
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
});
I found it ... We can create a visitor counter very very simply by using a table with one integer column and a DB::table('test')->increment('count'); in AppServiceProvider Boot function.

I'm posting form data with AJAX, but the form keeps submitting and refreshing the page anyway. What am I missing?

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('');
}
});
});

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

JavaScript return false is not working

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

using jquery to make ajax call and update element on form submit

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'
});

Categories