How to get the next load of data inside jQuery DataTable - javascript

I am displaying SharePoint data inside a jQuery DataTables. The total number of rows is like 2000, but I am displaying only 100 on the first load.
When the page is loaded the data is displayed correctly. So, I wanted to get the next load of data inside the datatable, but I couldn't figure it out how to do that.
I thought of using bServerSide and iDeferLoading but these are giving me errors like the json format is not correct.
Below is my current code that I am testing at the moment. Can anyone tell me how can I get the rest of the results? How can I implement pagination when the user reaches the end of 100 rows?
Why bServerSide and iDeferLoading do not work in my case?
I have the same issue using jQuery and REST while doing a postback to SharePoint.
$(document).ready(function () {
window.StartTime = new Date();
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
SP.SOD.executeFunc('sp.search.js', 'Microsoft.SharePoint.Client.Search.Query.KeywordQuery', function () {
var queryText = "ContentTypeId:0x010066FA3DE3E334C841B418C82CC475A227*";
var clientContext = new SP.ClientContext.get_current();
var keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(clientContext);
keywordQuery.set_queryText(queryText);
keywordQuery.set_rowLimit(50);
keywordQuery.set_trimDuplicates(false);
var searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(clientContext);
var results = searchExecutor.executeQuery(keywordQuery);
clientContext.executeQueryAsync(onQuerySuccess, onQueryError);
function onQuerySuccess() {
var rows = results.m_value.ResultTables[0].ResultRows;
var totalRows = results.m_value.ResultTables[0].TotalRows;
$("#example").DataTable({
"bDestory":true,
"bProcessing":true,
//"bServerSide": true,
"iTotalRecords":totalRows,
"iTotalDisplayRecords":10,
"iDeferLoading": totalRows,
"aaData":rows,
"aoColumns":[
{"mData":"Title"},
{"mData":"Path"}
]
});
console.log("After added to table: " + ((new Date() - window.StartTime) / (60 * 60)) + " seconds");
}
function onQueryError(sender, args) {
alert("call failed. Error: " + args.get_message());
}
});
});
});
This is the header response when I click on NEXT or dropdownlist when using bServerSide and iDeferLoading (Apparantly the Content-Type is returned as text/html):
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Vary: Accept-Encoding
Server: Microsoft-IIS/8.5
X-SharePointHealthScore: 0
X-AspNet-Version: 4.0.30319
SPRequestGuid: 6fc9299d-cba4-c06b-92ee-423504bab93b
request-id: 6fc9299d-cba4-c06b-92ee-423504bab93b
X-FRAME-OPTIONS: SAMEORIGIN
SPRequestDuration: 84
SPIisLatency: 1
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 15.0.0.4569
X-Content-Type-Options: nosniff
X-MS-InvokeApp: 1; RequireReadOnly
Date: Tue, 01 Sep 2015 19:37:35 GMT
Content-Length: 23942
How can I force it to return JSON formated data?

Option bServerSide doesn't work for you because the data in the response has to be structured in a certain way, see Server-side processing (for DataTables 1.9) or Server-side processing (for DataTables 1.10).
I would remove this line keywordQuery.set_rowLimit(50); if it limits number of results and let the DataTables do the filtering, sorting and pagination.
Also remove invalid or irrelevant options in your DataTables initialization codes, so it looks like:
var rows = results.m_value.ResultTables[0].ResultRows;
$("#example").DataTable({
"aaData":rows,
"aoColumns":[
{"mData":"Title"},
{"mData":"Path"}
]
});

Related

PHP curl form with no action and js events

I'm trying to use curl to post some data and retrieve it from a website that isn't mine, the websites form doesn't seem to have a form action and the page doesn't reload when you submit the data and there also seems to be some js behind the click of the button.
$url = "http://emonitoring.poczta-polska.pl/#";
$parm = "numer=RR123456789PL";
and here is the curl:
array(
CURLOPT_URL => $url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => $parm,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE
);
I execute and init the curl as expected, just showing the important parts. Here is also the live http headers output:
POST /wssClient.php HTTP/1.1
Host: emonitoring.poczta-polska.pl
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Content-Type: application/x-www-form-urlencoded
Origin: http://kody.poczta-polska.pl
Referer: http://kody.poczta-polska.pl/
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
HTTP/1.1 200 OK
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Length: 1215
Content-Type: text/html; charset=UTF-8
Date: Mon, 30 Jun 2014 03:31:59 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: Apache
X-Cnection: close
At the moment it just shows the page and it doesn't look like that form was submitted, I've also tried putting the url as: "http://emonitoring.poczta-polska.pl/wssClient.php" and just get told to enter the number.
In such cases you go to chrome, hit F12, go to network, submit the form and see what is sent to the server. I see this posted
s:fggsbnqu033gqiipemr50fer56
n:RR123456789PL
l:
If you view source you see
if (jQuery('#numer').val().length == 19) {
var numer = dodajck(jQuery('#numer').val())
} else var numer = jQuery('#numer').val();
jQuery.ajax({
type: 'post',
cache: true,
dataType: 'html',
data: ({
s: 'fggsbnqu033gqiipemr50fer56',
n: numer,
l: ''
}),
url: 'wssClient.php',
The s:.... could mean you need to have a session on their server to be able to call the wssClient - if so, you will need to CURL with sessions
If you can call their server without a session or you have a session before you call you can curl using the parm is n= and not numer= and you need to have calculated the checksum using their function which can easily be translated to PHP
function dodajck(numer) {
// dodatkowe sprawdzenia i określenie wag oraz części numeru, która
// ma zostać zważona
//String wagi;
//String doWazenia;
var wagi = "3131313131313131313";
var doWazenia = String(numer);
// wyliczenie sumy iloczynów waga * cyfra
var suma = 0;
for (var i = 0; i < 19; i++)
suma = suma + Number(doWazenia.substring(i, i + 1)) * Number(wagi.substring(i, i + 1));
// ostateczne sprawdzenia
// przykład numeru 20-cyfrowego
// 00
// 1 - rodzaj?
// 590 -- kraj 590 = PL
// 0773 -- firma 0773 = PP
// 3 -- rodzaj przesyłki
// 12345678 - numer przesyłki
// 9 - CK
// ważone są numery od 1 do 19
var ck = 10 - suma % 10;
if (ck == 10) ck = 0;
return String(numer) + String(ck);
}
The form is submitted via AJAX. To see the exact HTTP request simply fire up the developer tools in Chrome or Firefox (F12). Navigate to the 'Network' tab, and hit the submission button on their website. You should see a request being fired off. If you open it up, you will be able to see everything you need to make the request yourself - URL, Parameters and their format, HTTP header values, etc. - and the response you're supposed to get.
Hope this helps!

How to force browser to open "save as" dialog for binary response?

I'm developing Zimbra Zimlet.
I'm requesting JSP from Javascript (both belong to the same Zimlet)
var jspUrl = this.getResource("my.jsp");
var callback = new AjxCallback(this, this._rpcCallback, ["param1", "param2"]);
AjxRpc.invoke(null, jspUrl, null, callback, true);
_rpcCallback function
automator_HandlerObject.prototype._rpcCallback = function(p1, p2, response) {
if (response.success == true) {
appCtxt.getAppController().setStatusMsg(response.text);
} else {
console.log("response error");
}
}
I need to return some binary file in response to that request. Here is JSP code
<%# page import="java.io.FileInputStream" %>
<%# page import="java.io.BufferedInputStream" %>
<%# page import="java.io.File" %>
<%# page import="java.io.IOException" %>
<%
ServletOutputStream outStream=response.getOutputStream();
File myfile = new File("/tmp/attachment.zip");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=attachment.zip");
response.setContentLength( (int) myfile.length( ) );
FileInputStream input = new FileInputStream(myfile);
BufferedInputStream buf = new BufferedInputStream(input);
int readBytes = 0;
while((readBytes = buf.read( )) != -1)
outStream.write(readBytes);
outStream.flush();
outStream.close();
buf.close();
%>
("application/x-download"/"application/force-download" also were tested with FireFox and Chrome)
I expected "save file" browser dialog to be appeared.
I tried
document.write(response.text)
in _rpcCallback function and I can see appropriate response headers
HTTP/1.1 200 OK
Date: Fri, 03 May 2013 08:16:49 GMT
Expires: Thu, 01-Jan-1970 00:00:00 GMT
Content-Type: application/octet-stream
Content-Length: 20021
Set-Cookie: JSESSIONID=11ebfk145b34z;Path=/zimlet
Content-Disposition: attachment;filename=attachment.zip
as well as binary response body content, but nothing happened.
What code _rpcCallback function must contain in order to show "download file" dialog instead of printing the file as text?
Tested with Zimbra Desktop 7.2.2 GA
Thanks to Julian the solution has been found and it is too simple:
window.open(fileUrl);

jquery how to get the status message returned by a ajax call of type post?

javascript
$('#send').on('click', function() {
$.ajax({
'url': $('#url').val(),
'type': 'post',
'complete': function (jqXHR, textStatus) {
var msg = "Status: " + jqXHR.status + " (" + jqXHR.statusText + " - " + textStatus + ")<br />";
msg += jqXHR.getAllResponseHeaders().replace(/\n/g, "<br />");
$('#results').html(msg);
}
});
});
php
header("HTTP/1.0 200 Some message here");
flush();
exit();
Results
Status: 200 (OK - success)
Date: Wed, 07 Dec 2011 21:57:50 GMT
X-Powered-By: PHP/5.3.6
Transfer-Encoding: chunked
Connection: Keep-Alive
Server: Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6
Content-Type: text/html
Keep-Alive: timeout=5, max=100
Question
How do I get the "Some message here" part of the header?
http
http protocol
6.1 Status-Line
The first line of a Response message is the Status-Line, consisting of
the protocol version followed by a numeric status code and its
associated textual phrase, with each element separated by SP
characters. No CR or LF is allowed except in the final CRLF sequence.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
Got it. It's jqXHR.statusText.
$.get("test.php").complete(function(jqXHR) {
console.log(jqXHR.statusText);
});
Just tried it out in Chrome with your exact PHP code.
Have you tried xhrobject.getResponseHeader() yet? jQuery docs say it's also available there. If you don't know the header's name, try getAllResponseHeaders().
Also, can you see that message in your browser's debugging console (network tab, connection headers)? If it's not there, it will hardly be available from js.

Can't do anything with Ajax response in Firefox extension

I'm writing a simple AJAX call that returns a full HTML page and then I attempt to get some values I need from this response. I dont know why its not working and I've done everything I could possibly think of. It works when I have my code as part of another HTML page but not as part of a Firefox extension and thats the problem: I'm writing a Firefox extension!
In the Firefox extension I get a response and I can alert, and its there (i.e. I see the response text)! but I cant call .find, .filter or anything else really. The code breaks silently at some point in the success function and nothing happens.
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>runthis</title>
<script type="text/javascript" language="javascript" src="jquery-1.6.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').click(function(){
var makeTransferURL = "empty";
var pc = "empty";
$.ajax({//Transfer
type: "POST",
url: "http://localhost/transfer2.html",
data: "",
dataType: "html",
context: document.body,
success: function(response){
var table = $(response).find('table.123RowSeparator');
var a = table.find('a[href*="123"]');
var href = a.attr("href");
makeTransferURL = href;
var link = makeTransferURL.indexOf('PC_');
pc = makeTransferURL.substring(link, (link + 11));
alert(pc);
},
error: function() {
alert("Sorry, The requested property could not be found.");
}
});
});
});
</script>
</head>
<body>
<input type="button" value="load" />
</body>
</html>
The exact same code as a firefox extension doesnt work:
window.addEventListener("load", function() { myExtension.init(); }, false);
var myExtension = {
init: function() {
gBrowser.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered "onload" event
if(doc.location.href=="http://localhost/index2.html") {
var makeTransferURL = "empty";
var verifyTransferURL = "empty";
var confirmTransferURL = "empty";
var token1 = "empty";
var token2 = "empty";
var pc = "empty";
$.ajax({//Transfer
type: "POST",
url: "http://localhost/transfer2.html",
data: "",
cache: false,
async: false,
dataType: "html",
context: document.body,
success: function(response){
var table = $(response).find('table.123RowSeparator');
var a = table.find('a[href*="123"]');
var href = a.attr("href");
makeTransferURL = href;
var link = makeTransferURL.indexOf('PC_');
pc = makeTransferURL.substring(link, (link + 11));
alert(pc);
},
error: function() {
alert("Sorry, The requested property could not be found.");
}
});
}
aEvent.originalTarget.defaultView.addEventListener("unload", function(){ myExtension.onPageUnload(); }, true);
},
onPageUnload: function(aEvent) {}
}
I need to know why!
Here is the HTTP header of the response:
HTTP/1.1 200 OK
Date: Mon, 11 Jul 2011 10:43:32 GMT
Server: Apache/2.2.19 (Win32)
Last-Modified: Wed, 06 Jul 2011 12:41:47 GMT
ETag: "9000000015529-f7b9-4a765ec7780ff"
Accept-Ranges: bytes
Content-Length: 63417
Keep-Alive: timeout=5, max=97
Connection: Keep-Alive
Content-Type: text/html
Found the solution, its not elegant(or correct practice) but give me a break! No one answered :)
Here is what I did to get this to work:
$('#divid').css('display', 'none');
response = response.replace(/<head>(?:.|\n|\r)+?<\/head>/ig, "");
doc.getElementById('divid').innerHTML = response.replace(/<script[^>]*>[\S\s]*?<\/script[^>]*>/ig, "");
var table = $('#divid').find('whateveryoufeellike');
So I think the problem was that I was getting a plain HTML formatted string and I couldn't use jQuery functions like .find and .filter on a string like that. Took the string and using regex, striped it off of its head and script tags and (probably do images too soon) dumped what was left in a Div I created. But not before setting the div to be hidden so that the code doesn't show. The user feels no difference really and I can now use the DOM for the mother page and take run all the .finds and .filters my heart desires!
There beauty of it is that there wont be any collision issue between tags with same id/class on the same page as long as the name of the Div you make in your page is unique to that page. So something really random would be a good choice :D suggestions... !HWSyujtewq$y$y$w£t!"£%^(&)%$dsfdgjnbfdvsc

jQuery AJAX and Google Currency calculator

I have some code that performs an AJAX call to the google currency calculator. Which in theory should return a JSON array that i can ten use to get some exchange rate related data.
The Link is:
http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY
Going to the link shows
{lhs: "1 U.S. dollar",rhs: "6.49148317 Chinese yuan",error: "",icc: true}
My javascript code (I tired this with both POST and GET):
jQuery.ajax({
type: "GET",
url: "http://www.google.com/ig/calculator",
data: "hl=en&q=1USD=?CNY",
success: function(msg) {
var currency = $.parseJSON(msg);
alert (currency ['rhs'];);
}
});
Examining fire bug shows in red with an empty response
GET http://www.google.com/ig/calculator?hl=en&q=1USD=?CNY 200 OK 255ms
What am I doing wrong?
You can't perform cross domain requests with jQuery. You need to use JSONP to perform this request. These links might help:
http://api.jquery.com/jQuery.getJSON/#jsonp
jsonp with jquery
JSONP requests are not subject to same-origin policy restrictions.
heard google has stopped services from iGoogle from Nov 1st..
the link no longer works.
As we know google has stopped services from iGoogle from Nov 1st/2013..
But we can use https://www.google.com/finance/converter to get the real time data.
Following example of jquery will work for you.
function CurrencyConvetor(amount, from, to) {
var result = '';
var url = "https://www.google.com/finance/converter?a=" + amount + "&from=" + from + "&to=" + to;
$.ajaxSetup({async: false});
$.get(url,
function (data) {
var startPos = data.search('<div id=currency_converter_result>');
var endPos = data.search('<input type=submit value="Convert">');
if (startPos > 0) {
result = data.substring(startPos, endPos);
result = result.replace('<div id=currency_converter_result>', '');
result = result.replace('<span class=bld>', '');
result = result.replace('</span>', '');
}
})
return result;
}

Categories

Resources