jQuery submit() is not firing - javascript

I am trying to trigger the submit of a form from a link outside the form (not the submit button).
Here is the basics of the form:
<form action="/Hospice/TabPatientTrackingPost" id="formTabPatientTrackingPost" method="post">
[a big form with lots of inputs]
<div class="pull-right">
<button type="submit" class="btn btn-brand" id="btnSave" name="btnSave">Save</button>
<button type="reset" class="btn btn-brand" id="btnCancel">Cancel</button>
</div>
</form>
Here is what the link looks like:
Living</li>
JS Function:
function triggerSave() {
alert("triggerSave test alert");
$("#formTabPatientTrackingPost").submit();
}
But, the code $("#formTabPatientTrackingPost").submit(); is not causing the form to post the submit.
The alert("triggerSave test alert"); is firing, but the form is not submitting.
It works fine if I just click the Save button.
Any ideas what I am doing wrong?

Based on what you have posted, this works fine for me.
http://jsfiddle.net/jFYN2/
triggerSave();
I would check to make sure you're including the right version of jQuery.
Also verify that you do not have any syntax issues in the [a big form with lots of inputs]

try this: http://jsfiddle.net/8rLGN/2/
$('a').click(function(e) {
e.preventDefault();
alert("triggerSave test alert");
$("#btnSave").trigger('click');
});

You need to make sure your function is available globally when calling functions from the onclick attribute, try:
triggerSave = function() {
alert("triggerSave test alert");
$("#formTabPatientTrackingPost").submit();
}
DEMO

As I worked on this more, I realized the problem was only occurring in Chrome. Everything worked in Firefox and IE (yeah, who would have guessed).
Then, that led me to this post: JQuery submit not working in Chrome
So, my final solution was to use an AJAX POST to get this working:
triggerSave = function () {
$.ajax({
url: '/Hospice/TabPatientTrackingPost',
type: 'POST',
dataType: 'json',
data: $('form#formTabPatientTrackingPost').serialize(),
success: function (data) {
console.log("success");
}
});
}
Thank you to everyone that helped! +1 for all the useful answers.

Related

Preventing form from going to action page also prevents data from being submitted

I created a form that submits its input to a database via a PHP page, and it works great, except for that I can't get the below script to work.
The intention is to submit the form but without actually jumping to createaccount.php. However, when I use the jQuery script below it prevents the form data from being submitted at all.
This code is from a project from a few years ago, and back then it worked fine. It seems it also works for everyone else on StackOverflow, so... confusing.
If it helps, I'm using Chrome. And I also tried using e instead of event, and instead of preventDefault() I also tried stopPropagation() and stopImmediatePropagation(), but these have the same results. Any ideas would be appreciated. Thanks for your time!
HTML
<form action="createaccount.php" method="post" id="form">
Username:<input type="text" name="username">
Password:<input type="password" name="password">
Email:<input type="email" name="email">
<input type="submit" name="submit" value="Submit">
</form>
JavaScript (jQuery)
$(document).ready(function() {
$("#form").on('submit', function(event){
event.preventDefault();
});
})
after event.preventDefault() add the following:
let form = document.getElementById('form')
form.submit()
and your form will be submitted
event.preventDefault(); Stops the form from submitting.
after that line you could do an $.ajax request
$(document).ready(function() {
$("#form").on('submit', function(event){
event.preventDefault();
$.ajax({
url: 'createaccount.php',
type: 'post',
data: $("form").serialize(),
success: function(data) {// do something if you want to give feedback}
})
});
})

tag <form> deletes part of code after ajax request?

I have a kind of form like this:
<form>
<input class="form-control" id="searchField" type="text">
<button type="submit" id="searchUserButton">SEARCH BUTTON</button>
</form>
When I press on SEARCH BUTTON (I'm using jquery to figure out when button is pressed), I call an ajax request and I print some information from json file in a html file BUT something strange happens:
I can't see the result! Otherwise if I remove the form tag (so I have just input and button element) everything is ok, I can see all the data...so what happens?! How should I do in the right way an ajax request with jquery (so when button is pressed)?
Jquery:
$("#searchUserButton").bind("click", function () {
searchData();
});
Ajax:
function searchData() {
$.ajax({
type: 'GET',
url: 'data/file.json',
dataType: 'json',
success: showData,
error: function () {
// FAIL
alert("ERROR!");
}
});
}
Change your click event to this:
$("#searchUserButton").bind("click", function (e) {
e.preventDefault();
searchData();
});
Your problem seems to be what I had assumed in the comments above.
A type="submit" button inside of a <form> will cause the form to process and the page to reload, whereas without <form> tags, this will not happen. By doing e.preventDefault();, you're instructing the button to not submit the form, and instead do your searchData() function.
Just change
<button type="submit" ...
to
<button type="button" ...
otherwise the form submits anyways and your page reloads regardless of your click handlers.

Updating a DIV on Submit without page refresh

I need refresh <myDiv> on my webpage when the Submit button is clicked.
I created an example of what I need. I want to display the user input text inside <myDiv> when the Submit button is clicked. Currently it's not showing anything. How can I fix this?
http://jsfiddle.net/NathaliaZeed/8dn5j/2/
Thanks everybody.
You need to use complete: not done:, then, assign your val1 variable to myDiv.
Working fiddle: http://jsfiddle.net/8dn5j/14/
See below:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
e.preventDefault();
$.ajax({
type: 'post',
data: {'val1':val1},
complete: function(jqXHR, textStatus){
$("#myDiv").html(val1);
}
});
});
The code in your example is good, except you forget to load the jQuery library.
If you make sure you include jQuery, the javascript code should work.
Also, your example should run on a PHP server. JSfiddle does not interpret PHP code, so that is also why the example does not work.
If you don't have a PHP server, Google for WAMP for Windows or MAMP for Mac.
Not Sure why you need php and ajax if there is only need to update the div on button click and not doing any server side processing for the need you described in question this code will work
<div class="myDiv" id="myDiv"></div>
<div class="sear">
<form action="" method="post">
Search Word: <br />
<input type="text" name="val1" id="val1" /><br />
<input type="button" value="Submit" id="btn" />
</form>
</div>
Js
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$("#myDiv").html(val1);
$("#myDiv").toggle("slow");
});
By the way, you don't need to use the form-tag..
I would do it this way:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$.ajax({
type: 'post',
data: {val1:val1},
success: function(data) {
$("#myDiv").text(data);
}
});
});
For me it doesn't do anything with Ajax request.
$('#btn').click(function(e) { e.preventDefault();
$("#myDiv").html($('#val1').val());
//..ajax stuff..
});

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

Process form data using jQuery

I'm currently using Prototype, but I'd like to rewrite this function to jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}
HTML example that goes with it:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result">&lt/div>
I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.
Thanks in advance for your help.
With this HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
You can do this with jQuery:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.
EDIT:
Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.
Use this and get rid of the onsubmit attribute in your HTML:
$(document).ready(function() {
$("#foo").submit(function() {
$.post($(this).attr("action"), $(this).serialize());
return false; // prevent actual browser submit
});
});
jQuery serialize method docs
You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...

Categories

Resources