Problems getting error message from AJAX - error on phone only - ajax

I have a basic web app - it is bug free for a while.
Occasionally - for what I expect is some network issue, I am unsure -
And only on a phone (Android / chrome) - The basic AJAX returns an error - but there is no value.
This is driving me a bit crazy - as I do not know how to debug an error that is blank.
Basic AJAX post:
$.post("<?php echo base_url(); ?>"+controller_G+"/"+Method_Param_G+"?"+Math.random()+"&SEARCH_STRING="+SEARCH_STRING_G, $("#"+Data_G).serialize(), function(data, status){
}).done(function(data){
// OWNER SEARCH VIA APP
if(data.indexOf("Search term found:") > -1){
// Happy Days! :)
}
}).fail(function(xhr, textStatus, errorThrown){
$("#ajax_message").modal();
$("#ajax_error_message_inner_text").html(textStatus+" -> "+errorThrown+" -> "+xhr.responseText);
});
The ajax_message produces "error -> -> undefined"
I can not replicate this error in my desktop browser chrome - all seems fine there.
Would also be helpful to know:
What are the typical ways to debug in android/iphone anyway?
And what are the typical errors with AJAX on a phone?
When I reload the page on the phone - normal operation returns for a while.
eventually another error returns.

Error event don`t have "xhr, status, error" params.
Try this:
$.ajax({
url: "<?php echo base_url(); ?>"+controller_G+"/"+Method_Param_G+"?"+Math.random(),
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
success:function(data){
// Happy days :)
},
error: function(jqXHR, exception){
var msg = "";
console.log(jqXHR);
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}});

Debug the app using chrome developer tools. Go through this Link
After setup the Ajax Error can then be seen in Network tab just like any other normal web debugging.

Related

Catching an AJAX error from a post request (422)

I have the following Ajax but it needs to handle a 422 error being returned (which means Out of Stock). I've tried a few ways around but it error's and refuses to POST stating:
Failed to load resource: the server responded with a status of 422 ()
I'm unsure how to catch the 422 error and return something to the user displaying that it's out of stock.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id='+ request.variant_id + '&quantity='+request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res){
Shopify.moveAlong();
},
error: function(){
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length){
Shopify.moveAlong()
}
}
});
}
else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
I've tried a few ways around but it error's and refuses to POST.
What I have understood is, you are seeing this error in Browser console. It cannot be prevented, but it does not mean that you request is not going through. The POST request is recieved by Shopify and a response with status 422 is sent, so that is treated as an error (Non 2xx response codes are treated as error).
To handle the error and display error message, adapt the code accordingly. Check updated code and code comments.
Shopify.moveAlong = function() {
// If we still have requests in the queue, let's process the next one.
if (Shopify.queue.length) {
var request = Shopify.queue.shift();
var data = 'id=' + request.variant_id + '&quantity=' + request.quantity_id;
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: data,
success: function(res) {
Shopify.moveAlong();
},
error: function(jqXHR, textStatus, errorThrown) {
// Check status code
if (jqXHR.status === 422) {
// display error wherever you want to
console.log(jqXHR.responseText);
}
// if it's not last one Move Along else update the cart number with the current quantity
if (Shopify.queue.length) {
Shopify.moveAlong()
}
}
});
} else {
window.location.href = "/cart";
}
};
Shopify.moveAlong();
AJAX Error Docs

Select2 Dynamic Select AJAX

I have the following AJAX script:
$.ajax({
type:'POST',
url: '/carrier/manifests/storeManifestShipments',
data: {
proNumber: proNumber,
bolNumber: bolNumber,
poNumber: poNumber,
SpecInst1: SpecInst1,
SpecInst2: SpecInst2,
SpecInst3: SpecInst3,
billTo: billTo,
originName: originName,
originAddress1: originAddress1,
originAddress2: originAddress2,
originCity: originCity,
originState: originState,
originZip: originZip,
consigneeName: consigneeName,
consigneeAddress1: consigneeAddress1,
consigneeAddress2: consigneeAddress2,
consigneeCity: consigneeCity,
consigneeState: consigneeState,
consigneeZip: consigneeZip,
shipmentProjectedDate: shipmentProjectedDate,
shipmentWeight: shipmentWeight,
shipmentPieceCount: shipmentPieceCount,
createdBy: '{{Auth::user()->id}}',
_token: $('input[name=_token]').val(),
dataType: 'json',
},
success: function(response) {
if(response !== undefined) {
$('#createShipment').modal('hide');
var shipmentSelect = $('.shipmentSelect');
var option = new Option(response.pro_number, response.id, true, true);
shipmentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
shipmentSelect.trigger({
type: 'select2:select',
params: {
data: response
}
});
console.log('success');
}else{
console.log('failed');
console.log(response);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
toastr.error('Validation error - Make sure all required fields are filled!', 'Error Alert', {timeOut: 5000});
console.log('Internal error: ' + jqXHR.responseText);
} else if (jqXHR.status == 422) {
toastr.error('Validation error - Make sure all required fields are filled!', 'Error Alert', {timeOut: 5000});
console.log('Internal error: ' + jqXHR.responseText);
} else {
console.log('Unexpected error.');
}
}
});
As you can see, within the success event I lay out something similar to how the example suggests it here: https://select2.org/programmatic-control/add-select-clear-items.
The problem is that it doesn't want to "select" the item from the select2 that is referenced (.shipmentSelect). It doesn't throw an error either, but nothing really happens. It does print the success message in the console.
The response is formatted as such:
id: 1
pro_number: 1234
name: person1
.....
So I'm curious if there is a different way of formatting it, but I believe the issue comes from the following lines:
shipmentSelect.trigger({
type: 'select2:select',
params: {
data: response
}
});
I believe I need to provide maybe something else besides the general response?
Thanks

Ajax call to another website

For some reason when I run this simple javascript snippet I get the message "Error! Status = 404 Message = error"
callPHP(1)
function callPHP(args)
{
$.ajax({
url: "http://lectiogroupgenerator.esy.es/index.php",
type: 'post',
data: { "json" : JSON.stringify(args) },
dataType: "json",
success: function (data)
{
if (data)
{
alert(data);
return data;
}
else
{
alert("Data is empty");
}
},
error: function (xhr)
{
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
return false;
}
My PHP file is just:
<?php
?>
I'm guessing 404 implicates that the php could not be found, but it does exist and I have no clue why it can't find it maybe it has something to do with me making a google chrome extension?
It might be because of the CORS issue. http://lectiogroupgenerator.esy.es/index.php doesn't allow cross origin HTTP requests.
If that's not the case try explicitly defining the website in the permissions in the manifest file to allow requests in and out to that website.
The problem was caused by the Same-origin policy, it was solved when I got an SSL certificate for my website.

Joomla mootools Ajax request always returning response text suffixed by '[]'

I am having a peculiar problem. I am trying to validate some card numbers using AJAX. Entire process goes fine and I am getting response from the script as expected. But I am not sure why all the response texts (even if it is an empty string) will show a [] suffixed to it when I alert it on my javascript. If I give an alert directly from the javascript, it shows fine. But all the responses from AJAX gives the above mentioned output.
Can anyone give me a clue why this is happening? I might have done something stupid in my code... but not able to figure out what... Any inputs will be highly appreciated.
Thanks in advance
EDIT:
Javascript Code:
var url = '" . JURI::base() . "index.php?option=<component>&view=<view>&format=raw&task=<task>';
var a = new Request({
url: url,
data: {
'".JUtility::getToken()."': 1
},
method: 'post',
onSuccess: function(responseText) {
alert(responseText);
},
onFailure: function(xhr) {
alert('Failed');
}
}).send();
PHP Script on view.raw.php
<?php echo "Here"; ?>
This script when run, will throw the alert message as "Here[]"
---- RENDERED JAVASCRIPT CODE ---
window.addEvent('domready',function() {
if($('addpluspayment')) {
$('addpluspayment').addEvent('click', function(event) {
bbCardNum = $('bbpluscardpayment').value;
if(bbCardNum.length <= 0) {
alert('Número de tarjeta no válida');
return;
}
totalAmountToCheck = parseFloat($('taqPaymentAmount').value);
var url = 'http://mydomain.com/index.php?option=com_bbpayment&view=taqcart&format=raw&task=bbcheckpoints';
var a = new Request({
url: url,
data: {'5df1de004436f241ef112345035bab51':1,'totalAmountToCheck':totalAmountToCheck,'bbCardNum':bbCardNum},
method: 'post',
onSuccess: function(responseText) {
if(responseText == 'othercategories[]') {
alert('Entradas encontradas en otras categorías');
}
else {
alert(responseText);
}
},
onFailure: function(xhr) {
alert('Failed');
}
}).send();
});
}
});
Here, the alerts - 'Número de tarjeta no válida', 'Entradas encontradas en otras categorías' and 'Failed' (which are directly thrown from the javascript) comes up without any problems.. but all responseText alerts suffix a [], even if the PHP script echos just 'Hello' (which will throw the alert as 'Hello[]')

jQuery Ajax Call, give offline/ "not able to connect" message

Yes, i have a normal ajax call that calls imback.php, that checks for new stuff if you have been blur for 50 sec.
Now if you disconnects from the internet, and when you get on focus, it will not be able to get imback.php.(i think its 404 error) So i would like to make a offline msg/timeout thing, so it alerts "You have no internet connection or something else went wrong".
How can i do that?
$.ajax({
url: 'imback.php',
success:function(msg) {
$('.NewStuffSinceActive').prepend(msg);
}
})
You can use the error callback for this:
$.ajax({
url: 'imback.php',
success: function(msg) {
$('.NewStuffSinceActive').prepend(msg);
},
error: function(xhr, status, error) {
alert("An error occured: " + error);
}
})

Resources