Report user errors in jQGrid - javascript

I have a jqgrid table querying a MySQL DBMS through an apache2 web server via XML.
Sometimes whenever the DB server shuts down or the server side program encounters
some kind of crashes the jqgrid just freezes down waiting for the XML data to arrive.
In this kind of situation, I would be preferable to make the jqgrid user aware of this matter and thus display a gentle message describing the type of the annomaly.
I was wondering is there any jqgrid option specific for this kind of situation
I'm using:
jquery-1.3.2
jquery-ui-1.7.2
jquery.jqGrid-3.5.3
Thanks,

If for the jqgrid you are using the function datatype with jQuery.agax then place your logic in the error handler. The only problem with this is that you manually have to populate the grid and you don't get the "Loading" hint, though you can create one.
This sample was taken from the usual pattern that I use when calling ASP.NET WCF services, my results object contains int properties for the pager and a rows collection, this is defined in myGrid.setGridParams.
datatype: function(postdata) {
$.ajax({
type: "POST",
url: 'SomeService.svc/SomeGetMethod',
data: JSON.stringify(postdata),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(res) {
myGrid.clearGridData();
for (var i = 0; i < res.d.rows.length; i++) {
myGrid.addRowData(i + 1, res.d.rows[i]);
}
myGrid.setGridParam({
page: postdata.page,
lastpage: res.d.total,
records: res.d.records,
total: res.d.total
});
myGrid.each(function() {
if (this.grid) this.updatepager();
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Code to handle error.
}
});
},

I answered a similar question regarding the reporting of (server side) errors with a jqgrid.
How can I get JQGrid to recognize server sent Errors?

You can use the loadError event in jqGrid definition (see documentation). E.g.:
//Catch errors
loadError = function(xhr, textStatus, errorThrown) {
var error_msg = xhr.responseText
var msg = "Some errors occurred during processing:"
msg += '\n\n' + error_msg
alert(msg)
}

Related

Why can't my ajax get request find my handler route when I add arguments?

I am building a web app that displays data about flowers that is stored in my local server running bottle.
My front end is html, js with ajax;
My back end is python with bottle
In the browser there is an empty div in which the data is to be displayed.
Below it there is a row of images. When the user clicks on an image the data should display in the div above.
I tried using $.ajax instead of $.get, and I'm getting the same result.
This is my event listener in js:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
This is my handler for this request:
#get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(data is an array of dictionaries, each containing data of a single flower)
I am getting a 404 error (the function get_flower_desc is not executed at all) that possibly is happening because of the argument, because whenever I use a a function with no parameters and pass in no arguments I am getting the result that I'm expecting.
I found that I had to formulate an AJAX request quite precisely to get it to work well with Bottle in a similar scenario.
Here is an example with a GET request. You could attach this function to the event handler or move it directly to the event handler.
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
However, I found better results using a POST request from AJAX instead.
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
For the POST request, the backend in Bottle should look like this.
#post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
Make sure your data is valid JSON and that the database code you have is working correctly.
These solutions using AJAX with Bottle worked well for me.

JQuery ajax method returning error during POST on Chrome

I have a web application written in ASP.NET MVC 4. Client side richly uses JQuery to perform requests to save and retrieve data, during the user experience. In certain moments the user can change some data and click a button-like link to save it. For architecture/performance/requirements restrictions, this process is made in two steps:
A POST request is sent to the server to a given URL (which will fire a certain action of a certain controller), containing a JSON object;
On the first POST success a timer is set to run a second POST to the same server, but different URL (another action in the same controller), with no content at all.
The second POST will just start a complementary process and conclude what was started by the first one. However, it never gets the server. The $.ajax method fires the error handler.
A simplified version of the first request code is
$.ajax({
url: self.opcoes.urlCreate,
type: "POST",
data: JSON.stringify(lancamento),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
self.LancarDia(250);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Não foi possível incluir o lançamento. O servidor retornou\n" +
ajaxErrorMessage(jqXHR, textStatus, errorThrown));
}
});
The method LancarDia() receives the miliseconds amount to set the timer for the second request, so the idea is to wait 250 miliseconds and then send the second request. The LancarDia() code is:
MyClass.prototype.LancarDia = function (milisegundos) {
var self = this;
if (milisegundos) {
if (self.timerLancarDia)
clearTimeout(self.timerLancarDia);
self.timerLancarDia = setTimeout(function () {
self.LancarDia();
self.timerLancarDia = undefined;
}, milisegundos);
return;
}
$.ajax({
url: self.opcoes.urlLancarDia + self._dataAtual.format("MM/dd/yyyy"),
type: "POST",
success: function (data) {
if (self.opcoes.onLancou)
self.opcoes.onLancou(self._dataAtual);
},
error: function (jqXHR, textStatus, errorThrown) {
var mensagem = "Não foi possível atualizar o MUMPS. Motivo:\n" +
ajaxErrorMessage(jqXHR, textStatus, errorThrown);
alert(mensagem);
}
});
}
Notice that the first POST always work and the second fails many times but not always. When it fails what I get is:
jqXHR.status == 0
jqXHR.readystate == 0
textStatus == "error"
errorThrown == ""
In its first version, the code didn´t use any timers. On the success of the first POST the second was immediatly sent. Changing to the current implementation was reported to reduce the frequency of the problem, but it still happens.
Only Chrome shows this problem, FireFox and IE run clean.
Have anyone faced and solved this problem?
Thanks in advance
You mention the second POST never gets sent to the server, how are you verifying this? It sounds more like a race condition where the second request is being sent before the server is ready for it (e.g. it is still doing something that was started by the first request).
After a long study, our infrastructure staff figured out that the problem was caused by the caching policy of the browser (Chrome) and the caching policy configured in the web server (IIS 7).
After configuring IIS to add no-cache in the cache-control response header, the problem disapeared.

.Next To remove limitation on data send using JSONP

Can we remove the limitation on data send using JSONP. Below is my code. What i am trying to do is to pass 3000 characters(actuallly a image which is converted to base64 data) at a time to service(serviceCall.ashx). As my data is large up to 30,000-40,000 characters i am dividing it in packets(3000 each ) and then sending it. Is there any way i can send this complete data in one go. Reason for switching to JSONP is to avoid the pop up on IE which says 'This page is accessing info that is not.....'. I know as JSONP uses GET method there would obviously a data limitation but is there any way to work around this problem.
$.ajax({
type: "GET",
url: 'http://sys108/restnew1/serviceCall.ashx',
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
async: false,
data: {
datachunk: imgdatachunk,
packetlen: imgdatachunk.length,
imagekey: imageid
},
success: function (data) {},
error: function (jqXHR, textStatus, errorThrown) {
if (window.console)
console.log("Error... " + textStatus + " " + errorThrown);
}
});
No, it's not possible to send a GET request of that length in a more-or-less reliable way: actually, it depends both on how the web server is set up and what client (= browser) is used by someone who works with your application.
So I'd suggest looking for alternative (to JSONP) solutions - like CORS, for example.

Unable to retrieve particular JSON objects using jQuery

I try to retrieve a JSON object with jQuery from a server. Some properties of this object are arrays. When these arrays are not empty, I'm able to process my object. But when I retrieve a JSON like this one :
{"Id":144,"Identifier":"4000011","ContractId":115,"ContractName":"Test4","Meters":[],"Scans":[]}
where "Meters" and "Scans" are empty, jQuery raises an error... I query my server with this code :
$("#test").click(function () {
$.ajax({
type: "GET",
url: "/Gateway/GetDetails/144",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
...
},
error: function (jqXHR, textStatus, errorThrown) {
...
}
});
In the error handler, I can see my JSON object in the responseText property of the parameter "jqXHR". Did you encounter this problem ?
Thanks in advance !
The JSON you've supplied is valid (as confirmed by the JSON Lint tool); is it possible that the Server you are querying is returning an HTTP Error Status Code, or that an internal error is happening on the server side. You can confirm this by using a debugging proxy like Firebug, Chrome Developer tools.
I answer my own question... First I tested only with Internet Explorer 9; with an other browser, all worked as expected. After I cleared the Internet Explorer cache, the problem disappeared.

Unable to get a simple jQuery.Ajax call to work

I'm pretty new to the web-dev world, and I'm having a bear of a time getting a simple jQuery.ajax call to work. Here is the call:
var url = "http://client.the_url.com/get_account_data.php";
$.ajax({
url: url,
dataType: 'json',
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:function (xhr, ajaxOptions, error){
alert("Error");
}
});
I can copy and paste the url into a browser and it renders what I would expect:
{
"id":"Level 3.xpusdscah",
"type":"Level 3",
"name":"xpusdscah",
"total":0,
"in":0,
"out":0
}
Instead, I get the Error alert every time. :/.
The php script I'm hitting starts with the header:
header('Content-type: application/json');
I was trying to pass params to the php script, but now I'm not even doing that. I would think this should be a 'no brainer', but if it is, then I have no brain. I'm trying to figure out how to use wireshark right now, but should I really need to use wireshark to debug a call that is as simple as it gets to a php file?
Can anyone help me? What I'm really hoping for is a "Well duh, you didn't do (insert obvious solution here)!
Thanks in advance,
Fledgling web developer
First, your callback function isn't helpful. It just shows the text "Error" every time. You want to actually display what the error is, like this:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(resultsData){
resultsDataString = JSON.stringify(resultsData, null, 4);
alert("We're finally making the call.");
},
error:error(jqXHR, textStatus, errorThrown){
alert("Error:" + textStatus+ "," + errorThrown);
}
});
Your parameters for the error callback were named strangely. The documentation says the second param is a text error code, and the errorThrown is the HTTP status code provided by the web server. See the documentation here: http://api.jquery.com/jQuery.ajax/
Next, you'll want to grab a packet sniffer. This will allow you to inspect the packets going to and from the web server and see the error message that it is throwing. A good free option is Fiddler.
The data you're sending is not json.
var data = "login="+localLogin+"&pw="+localPassword+"&forAccount="+forAccount+"&forAccountType="+forAccountType+"&topAccount="+topAccount+"&fromDate="+fromDate+"&toDate="+toDate;
Should be something like this:
var data = '{"Key1":"' + Value1 + '","Key2":"' + Value2 .... + '""}';
And perhaps you should add the type as POST and content type like this:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: ....
try these:
inspect the Network tab on your console.
copy and paste the response and parse it in the console command line to verify the JSON is well formed.
show more verbose error description.

Categories