Laravel Hiding Validation Errors Message with Ajax when is true - javascript

i have implement the validation errors message with ajax successfully, but when the previous input form is true, the previous error in that input form is not hiding. Anyone can help me to hide the previous error if input form is true?
This is my javascript code :
$.ajax({
url: `${window.url}/income`,
type: "POST",
data: {
_token: CSRF_TOKEN,
detail: arrValues,
data_contact_id,
total,
description,
invoice,
transaction_date,
to_account_id,
},
dataType: "JSON",
success: function (response) {
console.log(response);
if (response.status) {
Swal.fire({
icon: "success",
type: "success",
title: response.message,
showConfirmButton: true,
}).then((result) => {
window.location.href = `${window.url}/income`;
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
let fields = [
"data_contact_id",
"invoice",
"transaction_date",
"to_account_id",
"description",
];
fields.map((field) => {
$(`#${field}`).removeClass("is-invalid");
$(`.${field}-error`).html(``);
});
let errors = jqXHR.responseJSON.errors;
$.each(errors, function (key, value) {
$(`#${key}`).addClass("is-invalid");
$(`.${key}-error`).append(`
<span class="text-danger" style="font-size: 0.8rem">
${value.map((v) => "<strong>" + v + "</strong><br>")}
</span>
`);
console.log("Field : ", key);
});
Swal.fire({
icon: "error",
type: "error",
title: "Error!",
showConfirmButton: true,
});
},
});
In my controller i have return validation error json from Validator::make()
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()]);
}

$.ajax({
beforeSend: function(){
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();
},
complete: function(){
// Handle the complete event
}
error : function(){
// Handle the error event
}
// ......
});
$(`#${key}`) add class key_of_form
$(`.${key}-error`) add class error_of_key
before submit of form or beforeSend of ajax you need reset error messages same as :
$(".key_of_form").removeClass("is-invalid");
$(".error_of_key").empty();

Related

Set isConfirmed to true after timer runs out on SweetAlert2

I am using sweetalert2 when confirming an input from user. I am using a dialog with two buttons , confirm button and cancel button, also I added a timer. When submit button is clicked everything works fine ( ajax is called ) but when timer runs out I want the same result as confirm button. I have tried adding Swal.isConfirmed = true, result=true but didn't get desired one.
Swal.fire({
title: 'Дали сакате да ги зачувате промените?',
showDenyButton: true,
confirmButtonText: 'Зачувај',
confirmButtonColor: '#00CA4E',
denyButtonText: `Откажи`,
denyButtonColor: '#FF605C',
html: '<strong></strong> секунди.<br/>',
timer: 3000,
didOpen: () => {
timerInterval = setInterval(() => {
Swal.getHtmlContainer().querySelector('strong')
.textContent = (Swal.getTimerLeft() / 1000)
.toFixed(0)
}, 100)
},
willClose: () => {
clearInterval(timerInterval);
Swal.isConfirmed = true;
}
}).then((result) => {
/* Read more about isConfirmed, isDenied below */
if (result.isConfirmed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("SubstitutionAddPlayers","Scoreboard")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
} else if (result.isDenied) {
//Swal.fire('Changes are not saved', '', 'info')
}
})
I want when timer runs out, result in then to be true and ajax call to be executed.
If a SWAL2 is dismissed from a timer, you can use result.isDismissed the same way as result.isConfirmed in any conditional statement.
if (result.isDismissed) {
// .. code if timer is dismissed
}
if (result.isConfirmed) {
// .. code if timer is confirmed
}
This is the result response if you remove all buttons and let it be:
{isConfirmed: false, isDenied: false, isDismissed: true, dismiss: 'timer'}
So try adding
if (result.isDismissed) {
console.log('confirmed');
$.ajax({
type: "POST",
url: "#Url.Action("
SubstitutionAddPlayers ","
Scoreboard ")",
data: {
jsonSubstitution: substitution,
},
success: function(data) {
},
error: function(req, status, error) {
console.log(msg);
}
})
//Swal.fire('Saved!', '', 'success' )
}
Note: Consider disabling outside click on that specific one maybe.

AJAX not giving me a responseText for 500 requests?

I have a function attached to the error on my ajax but it wont show me any error messages for 500 response codes? I display the error message with xhr.responseText but its returning an empty string, can anyone tell me why?
$.ajax({
type: "PUT",
url: "/ajax/account/create_key",
data: { key_id: document.getElementById('account-key-value').value, expires_at: document.getElementById('account-key-expires').value },
success: function(result) {
// close modal
swal({
title: "That was a success!",
text: 'Your account key has been created.',
icon: "success",
button: "Okay!",
});
document.getElementById('account-keys-content').innerHTML = result;
},
error: function(xhr, ajaxOptions, thrownError) {
if(xhr.status == 400) {
swal({
title: "Opps!",
text: xhr.responseText,
icon: "error",
button: "Okay!",
});
}
else {
swal({
title: "Opps, something went wrong!",
text: xhr.responseText,
icon: "error",
button: "Okay!",
});
}
}
});

JQuery UI Dialog and duplicated form elements

I am using a JQuery UI Dialog and the ajax submit plugin from malsup.com.
The issue is that the UI Dialog (I believe that is the culprit) is duplicating the fields of the form. It would not be such an issue except that this form is for uploading multiple files. The form uses a DataTable.
Apart from the duplicating fields the process is fine.
I am not re-using the dialog, which would duplicate the fields (see this )
The page gets the form and submits it through ajax: here is the code:
function smxTableDialogForm ( aURL, tableId, row ) {
var lData = "";
var lURL = aURL.split("?");
var lDialog;
if (lURL.length == 2){
lData = lURL[1];
lURL = lURL[0]
};
$.ajax({
type: "POST",
url: lURL,
data: lData,
dataType: "json"
}).
done( function(response){
if ( response.success ){
lDialog = $("<div></div>").dialog( {
height: "auto",
maxHeight: 800,
width: 750,
autoOpen: false,
buttons: [
{ text: "Save",
icons: {primary: "ui-icon-check" },
click: function () {
smxAjaxSubmit(response.formid);
$(this).dialog("close");
}
},
{ text: "Cancel",
icons: {primary: "ui-icon-close"},
click: function() {
$(this).dialog("close");
}
}],
close: function (event, ui) {
$(this).remove();
},
resizable: false,
modal: true
});
lDialog.html(response.content);
lDialog.dialog("open");
}
else {
$.alert(response.message, response.title);
};
}).
fail( function(jqXHR, textStatus, errorThrown) {
$.alert("Sorry, no info to display.", "oops");
});
};
function smxAjaxSubmit (aFormId) {
$("#" + aFormId).ajaxSubmit({
dataType: "json",
beforeSend: function(){
$.blockUI({ message: '<h3><img src="/sysimages/ajaxloader.gif" /> Just a moment...</hr>' });
},
complete: function(){
$.unblockUI();
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
$.alert("Problem. status: " + textStatus + "; error: " + errorThrown, "oops");
}
});
};
Any ideas gratefully received. Thanks.

unable to send data via this.serialize

I am using following function to validate and send data to the php server:
$(document).ready(function () {
$(function() {
// Setup form validation on the #register-form element
$("#register_form").validate({
// Specify the validation rules
rules: {
register_username: "required",
register_password: "required",
register_email: {
required: true,
email: true
},
register_confirm_password: {
required: true,
equalTo: '#register_password'
},
},
// Specify the validation error messages
messages: {
register_username: "Please enter your username",
register_password: "Please enter your password",
register_confirm_password: {
required: "Please provide a password",
equalTo:"Please enter password same as above."
},
register_email: "Please enter a valid email address",
},
submitHandler: function(form) {
var pdata = $(this).serialize();
alert(pdata);
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(this).serialize(),
dataType : 'json',
success: function(data) {
if (data.success){
console.log("Form is submitted.data is" + data.success);
$.each(data, function() {
$.each(this, function(k, v) {
console.log("key; " + k);
console.log("value; " + v);
});
});
}
else
{
console.log("The data returned is:" + data.success);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
return false;
},
});
});
});
All the validation works, but the issue is with the line:
var pdata = $(this).serialize();
I am getting empty pdata:
alert(pdata);
I don't know why the data is not serialized here. Please help me to solve this.
Don't serialize $( this )
Try serializing the form instead.
$( "#register_form" ).serialize();
$(this) isn't what you think it is anymore. It's not #register_form, but instead the submitHandler function.
If you do console.log(pdata) you should see the function definition in your console.
The scope of the submitHandler function is not the form element, so this is not pointing to the element you require. It does however provide you with a parameter, which you've named form, that you can use instead, like this:
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'http://localhost/quiz/index.php/signin',
data: $(form).serialize(),
// your code...

Cancel button not working in sweetalert

when i am clicking on cancel button in sweetalert.js it still running the AJAX call i want to terminate the process on cancel button.
swal({
title: " Asking price for "+askData[0]+"?",
text: "If you are sure press OK or edit this text",
type: "input",
inputType: "text",
inputValue: "Hello "+askData[1]+", I am interested in buying your "+askData[0]+" of Variety :"+askData[3]+". Please update the Price!",
showCancelButton: true,
closeOnCancelButton:true,
closeOnConfirm: false,
showLoaderOnConfirm: true
}, function(inputValue) {
if (inputValue === "") {
swal.showInputError("Please write something !");
return false;
}
$.ajax({
url: urlEnq,
type: "GET"
});
$.ajax({
url: 'saveUserMessage',
type: "POST",
data: {fieldUserId:fieldUserId,filedUserCompanyId:filedUserCompanyId,message:inputValue},
success: function(data)
{
swal("Done!", "Your message has been successfully sent.", "success");
}
})
.error(function(data) {
swal.showInputError("Please write something !");
});
});
});
});

Categories

Resources