Ajax datatable Server-side processing draw - ajax

During server side processing, one of the parameters sent from the server "draw" is coming as null, but I am not able to figure out in which scenario is that parameter being sent as null from the server, has anyone encountered this issue before , i tried navigating though the application but I am not able to replicate this issue, got this issue only once, but not able to reproduce it.
Basically, we have a datatable in our application, in which the data gets populated through ajax call, but in one of the scenarious , the "draw" parameter is sent as null from the server.

This is the content of the ftl file(similar to HTML file) which is used server side processing :
"processing": true,
stateSave: true,
"serverSide": true,
"pageLength": 10,
"lengthMenu": [10, 25, 50, 100],"pagingType": "full_numbers",
"scrollX": "true","scrollY": 500,
"ajax": {
"url": "/platform/${registry}/facility${facilityId}/case-list/load",
"type": 'POST',
"data": function (d) {
d.visibleColumns = getVisibleColumns();
},
headers: {
'X-CSRF-Token': $('meta[name="_csrf"]').attr('content')
}
},
There is a code in the same ftl file where the application is manually sending the parameters to the server:
var url = "/platform/${registry}/facility${facilityId}/case-list/export?output=excel&draw=1&start=0&length=100000";
Though we are not doing anything with these paramerters in the controller class(Spring MVC contoller)
This is the code in the java class, which is trying to read this parameter value and parsing it to int , since "req.getParameter("draw")" value is null, its throwing NumberFormatException in the code, but not able to replicate in which scenario.
public int getDraw() {
return Integer.parseInt(req.getParameter("draw"));
}

Related

How to access RESPONSE data from an AJAX Get in JQuery

This is my first attempt at using an AJAX GET to pull data and it is really causing me a nightmare. I have used POST loads of times and assumed accessing the data would be the same basic process, but no matter what I try I always end up with "Undefined".
This is the code I have been trying to make the GET work in my script;
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/buytoken/public/api/stage?secret=***************",
cache: false,
dataType: "json",
success : function(response){
var len = response.length;
for(var i=0; i<len; i++){
var sold = response[i].progress;
}
alert(sold);
}
});
});
This is then what the response should be;
{
"success": true,
"response": {
"ico": "running",
"total": "8,000,000",
"total_amount": "800,000",
"sold": "1,599,300",
"sold_amount": "159,930",
"progress": 20,
"price": "0.1",
"start": "2022-02-28 00:01:00",
"end": "2022-05-31 00:01:00",
"timezone": "Europe/London",
"min": "500",
"max": "4000000",
"soft": "400000",
"soft_amount": "40,000",
"hard": "800000",
"hard_amount": "80,000"
}
}
The script that I am trying to access is on the same webserver.
It is coming from a third-party piece of software that we are running on the site. The documentation states "Application provides some specific internal live data in JSON"
So, we should be getting JSON back.
I need to access just two pieces of data "sold_amount" and "progress" which I want to load into variables in the Success callback.
I really would be grateful if somebody could explain or better still show me how this is supposed to work because I am really banging me head against the wall on this.
Also, if I need to add any extra bits like error handling then please point that out.
Thanks to anybody who responds to this..

fineUploader Failed in the Request To endpoint and the cause in onError Callback is UnKnown Reason

kindly i have to pages using fineUploader ,
the first page is working correctly but the second isn't : the response in debugging browser console is:
My Html Body will be existing here.
Simple upload request failed for 0
[Fine Uploader 5.11.8] Error when attempting to parse xhr response
text (Unexpected token < in JSON at position 0)
for the point one :(the request didn't reach the endpoint because i made a tester in the endpoint page if any script accessed it)
so the request in the first page is working and the same request with the same path in endpoint property isn't working in the second
i read many articles with the same error but all of them were not identifying correct endpoint path , which i did correctly and tested in the first Page.
var uploader = new qq.FineUploader({
debug: true,
element: document.getElementById('my-uploader'),
request: {
endpoint: "http://localhost/fineuploader/endpoint.php",
// endpoint: "http://localhost/fineuploader/endpoint.php",//commented to prove that i used //both of the relative and absolute paths
},
chunking: {
enabled: true,
concurrent: {
enabled: true
},
success: {
endpoint: "http://localhost/fineuploader/endpoint.php?done",
}
},
deleteFile: {
enabled: true,
endpoint: "http://localhost/fineuploader/endpoint.php"
},
retry: {
enableAuto: true,
showButton: true
},
form:{element:"FormId", },
callbacks: {
onError: function(id, name, errorReason, xhrOrXdr) {
alert(qq.format("Error on file number {} - {}. Reason: {}", id, name, errorReason));
},
});
The Answer of Mr Ray Nicholus Here was useful but i want to provide the solution in my case and my mistake, my problem was that in the first page i didn't provide action attribute in form tag and in the second i did , so when i provided in the second page the action of the form a different value than what is specified in
<form id="test" action="form.php">
request: {
endpoint: "http://localhost/fineuploader/endpoint.php",},
the requests were going to the action attribute value path(form.php) not for the above request value (endpoint.php).
It's really very simple, and there is no other answer to this question: either your endpoint is incorrect (and of course the response will be invalid too) or your endpoint is correct but your endpoint is not returning valid JSON. You'll need to look at the response closely to determine the issue.
In your case, your endpoint is returning HTML, not JSON. You'll have to fix this on your server.

Ext Data Session and bad server response ("[W] Ignoring server record: ...")

Our application handles and manages records changes on the client side. We use ExtJS5 Data Session mechanism.
A session tracks records that need to be updated, created or destroyed
on the server. It can also order these operations to ensure that newly
created records properly reference other newly created records by
their new, server-assigned id.
Let me introduce short use case.
User opens and fills a form. Behind the scene fields are binded to entity object which is tracked by session. When user clicks Submit then session is synchronized, i.e. Ext sends requests to the server and parse response. Here I've encountered a problem.
Server returns following object but Ext does not recognize it:
[{"success": false, errorMessage: "error"}]
Ext prints warning:
[W] Ignoring server record: {"success":false}
or
[W] Ignoring server record: {"success":true}
My question is how should look server response in order to indicate that record is not accepted/saved by backend?
The source code where above warning is printed: http://docs-origin.sencha.com/extjs/5.0/apidocs/source/Operation.html (in function doProcess)
Below I put snippet how I'm starting a batch operation (sync session):
var session = this.getViewModel().getSession(),
saveBatch = session.getSaveBatch();
saveBatch.on('complete', function (batch, operation, eOpts) {
// whole batch processing has been completed
/*...*/
});
saveBatch.on('exception', function (batch, operation, eOpts) {
// exception has been occurred (possible for each operation) (such as HTTP 500)
/*...*/
});
saveBatch.on('operationcomplete', function (batch, operation, eOpts) {
// single operation has been completed
// now, every operation is marked as successful
/*...*/
});
saveBatch.start();
update 26.09.2014
Sencha developer has suggested including an id of object in the response. so I've modified server response to:
[{"id": 10, "success": false}]
but this does not solve the problem.
I spend some time on debugging Ext.data.operation.Operation.doProcess method and I analyzed a sample code from sencha support. Ultimately I've found the solution.
There is my proxy config:
proxy: {
type: 'rest',
// ...
reader: {
type: 'json',
rootProperty: 'data',
totalProperty: 'totalCount',
successProperty: 'success',
messageProperty: 'errorMessage'
}
}
Server response when some error occured:
{
"success": false,
"errorMessage": "<error message>"
}
Server response when data was successfully saved:
The minimal form for delete or update record without changing data:
{
"success": true,
}
The extended form for creating or updating record with changing record data:
{
"success": true,
"data": [{
clientId: 5, // clientIdProperty
id: 5,
// [optional] fields to change, e.g.:
name: 'new name'
}]
}
I modified a demo which I have from sencha support:
https://fiddle.sencha.com/#fiddle/bem
in proxy config use data2.json for error and data3.json for success response.

S3 Upload Issue

I am trying to upload a file on S3. I have been verified everything couple of times and all looks correct to me, but whenever I am trying to upload file, getting error message saying
responseText =
InvalidArgumentPOST requires exactly one file upload per request.0file3670E4EE52B3BCD5b3rOF/9WJHymo1ZENIOlrct/ZusAJ50AnSIP0df3K3+DdEcAFolJDx8qU6DH2N1l
Can someone please help me to findout what I am doing wrong here?
<div id="s3-fileuploader" class="dropArea"></div>
<script type="text/javascript">
j$ = jQuery.noConflict();
//block and unblock UIbased on endpoint url
function setUI(){
j$('div.dropArea').unblock();
}
$(document).ready(function () {
$('#s3-fileuploader').fineUploader({
request: {
endpoint: "https://{!bucketname}.s3.amazonaws.com",
accessKey: "{!key}"
},
signature: {
//always included
"expiration": "{!expireStr}",
signature : "{!signedPolicy}",
policy: "{!policy}",
"conditions":
[
//always included
{"acl": "public-read"},
//always included
{"bucket": "{!bucketname}"},
//not included in IE9 and older or Android 2.3.x and older
{"Content-Type": "{!ContentType}"},
//always included
{"key": "{!key}"},
//always included
{"x-amz-meta-qqfilename": "{!URLENCODE('test.jpg')}"},
]
},
cors: {
expected: true, //all requests are expected to be cross-domain requests
sendCredentials: false, //if you want cookies to be sent along with the request
allowXdr: true
},
autoUpload: true,
multiple:false,
debug: true,
text: {
uploadButton: '<i class="icon-plus icon-white">Select Files</i> '
},
uploadSuccess: {
endpoint: "{!redirectURL}"
}
}).on('submit',function(event,id,name){
//set endpoint
console.log('https://{!bucketname}.s3.amazonaws.com');
$(this).fineUploader('setEndpoint','https://{!bucketname}.s3.amazonaws.com');
});
setUI();
});
</script>
</body>
The signature option is supposed to include information about your signature server. Instead you are apparently attaching an (invalid) policy document to this option. Furthermore, you do not create the police document, Fine Uploader creates it for you and passes it to your signature server for signing.
Also you should be using the fineUploaderS3 jquery plugin for this.
It looks like you have not read the documentation that describes how Fine Uploader S3 works. I suggest starting with the guides on the home page of http://docs.fineuploader.com.

Intermittent failure of jQuery ajax using IE8

I am using jQuery ajax to load data into a jQuery tab. It works fine in Chrome and FireFox. In IE8 the data is sometimes not loaded. If I clear cache or reload the page it apparently works fine.
As far as I can tell it fails after shutting down IE and then starting it up again some time later. It has failed within hours, but succeeds if the delay is only minutes. At least that is what I think the failure mode is, I have not rigorously determined a magic time.
ETA: It works if I clear the cache or refresh the page.
I have put a superfluous time parameter in the post data, and set cache:false in the ajax call.
The data is not cached since if I change the expected data it will fill it in properly.
Another update:
A missing piece of data. This is a Facebook app. That turns out to be crucial.
I sniffed both the working and not working sessions with Wireshark. It turns out the difference is that the working session submits the Facebook cookies and the not working one doesn't.
So the question is now how to force the ajax call to include cookies. The descriptions I have found about the ajax call is that it includes cookies. Is the behaviour I am seeing a bug?
ETA:
The javascript:
$.ajaxSetup
(
{
// Disable caching of AJAX responses
cache: false
}
);
$(document).ready
(
function()
{
$('#shopTabs').tabs();
thing.create();
thing.editPicture();
$('#shopTabs').bind
(
'tabsselect',
function(event, ui)
{
thing.setReload(ui.index);
thing.setActive(ui.index);
}
);
}
);
// Must be global for Java to call
function reload()
{
thing.create();
thing.editPicture();
}
var thing =
{
reload : 0,
active : 0,
noOp : function()
{
},
create : function()
{
date = new Date();
$('#shopTabs1').load('create.php', {time : date.getTime()}, thing.linkform);
},
editPicture : function()
{
date = new Date();
$('#shopTabs2').load('editPicture.php', {time : date.getTime()}, thing.noOp);
},
linkform : function()
{
$('#upload').ajaxForm({target : '#shopTabs1'});
},
setReload : function
(
index
)
{
this.reload = this.reloadList[index];
},
setActive : function
(
index
)
{
this.active = this.activeList[index];
},
load : function
(
php,
args,
loadFn
)
{
var settings =
{
type : "POST",
cache : false,
url : php,
data : args,
context : this,
success : function (data)
{
$(this.active).html(data);
loadFn();
}
}
$.ajax(settings);
}
};
thing.activeList = ['#ui-tabs-1', '#shopTabs1', '#shopTabs2'];
thing.reloadList = [thing.noOp, thing.create, thing.editPicture];
In your thing.create function, add a changing query parameter, current date is good, or use a random number.
$('#shopTabs1').load('create.php?r='+escape(new Date().toString()), {time : date.getTime()}, thing.linkform);
or
$('#shopTabs1').load('create.php?r='+new Date().valueOf(), {time : date.getTime()}, thing.linkform);
same with your editPicture.
That will prevent IE from caching, as mentioned by Omu's answer
It turns out the problem was that IE officially expects a P3P header to load an iframe from a third third party site. Facebook implements apps using iframes from the app provider.
IE does not consistently fail if there is no P3P header.

Resources