AJAX not giving me a responseText for 500 requests? - javascript

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!",
});
}
}
});

Related

How to check if ajax jquery is in progress or loading in a function

I have a function named "loadloker", that contains ajax jquery function. i want to ask how to check is ajax in this function is running due to already invoked before.
These are the code block:
function loadLoker(id, e){
if(id==currentLokerId) return;
var url = "{{ route('daftarloker.show', ':id') }}"
url = url.replace(':id', id);
$.ajax({
type: 'POST',
url: url,
success: function(res) {
if(res.success){
let loker = res.data.data;
currentLokerId = loker.lokerid;
$(e).parents('.card').addClass("border border-info border-3");
$('#lokerPerusahaanNama').text(loker.perusahaan.nama);
$('#lokerdetailContainer').show();
swal.close()
}else{
swal({
title: "Gagal!",
text: "Gagal mendapatkan data dari server",
icon: "warning",
button: "Ok!",
type: "warning",
});
}
$('#lokerdetailloadingContainer').hide();
},
error: function (request, status, error) {
swal("Gagal!", "Gagal mendapatkan data dari server", "error");
}
});
}
I expected to exit from this function if ajax in this function is still running,
You can check $.active property
function checkAjaxStatus() {
if ($.active > 0) {
console.log("request is in progress");
} else {
console.log("No request");
}
}

Laravel Hiding Validation Errors Message with Ajax when is true

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();

Receiving 66:285 Uncaught TypeError: Cannot read property 'then' of undefined

I have designed a simple ajax request for deleting a file from database in mvc. for that i am using javascritp ajax with swal prompt for delete. But it is not working. I am getting .then undefined error.
Here is the code--
$(".btnDel").click(function () {
var NewFileName = $(this).val();
var id =#Model.Pd.Id;
console.log(id);
console.log(NewFileName);
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "#Url.Content("~/ManageProducts/DeleteExistingFile")/",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
});
Thanks for the edit. The snippet below defines id and NewFileName for testing and uses example.com for the POST - if you try to delete the file you get the "oops" message. In other respects it should be the same as the code in the post.
const id = "example_id";
const NewFileName = "example.pdf";
//**********************************
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: [
'No, cancel it!',
'Yes, I am sure!'
],
dangerMode: true,
})
.then(function (isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "https:www.example.com/delete",
data: { 'id': id, 'fileName': NewFileName },
success: function (data) {
swal("Message.", data, "success");
location.reload();
},
error: function () {
swal("", "Something went wrong", "error");
}
});
}
else
{
swal("Cancelled", "Your imaginary file is safe :)", "error");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
I am at a loss to explain why the snippet works but running it in VS says swal returns undefined. I would test the code in a browser first to see if it still errors.
Disclaimer: this is not the answer. . . yet. I am happy to delete it if anyone solves the mystery.

Sencha ExtJs button - password Recovery email not working

This displays a confirmation message, but when I hit yes, it gives this error:
HTTP Status 415 -
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
{
xtype: 'button',
id: 'passwordRecoveryButton',
text: 'Reset Password',
style: 'border-color: red',
listeners: {
click: function(button, event){
var form = Ext.getCmp('gmiUserDetailsPanel').getForm();
var currentRecord = form.getRecord();
var emailId = currentRecord.get('emailId');
Ext.Msg.show({
title:'Password Recovery',
msg: 'Are you sure you want to send a password recovery email to ' + emailId +'?',
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION,
fn: function(btn) {
if (btn === 'yes') {
Ext.Ajax.request({
url: 'admin/passwordRecovery.htm',
jsonData : emailId,
method: 'POST',
success: function(response){
Ext.Msg.show({
msg: 'Email successfully sent to ' + emailId +'.',
})
},
failure: function(response){
Ext.Msg.show({
modal : true,
title : 'Unable to send email!',
msg : 'Unable to send email to : '+emailId+', please contact support team.',
icon : Ext.Msg.ERROR,
buttons: Ext.Msg.OK
});
}
});
}
}
});
}
}
},
},
I am attempting to pass the information of the current record (or just the email) and this is in the java controller:
#RequestMapping(value = "/passwordRecovery", method = RequestMethod.POST)
#Secured("ADMIN")
public
#ResponseBody
UserOperationResponse PasswordRecoveryEmail(Model model, HttpServletRequest request, #RequestBody UserOperationRequest userOperationRequest) throws UnsupportedEncodingException, MessagingException {
UserOperationResponse userOperationResponse = new UserOperationResponse();
[...]

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