Why does an ajax request not trigger validation - javascript

I have a form which is dynamically generated. Inside the form is a function that executes an AJAX request, and on success, modifies the value( sets it to an empty string) of a hidden field which is used for validation.( The hidden field is set to "required:true" )
However, on successful execution of the function, the hidden field does not trigger jQuery's validation and i am able to submit the form. The validation of the hidden field is only triggered when i trigger the validation of other fields intentionally, and the error message for the hidden field will appear, together with the other error message.
Function:
function DeleteImageDP(){
var itemid=$('#DisplayDeleteItemID').val();
var filepath=$('#DisplayDeleteFilePath').val();
var itempicid=$('#DisplayDeleteItemPicID').val();
var cfm=confirm("Confirm deletion of picture? ( Note: Picture wil be deleted permanently.");
if(cfm == true)
{
$.ajax({
url:"delete/deletedp.php",
type:"POST",
data:"ItemID="+itemid+"&FilePath="+filepath+"&ItemPicID="+itempicid,
success:function(){
alert("Image successfully deleted.");
$('#ImagePreviewDP').prop('src','').hide();
$('#ImagePreviewDPValidate').val('');
$('#DisplayDelete').hide();
},
error:function(){
alert("Image could not be deleted due to an error.");
}
});
return true;
}
else
{
return false;
}
};
Validation:
$('#ItemDetailsContainer').on('change',function(){
//Validation code .....
ImagePreviewDP:{
required:true
},
//More validation code....
});
Form(extract):
//Input and preview for Display Pic
echo"<div class='BizEditItemDetails' >";
//More code above
echo"<img id=ImagePreviewDP name=ImagePreviewDP class='ImagePreview' src=\"$dp\" > ";
echo"<input type='hidden' id='ImagePreviewDPValidate' name='ImagePreviewDPValidate' value=\"$dp\" >";
//More code below
echo"</div>";
Why doesn't setting the value of $("#ImagePreviewDP") to an empty string trigger the on.change?Also how would i get the validation to trigger upon successful execution of the function instead of it only triggering together with other errors?

Programatically setting an elements value with javascript never triggers the onchange event, you have to trigger it yourself
$.ajax({
url:"delete/deletedp.php",
type:"POST",
data:"ItemID="+itemid+"&FilePath="+filepath+"&ItemPicID="+itempicid,
success:function(){
alert("Image successfully deleted.");
$('#ImagePreviewDP').prop('src','').hide();
$('#ImagePreviewDPValidate').val('');
$('#DisplayDelete').hide();
$('#ItemDetailsContainer').trigger('change');
// ^^ trigger event handler
},
...........

Related

NO refresh the page when success ajax

I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case
$(document).ready(function() {
$('form').submit(function(e){
//e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
url:'{{ route('contracts.store') }}',
method: "POST",
data: form_data,
dataType: "json",
success: function(data) {
$("#mgsContract").text("Add successfully");
$("#hideForm").css("visibility", "visible");
$("#hideForm").css("height", "auto");
$("#result-contract-id").val(data.contract_obj);
},
error: function(data) {
$("#mgsContract").text("Something wrong");
}
})
});
});
Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload(). (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])
when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.
however in any case if you need to reload or go to specific location you can use window.location
window.location.href = "an address"; // going to specific location
window.location.reload(); //reloading the page
an ajax example is the following, in which a loop for showing all errors inside the form is specified.
$("#form_id").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
method: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (data) {
// code in the case of success
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
// code in the case of error
console.log(err.responseJSON);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="' + i + '"]');
el.removeClass('is-valid');
el.addClass('is-invalid');
var parent = el.parents('.form-group');
parent.append("<small class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
});
}
},
});
});

How do I submit this form without page reload?

So basically I have this interest slider plugin that calculates the repayments on a loan over a certain period of time - https://loancalc.000webhostapp.com/
But the problem I am having is submitting the form without reloading the page, currently you enter your name and email.
I have included this ajax script on line 1146 of slider.js but the slider continues to reload the page when submitting the form.
I am told it could be because i'm not enqueuing the script (for wordpress) properly.
jQuery('.qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else if (email == ""){
$("input#youremail").focus;
return false;
}
else{
jQuery.ajax({
type: "POST",
url: "quick-interest-slider.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}});
The full code is here (slider.js, quick-interest-slider.php, register.php) - https://github.com/Curnow93/quick-interest-slider/tree/master/quick-interest-slider
There's no submit event on the input. It should be on the form. Also, you need to pass the event to the callback function.
jQuery('.qis_form').on('submit', function(event) {
Also your selector doesn't select anything. I have updated it using the right selector.

AJAX POST success and error firing

I checked many posts here regarding same issue but nothing was working, and more or less it behaves like a glitch:
function onbtnclick(){
var user_email=$('#user_email').val();
var send_data = {email:user_email};
$.ajax({
type: 'POST',
url: 'someURL.php',
crossDomain: true,
data:send_data,
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
alert("Thank you for the mailing list");
},
error: function (responseData, textStatus, errorThrown) {
alert('Your email is already in our mailing list.');
console.log('log e:'+responseData);
console.log('log e:'+textStatus);
console.log('log e:'+errorThrown);
}
});
return false;
}
};
<form name="myform">
<input id="user_email" type="email" name="email" placeholder="Your Email Here" style="width:300px" required><br>
<br><button type="submit" class="leka-button button-style2 offer_button" onclick="onbtnclick()"><h5>SIGN UP</h5></button>
</form>
Simply i'm trying to alert the proper message if the user new to fire success or if he registered to fire error, I tried to remove dataType:'text' or adding 'json' and\with removing crossDomain attribute as well but all didn't give me the reason.
In case this was useful, here is where I fire the AJAX script.
You call the JavaScript when you click on a submit button.
The JavaScript runs. The Ajax request is prepared. The JavaScript finishes. The submit button's default behaviour submits the form. The page unloads. The Ajax request is canceled. The regular form submission takes place.
Get rid of the onclick attribute. Bind your event handlers with JavaScript instead.
$(function () {
var $form = $([name="myform"]); // `name` is obsolete for form elements, give it an ID instead
$form.on('submit', onbtnclick);
function onbtnclick(event) { // Give this function a better name
event.preventDefault(); // Don't submit the form normally
// Then put the rest of your existing code
}
});

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

How do I submit a form using jQuery after AJAX validation?

My form has one input which needs to be validated before submitting. After a successful validation I try to submit the form, but it doesn't submit.
My code looks like this:
$(document).ready(function() {
$("#myForm").submit(function () {
checkInputData();
return false; // to prevent default submit
});
});
The validation function:
function checkInputData() {
var id = $($("#id")).val(); // value, which needs to be validated
$.get("check.php?id=" + id,
function(result){
if(result == 1) {
//if the result is 1, need to submit
$("#myForm").unbind(); // to prevent recursion?
$("#myForm").submit(); // doesnt work
} else {
// dont submit, give some visual feedback, etc...
}
});
}
What am i doing wrong? Thanks.
You need to return the result from your AJAX validation request. You can do this by setting this check to being async: false, this means the checkInputData() will wait for the result to come back, and you can return it, controlling the submission of the form.
In your code it's not waiting for the $.get action to happen, and it appears to skip over meaning your code will always appear to return true; from the checkInputData() call. You don't need to return false in submit, if used as below.
I have used the $.ajax call in place of $.get because it allows you to control the async property, but it essentially does the same thing. You can read more about it here.
function checkInputData() {
var value = $("#id").val(); // Value to be validated
var passedValidation = false;
$.ajax("check.php?id=" + value, {
async: false,
success: function(result){
// Do whatever check of the server data you need here.
if(result == "1") {
// Good result, allow the submission
passedValidation = true;
} else {
// Show an error message
}
}
});
return passedValidation;
}
$(document).ready(function() {
$("#myForm").on("submit", function () {
return checkInputData();
});
});
I assume you have a button such as below, within your form with id myForm:
<input type="submit" value="Submit Form" />
It's not getting submitted may be because you are not returning 1 on successful validation for result in below if condition
if(result == 1) {
In check.php your output should be 1, like echo '1'; if input is valid. And make sure there is not any other output before or after it.
AMember is correct your always returning false, there are a few solution. One solution is for you to bind your validation to a button element or any element that will not submit the form.
HTML
<form id="myForm">
.
input elements
.
<button class= "submit" type="button" onclick="submit">Submit</button>
</form>
Document Ready
$(function()
{
var $submit = $(".submit");
$submit.click(function ()
{
checkInputData();
});
});
Validation Callback Function
function checkInputData()
{
var id = $('#id').val(); // value, which needs to be validated
$.get("check.php?id=" + id, function(result)
{
if(result == 1)
{
var $myForm = $("#myForm");
//if the result is 1 submit.
$myForm.submit();
}
else
{
// dont submit, give some visual feedback, etc...
}
});
}
$(document).ready(function() {
$("#myForm").submit(function (e) {
checkInputData();
//return false; // to prevent default submit <-- THIS IS WRONG
e.preventDefault(); //Try this :)
});
});
Returning false will prevent it from submitting in all cases.

Categories

Resources