Stop jQuery Ajax Success from preventing form submit - javascript

I am using jQuery validate with remote to check if an email address exists. Don't ask me why but I need it to redirect to a new page IF a match is found in the database (false), otherwise they should be able to use the form normally.
This code works perfect EXCEPT: if it returns true (meaning it didn't redirect) the form submit button doesn't do anything. I don't see any attributes assigned like disabled, but the form submission is defintely prevented. If I don't type anything in the email input, it will let me click the button.
rules: {
fullname: "required",
email: {
required: true,
email: true,
remote: {
url: "validate-email.php",
type: "post",
success: function(response) {
if(response === false){
window.location.href = 'new-page.html';
}
},
},
},
},
once I remove the success: section, form submission works normally so obviously it has something to do with what I did in there... Thank you in advance for your help!

Not sure if this is the best solution, but I was able to fix it by using this:
remote: {
url: "validate-email.php",
type: "post",
complete: function(data) {
if(data.responseText == "false"){
window.location.href = 'new-page.php';
}else{
return response;
}
},
Thank you for your help!

Related

Follow the ASP.NET ActionResult after Ajax call

A controller returns an ActionResult, i.e.:
public async Task<ActionResult> Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// do something
return RedirectToAction("Index", "Orders", null });
}
this works fine is I use an ActionLink in the view.
But the actual call is done via Ajax:
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
with the:
$("html").html(response);
line I'm trying to follow the returned html page.
It doesn't work: the html is rendered wrong (layout and colors are different) and even the address is not correct (of course it remains on the current page, instead to follow the Controller path).
I'm not sure if this is possible to do in jQuery.
Why I use an Ajax call instead of the ActionLink? Because I need to wait a confirm by the user:
$("#btnCancel").click(function () {
event.preventDefault();
swal({
title: "#Resources.MsgCancelOrderTitle",
text: "#Resources.MsgCancelOrderText",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "#Resources.MsgCancelOrderConfirm",
cancelButtonText: "#Resources.MsgCancelOrderCancel",
closeOnConfirm: false,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
swal({
title: "#Resources.MsgCancelOrderSuccessTitle",
text: "#Resources.MsgCancelOrderSuccessText",
type: "success"
},
function () {
$.ajax({
url: "/Orders/Delete",
cache: false,
data: { id: $("#btnCancel").data("id") }
}).done(function (response) {
$("html").html(response);
});
});
}
});
});
If you want to redirect to another view, then don't bother with ajax, it defeats the entire purpose of it. Generally an ajax call returns either some data (JSON or XML) or a small snippet of HTML which is designed to fit somewhere within the page which made the ajax call (generally implemented in MVC as a Partial View).
If you need the redirect, then do it like this:
Once the user confirms their choice via the alert box, then if the request needed uses the GET method (like your example) then simply a call to window.location.href with the appropriate URL will do it. If it was using POST, then normally there'd be a HTML form you could instruct to submit itself.

Jquery form validation before Ajax request

I have gone through other threads and used one for reference but still I am not able to find the solution.
My question is:
I am calling a function on button click now that function has validation after validation I am trying to post data with ajax request in submit handler, problem is my fields are getting verified but Ajax request is not invoked.
<input type="button" value="Register" id="registerP" onclick="registerPatient()" class="form-control input-sm btn-success ">
function registerPatient(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: "patientName=" + patientName,
success: function(response){},
error: function(e){}
});
}
});
}
However if I am not using validation and calling Ajax directly i am able to post the data. Please suggest where I am going Wrong.
You can try like this which call jquery form validation and check if validated:
$(document).ready(function(){
$("#patientRegistration").validate({
rules: {
patientName: {
required: true,
textOnly: true
},
},
messages: {
patientName: {
required: "Please enter the full name",
},
}
});
});
function registerPatient(){
var IsValid=$("#patientRegistration").valid();
if(IsValid){
var patientName=""; //value for patient name
$.ajax({
type: "POST",
url: "/LoginMavenSpringMVC/appointment/savePatient",
data: {"patientName": patientName},
success: function(response){},
error: function(e){}
});
}
}
Change your data syntax of ajax to this.
data: {patientName:patientName},
Make sure you have a parameter on catching method of the same name "patientName" to invoke its post from page on post.
This should work.
Also check if you get a patientName paramater value in your post. To do so first check by "alert" and pass the patientName parameter. You will know what you are getting and why post is not happening.

How to pass MVC view model into AJAX call with AntiForgeryToken

The code below is working for me, but I'm trying to find a way to read all values from the form instead of having to re-create the view model in JavaScript (vm is the name of the parameter of the object).
I tried to serialize the form and pass it in, but maybe my syntax is incorrect.
Any suggestions?
$.ajax({
type: "POST",
dataType: "json",
url: "/post-details-save",
data: addAntiForgeryToken({
vm: ({
Id: $("#PostImageDetails_Id").val(),
Title: $("#PostImageDetails_Title").val(),
Description: $("#PostImageDetails_Description").val(),
CopyrightOwner: $("#PostImageDetails_CopyrightOwner").val(),
CopyrightUrl: $("#PostImageDetails_CopyrightUrl").val(),
SourceName: $("#PostImageDetails_SourceName").val(),
SourceUrl: $("#PostImageDetails_SourceUrl").val(),
SourceLicenseType: $("#PostImageDetails_SourceLicenseType").val()
})
}),
success: postDetailsSaveSuccess,
error: postDetailsSaveError
});
Confirm Form Setup
#using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { #id = "formID" }))
I have done similar stuff with submitting forms in partial views.
Basically, you need to confirm that your html form is set up correctly:
The AntiForgeryToken
#Html.AntiForgeryToken()
Data Fields
Could look something like the following with the name attribute being important.
<input type="hidden" name="ApproveUserID" id="ApproveUserID" value="#Model.ApproveUserID" />
AJAX The Form
If your form is set up correctly like explained above, you will be able to submit the data via AJAX with something similar to the JS below.
var form = $("#formID");
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(), // data to be submitted
success: function (response) {
if (response == "Success") {
//DO SUCCESS STUFF
} else
{
//DO FAILURE STUFF
}
},
error: function () {
//DO ERROR STUFF
}
});
Pro Tip:
You can always expand the data you send by placing
var formData = form.serialize();
Into a variable and expanding it from there.
Good Luck.

Validate and submit form with no page refresh

I'm using jQuery validation and processing the form via ajax so I can avoid a page refresh. The problem I am running into is that I can't figure out where to place the ajax code in the validation function so that the form won't send data until it's been validated.
For example:
$('#ticket_purchasing').validate({ // initialize the plugin
rules: {
firstname: {
required: true
},
lastname: {
required: true
},
phone: {
required: true,
digits: true,
},
email: {
required: true,
email: true
},
address: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
invalidHandler: function (event, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
var message = "All fields in red must be filled*";
$("div.error-message span").html(message);
$("div.error-message").show();
} else {
$("div.error-message").hide();
}
},
submitHandler: function (form) { // for demo
// Do stuff here
}
});
$('form#ticket_purchasing').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'ticket-purchase.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
// $('#sponsorship_request').slideUp();
// $('#ticket_purchasing').hide();
// $('.seats-form').fadeIn(1000);
},
error:function(data){
$("ticket_purchasing .error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
// $('#form2').show();
});
As you can see above I have both functions separated from each other, and because of this the form is submitting the data (which emails the information) even though it's not been validated yet. I tried using form.submit(); as show in the validator documentation, and putting the ajax code in there, but it was a no go with errors I couldn't solve.
Advice? I'm probably going at this all wrong haha.
Edit: Just added html for the form: https://gist.github.com/adrianrodriguez/26b6beee8bf5ba85a8ce
To be clear, the form works fine without the validation portion, meaning I can submit and collect the data without a page refresh without the use of the validation plugin.
Remove your $.ajax call as the actual form submission should happen after validation in the validate.submitHandler.
$('form#ticket_purchasing').validate({
//validation rules here
//invalid handler goes here
submitHandler: function(form) {
$.post('ticket-purchase.php', $('#ticket_purchasing').serialize(), successCallback());
}
});
BTW, changed your $.ajax to a $.post
Thanks for everyone's help. I eventually realized that I was going at it all wrong and found this answer:
submitHandler: function (form) { // for demo
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(data) {
console.log(data);
// Do stuff here
//$('#ticket_purchasing').hide();
//$('.seats-form').fadeIn(1000);
}
});
return false; // kill page refresh
}
Instead of going the traditional way of the ajax submit I just had to use the "form" parameter already provided from jquery.validation.js and then grab data from its attributes.
Thanks for everyones help!
$( "#target" ).submit(function( event ) {
});
between this.

How do I define the value of an input for a remote check of existing values (username)?

This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D

Categories