wrong ajax callback invoked using cordova - ajax

In my jqm app I make a POST using jQuery $.ajax sending and receiving json data. Everything is fine in the browser and on iPhone; on Android I noticed that when this server response is like this:
{ "code" : 500,
"errorMsg" : "bla bla bla",
"errors" : null,
"status" : "INTERNAL_SERVER_ERROR",
"success" : false
}
the ajax invokes the "error" callback and not the "success". This happens only on android and only if I include corova-2.0.0. js on the project. Any help?
I'm using cordova-2.0.0 with jqm 1.3.1 and jQuery 1.9.1
Here's my code:
var ajax = $.ajax({
type: "post",
url: url,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
timeout: 30000
});
var success = function (d) {
if(d.success==true && obj.success)
obj.success(d.data);
else
{
var msg = parseErrors(d);
console.log(msg);
//open page passing results
obj.msgBus.fire("RequestResult", {
callback: function(){ obj.msgBus.fire("Welcome");},
success: false,
text: msg
});
}
};
var error = function (xhr, status, e) {
console.log('error ajax url:[' + url + '] status:[' + status + '] error:[' + e + ']');
if (obj.error) {
if ((typeof e == 'string'))
obj.error({
statusText: e,
code: xhr.statusCode,
text: xhr.responseText
});
else {
e = $.extend(e, {
statusText: status
});
obj.error(e);
}
}
};
var complete = function () {
if (obj.complete) {
obj.complete();
}
};
var parseErrors = function(d){
console.log( d);
if(d.errors==null){
return d.errorMsg;
}
else
{
var res="";
for (var i=0;i< d.errors.length;i++){
res+= "{0}: {1} <br/>".format( d.errors[i].field, d.errors[i].errorMsg);
}
return res;
}
};
ajax.success(success).error(error).complete(complete);
where data is an object like this:
{
"date" : 1371679200000,
"idBeach" : "1",
"idStuff" : 3,
"idUser" : "8",
"numStuff" : 1
}

Try this, it works for me
$.ajax({
async: false,
type: "POST",
url: "Your_URL",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, object) {
alert(obj.Data);
});
},
error: function () {
alert("There was an error loading the feed");
}
});

Related

I can't pass the request value to controller laravel

Hi I'm new to Laravel and I'm having problem in passing the request properly in my controller which is a resource for update function I'm using Laravel 8. there is no error with the syntax it just return the request is empty. I paste my code for references.
my AJAX Request
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "PATCH",
data: {
'fullname' : 'albert'
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});
and here is controller
public function update(Request $request, $id)
{
return response()->json($request);
}
and here is my Route
Route::resource('companystructure', CompanyStructureController::class);
this is the return I receive from my controller
type: 'PATCH' does not exists on HTTP methods thus will not be recognized by Laravel.
Try this:
let url = '/companystructure/1';
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: url,
type: "POST", /// UPDATE
data: {
'fullname' : 'albert',
'_method': 'PATCH', /// UPDATE
},
processData: false,
contentType: false,
success: function(response) {
console.log(response);
//alert(response);
//location.reload();
},
error: function (xhr, ajaxOptions, thrownError) {
var error = $.parseJSON(xhr.responseText) || thrownError;
var errorMsg = error['message'] || thrownError;
var errorObj = error.errors || [];
if (errorObj) {
Object.keys(errorObj).forEach(function (key){
if (errorObj[key][0].length <= 1 ) {
errorMsg = errorMsg + '<br/>' + errorObj[key];
} else {
errorMsg = errorMsg + '<br/>' + errorObj[key][0];
}
});
}
md.showNotification(errorMsg, 'danger');
}
});

Updating Dygraph with ajax

I have below code which pull data from mysql using ajax json and draw Dygraph chart which it works fine but when my problem is updating the chart.
When I try to update the graph I am getting this error:
Uncaught ReferenceError: g is not defined
which is already defined
all these code are in document ready fucntion
// get data from server
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
if (test) {
document.addEventListener("mousewheel", function() {
lastClickedGraph = null;
}, false);
document.addEventListener("click", function() {
lastClickedGraph = null;
}, false);
if (response) {
var g = new Dygraph(document.getElementById("noroll"),
test, {
labels: ["Date", "Voltage", "Temp"],
digitsAfterDecimal: 3,
interactionModel: {
'mousedown': downV3,
'mousemove': moveV3,
'mouseup': upV3,
'click': clickV3,
'dblclick': referesh,
'mousewheel': scrollV3
}
}
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
// update Data every 2 second by pulling new data from mysql server
window.intervalId = setInterval(function() {
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
//console.log(test);
g.updateOptions({
'file': test
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
}, 2000); </pre>
//end update
In your setup, you define the graph with:
var g = new Dygraph(...
var limits the scope of g, so it's not accessible in your later call. Make the g variable available globally, or in a variable that you pass between functions.

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

How to use ajaxStart if $.ajax method is defined in a class?

I have created ajax method in one class in my js file. Below is enclosed for the reference
var ajaxcall =
{
SitePath: '',
data: '',
url: '',
callbackfunction: '',
fileElementId: '',
AjaxRequest: false,
callback: true,
async: false,
folder: '',
filename: '',
Call: function () {
if (ajaxcall.AjaxRequest == true) {
alert(ajaxcall.AjaxRequest);
return;
}
else {
try {
ajaxcall.AjaxRequest == true;
alert('b');
$.ajax({
type: "POST",
url: ajaxcall.url,
data: ajaxcall.data,
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: false,
success: function (data) {
if (ajaxcall.callback == true) {
ajaxcall.callbackfunction(data);
}
},
error: function (request, status, error) {
//alert("Exception Handling : \n" + request.responseText);
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
ajaxcall.AjaxRequest = false;
}
});
}
catch (e) {
ajaxcall.AjaxRequest == false;
// alert("Error Catch : " + e.Description + '\n' + 'Message: ' + e.Message);
}
}
},
AjaxFileUpload: function () {
$.ajaxFileUpload({
type: "POST",
url: "../GenericHandlers/FileUploader.ashx?path=" + ajaxcall.folder,
dataType: 'json',
async: false,
secureuri: false,
fileElementClass: ajaxcall.fileElementClass,
success: function (data) {
var data = data.toString();
ajaxcall.filename = data.substring(6, data.length - 7);
alert(ajaxcall.filename);
return true;
}
});
}
};
Now i want to show a div when ajax call starts and hide after finish.
So for that i have used
$(document).ready(function(
$('#Loading').ajaxStart(function () {
alert('a');
$('#Loading').show();
}).ajaxStop(function () {
$('#Loading').hide();
});
});
But when i call the ajax method (defined above in the class), control goes into ajax method first then in ajaxStart.
I don't know why it is happening. Please help.
Use the recommended global for these:
$.ajaxStart(function() {
$("#Loading").show();
});
$.ajaxComplete(function() {
$("#Loading").hide();
});
Try it this way attached to your Loading id element:
$("#Loading").ajaxStart(function() {
$(this).show();
});
$("#Loading").ajaxComplete(function() {
$(this).hide();
});
AjaxStart called when the http request start, not when the ajax method executes.

asp.net mvc 3 json does not work

This is my jquery with json
$('#btnVerificationOk').click(function () {
var verId = $('#trans_verification_id').val();
var verCode = $('#trans_verification_code').val();
$.ajax({
url: '/Profile/CompleteTransactions',
type: 'POST',
data: { },
dataType: 'json',
success: function (result) {
alert(result);
},
error: function () {
alert('ERROR ERROR !!!!!!!!!!!!');
}
});
});
And My C# method:
[Authorize]
[HttpPost]
private JsonResult CompleteTransactions()
{
return Json("Done");
}
Its always alerts 'ERROR ERROR !!!!!!!!!!!!' i tried debugging but CompleteTransactions method is not firing
And this is my second json which is bellow and works good
$('#btnTransfareOk').click(function () {
var userName = $('#transfare_username').val();
var amount = $('#transfare_amount').val();
if (userName == '' || amount == '') {
$('#transfare_error_list').html('Please fill boxes.');
} else {
$.ajax({
url: '/Profile/TranfareMoney',
type: 'POST',
data: { ToUsername: userName, Amount: amount },
dataType: 'json',
success: function (result) {
$('#transfare_error_list').html(result.text);
$('#trans_verification_id').val(result.id);
$('#transfare_username').val("");
$('#transfare_amount').val("");
},
error: function () {
$('#transfare_error_list').html('Oops... Error.');
}
});
}
});
I'm not 100% sure, but shouldn't you controller action handler be public ?

Resources