submit form through ajax doesn't work - javascript

I try to submit a form using ajax. Here is my code:
$BTN.click(function () {
$.ajax({
type: 'POST',
url: "/Record/Edit",
contentType: 'application/json',
data: JSON.stringify(data),
dataType: "json",
});
});
It works well. But i want to put a validation message to some inputs where the inputs need to be filled. I used has-value in the class. It validates the value when the form is being submitted. So I used this code to submit form. $('#frmEditCPRRecord').on("submit", function (e) { }); It did validates my form, but doesnt submit it.

Related

AJAX call being canceled when submit button is used [duplicate]

I am trying to perform an ajax call inside a form (a Drupal node edit form) , but it seems when performing the call, it submits the form for some reason. Here is a sample code:
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: {"text": jQuery("#edit-body").html()
},
success: function(result){
console.log(result);
}
});
I can replicate this just by executing it in the console, but I attach this to a button click function inside the form. Any tips on preventing the form from submitting, on a POST ajax call?
Here is the full code as requested
jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button" id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>');
jQuery("#proofread_bot-submit").click(function(event){
event.preventDefault();
jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");
jQuery.ajax({
type: "POST",
url: "proofread_bot/check",
dataType: "html",
data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
},
success: function(proofread_result){
jQuery("#proofread_bot-submit").after(proofread_result);
jQuery("#proofread_bot_throbber").remove();
}
});
});
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (isValid) {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
e.preventDefault();
return false;
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
If you are using a input type="submit" button, then you need to do a return false; at the end of the function to prevent it from submitting.
Another solution is to e.preventDefault() on the button click
$(".button").click(function(e){
e.preventDefault();
return false;
});
you can change submit button type to just a button type and add "onclick" event to that button.
input type="button" value="savebutton" onclick="return doThisOnClick();"
function doThisOnClick(){
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
}
I think this is most straightforward.

Validate Form preventing form submission

I am using asp.net MVC 5 and trying to validate form on submission. everything works fine until i added the below line of code to validate form using ajax call.
$('#signupform').validate({
submitHandler: function (form) {
$.ajax({
type: 'POST',
data: JSON.stringify({ type: "WhatsNew", code: $('#PrimaryCode').val() }),
url: '#Url.Action("CheckCode", "Home")',
dataType: 'json',
contentType: 'application/json'
})
.done(function (response) {
if (response == 'success') {
alert('success');
}
else {
alert('failed');
}
});
return false; // required to block normal submit since you used ajax
}
});
the above code simply blocking the submission of form.
You prevented submission by return false; in order to ajax-validate the form, but the form is not submitted after successful validation.
Add a form submit trigger inside .done();
if (response == 'success') {
// since validation is success, submit form here (e.g. YourForm.submit())
}
Possible walk through:
Before submitting the form inside .done(); make sure you remove/unbind validate from you form.
Follow this link: click here for another couple of ways.

Custom Ajax request with jQuery form validation

I want to validate a form with the jQuery form validation plugin but I was not able to send a custom Ajax request with the validation handler:
$('#headForm').validate(
{
//submitHandler: submit,
errorClass: "invalid",
rules: {
title: {maxlength: 50}
},
messages: {
title: {maxlength: 'Max 50 chars'}
}
});
My orginal submit handler looked like this:
$('#headForm').submit(function(event)
{
event.preventDefault();
$.ajax(
{
type: "PUT",
url: "/target",
data: $('#headForm').serialize(),
dataType: "json",
success: function()
{
alert("ok");
}
});
});
I tried to move it to a usual function and register it as a submitHandler in the validation block, but it didn't work.
function submit() { // impossible to pass the event!
$.ajax( ...
}
How can I combine jQuery validation with a custom Ajax request?
Possible form validation bug:
I've removed the validation code to see whether the submission works without it. And it did not unless I removed the link to jQuery form validation library! So it seems like validation is breaking jQuery core. Have I already said that I love dynamic typing ... ;-)
Did you define a parameter in the submit() function?
(I'm guessing that you didn't, and that could be why it didn't work)
I think you just need to specify the 'form' parameter, and then call serialize() on that parameter, as follows:
submitHandler: function(form) {
$.ajax({
type: "PUT",
url: "/target",
data: form.serialize(),
dataType: "json",
success: function()
{
alert('ok');
}
});
}
See the docs: http://docs.jquery.com/Plugins/Validation/validate#options

Combining jQuery Validate and ajax form submission

I have a simple form like
<form id="invite_form">
<input type="text" name="invite_email" id="invite_email" />
<textarea name="invite_message">Hello!</textarea>
<div id="send_div">
<span id="send_btn">Send</span>
</div>
</form>
My JS is as follows to submit the form via Ajax:
$('#send_btn').live('click', function(event){
event.preventDefault();
var form = $('#invite_form');
$.ajax({
url: '/invite',
type: "POST",
data: form.serialize(),
dataType: "html",
success: function(html) {
$('#send_div').html('Success!');
}
});
});
This works fine.
Now I would like to wrap a jQuery Validate function around this code to make sure [1] the email field is filled and [2] is valid email.
I am using Jorn's bassistance.de jQuery validation plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/.
Can anyone give a roadmap of how to tie the validation call to this ajax?
Thanks for helping, much appreciated.
Try this:
$('#send_btn').live('click', function(event){
event.preventDefault();
var form = $('#invite_form');
if(form.valid()) {
$.ajax({
url: '/invite',
type: "POST",
data: form.serialize(),
dataType: "html",
success: function(html) {
$('#send_div').html('Success!');
}
});
else {
; //do whatever if the form is not valid
}
});

jquery submit form and then show results in an existing div

I have a simple one text input form that when submitted, needs to fetch a php file (passing the inputs to the file) and then take the result (just a line of text) and place it in a div and fade that div into view.
Here is what I have now:
<form id=create method=POST action=create.php>
<input type=text name=url>
<input type="submit" value="Create" />
<div id=created></div>
What I need is the results of create.php?url=INPUT, to be dynamically loaded into the div called created.
I have the jquery form script, but I haven't been able to get it to work right. But I do have the library loaded (the file).
This code should do it. You don't need the Form plugin for something as simple as this:
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
This works also for file upload
$(document).on("submit", "form", function(event)
{
event.preventDefault();
var url=$(this).attr("action");
$.ajax({
url: url,
type: 'POST',
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
$('#created').html(data); //content loads here
},
error: function (xhr, desc, err)
{
console.log("error");
}
});
});
You must use AJAX to post the form if you don't want the page to be refreshed.
$('#create').submit(function () {
$.post('create.php', $('#create').serialize(), function (data, textStatus) {
$('#created').append(data);
});
return false;
});

Categories

Resources