i have a datatable which i'm loading via Ajax.
in the server side i'm prepering the data for the table and prepare another data for another thing
i want, beside the table loading, to do another thing with the other data i've prepared
so i added to my ajax code a success event, but it replace the table loading and i only can do the other thing
i can't separate between the table loading and the other thing because they are connected, meanning the other thing is influenced by the table loading(changes)
i tried also fnDrawCallback but i don't know how to pass the data of the other thing
Here's the Ajax code with success event:
"ajax": {
"url": "/Entreaties/GetEntreaties",
"data": function (d) {
d.status = 0;
d.firstLoad = firstLoad;
d.jAdvanceSearch = JSON.stringify(new AdvanceSearch());
d.freeText = $("#table_filter input").val();
},
"type": "POST",
"dataType": "json",
success: function (data) {
$.each(data.contactWaySum, function (key, value) {
alert(key + ": " + value.ContactWay);
});
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr.responseText);
}
},
Thank you all for your help
If I understand you right, you were using the built in DataTable ajax but stopped because you wanted to do several things at once. If so, go back to using the DataTable ajax and used the dataFilter function to separate them out and apply them.
Here is an example:
// If your server side sends back somehting that looks like this for the data table (this is what it is expecting)
{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }
// adjust your json to look like
// If the json object return looks like what the
{ dataTableData:{draw:1, recordTotal:20, recordsFilter:20, data:dataSet }, otherStuffData: otherData}
$("#sometable").DataTable({
// other data table stuff left out to save space
"serverSide": true,
"ajax": {
"url": "you url" ,
"data": function (ssp) {
// Do the stuff you need to to get your paramerters ready
// server side parameters (ssp) are documented at http://datatables.net/manual/server-side
// in addition to the ssp parameters, the name of the column is pulled from the table header column
return ssp;
},
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (a, b, c, d) { debugger; },
dataFilter: function (data) {
// call function or what ever you need to do with the other data here
doOtherStuff(data.otherStuffData);
// the web method returns the data in a wrapper
// so it has to be pulled out and put in the
// form that DataTables is expecting.
//return just the datatable data here
return JSON.stringify( data.dataTableData);
}
}
});
Related
I have a AJAX select2 drop-down menu set up to do infinite paging. What'd I'd like to do is go ahead and load the first page of results in the background so that as soon as the user clicks the drop-down, they have a set of options immediately, instead of waiting on the initial AJAX call.
When I search Google for how to do this, I only see results about trying to set an initial selection, which isn't what I want to do. I just want to pre-load the first page of results from my endpoint so the user sees data immediately instead on waiting for the AJAX call to return. Is this even possible?
My select2 setup code is below:
$(".my-class-identifier").select2({
ajax: {
cache: true,
dataType: "json",
delay: 500,
data: function(params, page) {
return {
name: params,
otherParams: $(this).data("other-params")
page: page
};
},
results: function(data, page) {
return {
/* The server returns no data after all the pages have been returned. */
more: data && data.length > 0,
results: data
};
},
type: "GET",
url: function() {
if ($(this).data("url")) {
return $(this).data("url");
} else {
return DEFAULT_ENDPOINT;
}
}
},
allowClear: true,
minimumInputLength: 0,
placeholder: "Search for some data..."
});
So what you are looking for is to initialize your select2. Select2 has an initialize option to load your values, it would look something like this:
initSelection: function(element, callback){
callback([
{id:1,text:'one'},
{id:2,text:'two'},
]);
}
Be sure to add this outside your ajax call, but inside your select2.
An example here in JSFiddle
How about in your backend, you check your search string. If the size is zero or the search string is empty, then send back your first-page result. Otherwise, do the search and return the result.
I've the following generic PostTo method which can be used to post data to an ASP.NET MVc Controller, without the need for repetitive mark-up, I'm pretty sure it was working at one point, but for some reason, the success callback (any of it) doesn't get called.
Any thoughts? Everything looks right, and the server is responding with a valid 200 OK response.
It is however, an empty response. I tried a different (and empty) dataType value, but nothing changed.
function PostTo(controller, action, data, successCallback) {
$.ajax({
url: Settings.HostPath + controller + "/" + action,
type: "POST",
cache: false,
dataType: "json",
data: data,
success: function (data, textStatus, jqXHR) {
if (typeof (successCallback) != "undefined")
successCallback.call(this, data);
}
});
}
ajax method in your script, excepts json data from the server, but as you told in comments, your actions returns nothing (i thinks it's returns EmptyResult).
So, add any json result in your action:
public ActionResult Test()
{
return Json(new {Success = true});
}
My first question with Stackoverflow. How do I display/read twitter search parse data in my webpage?
Below is the code I am working with. I can see 15 object in console.log() but I have no idea on how to show this in web page view.
My coding is below:
$
.ajax({
url : "http://search.twitter.com/search.json?q=gaga&callback=?",
dataType : "json",
timeout:1000,
success : function(data)
{
console.log(data.results);
//console.log(data.results);
//$('#twitter').html(data);// parse data here
},
error : function()
{
alert("Failure!");
},
});
See if this helps http://jsfiddle.net/2cxfN/
$.ajax({
url : "http://search.twitter.com/search.json?q=gaga&callback=?",
dataType : "json",
timeout:1000,
success : function(data)
{
console.log(data.results);
//console.log(data.results);
//$('#twitter').html(data);// parse data here
$.each(data.results, function(i,o){
console.log(o);
$('<img/>', {src:o.profile_image_url}).appendTo('body');
$('<div/>').text(o.from_user).appendTo('body');
});
},
error : function()
{
alert("Failure!");
},
});
Ah, I see you have a div with an id twitter - you would parse that HTML into what you want using the variables in each object that's in data.results, which I've extracted as o, then appendTo('#twitter');
I'm using jQuery UI autocomplete with data from a remote datasource. My use case is really similar to the example here:
http://jqueryui.com/demos/autocomplete/#remote
The only difference is that I set my delay to 0. In between the keystrokes, the menu disappears for about 1/10th of a second ~100milli seconds prior to the updated autocomplete list being displayed.
Is there anyway I can prevent the menu from temporarily disappearing between keystrokes? A good use case is google's search, where between keystrokes, the suggestion box does not temporarily disappear.
IMO, it is not a good practice to set a delay of zero when using a remote datasource. It will send more requests than needed and surcharge the server with no benefit.
Anyway, I think you can achieve what you want by defining the source option as a callback yourself.
First a bit of explanaton. I suppose you are using the remote feature passing an url as the source for the plugin. The plugin actually wraps this into a callback implemented this way:
// in case the option "source" is a string
url = this.options.source;
this.source = function(request, response) {
if (self.xhr) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: "json",
autocompleteRequest: ++requestIndex,
success: function(data, status) {
if (this.autocompleteRequest === requestIndex) {
response(data);
}
},
error: function() {
if (this.autocompleteRequest === requestIndex) {
response([]);
}
}
});
};
As you can see, if there is already an ajax request going on, it abords it. This happenning in your case as a request, as fast as your server can be, takes some time and your delay is zero.
if (self.xhr) {
self.xhr.abort();
}
This will actually execute the error callback of the aborted request that will execute itself the response callback with an empty dataset. If you look at the response callback, it closes the menu if data is empty:
_response: function(content) {
if (!this.options.disabled && content && content.length) {
...
} else {
this.close();
}
You can actually define your own source callback to make your ajax request yourself and change the default behavior by not aborting any pending request. Something like:
$('#autocomplete').autocomplete({
source: function(request, response) {
$.ajax({
url: url,
data: request,
dataType: "json",
success: function(data, status) {
// display menu with received dataset
response(data);
},
error: function() {
// close the menu on error by executing the response
// callback with an empty dataset
response([]);
}
});
}
});
I am using MVC to pass JSON data to JsTree and show a hierarchical view of information.
Everything is working just fine, however, there are times when the user does not have access the the data or for some reason the MVC action throws an exception:
In these cases, the action passes a JSON error message and sets the HttpStatusCode to NotAccepted or InternalServerError.
However the jsTree's sinner keeps spinning and I don't seem to find a way to make it stop and show the error message.
Has anyone solved this issue before? How can one does error handling when using JsTree's JSON data plugin?
UPDATE:
I figured out how to capture the error:
$("#jstree1").jstree({
"json_data": {
"ajax": {
"url": serviceUrl,
"data": function (n) {
return { pid: n.attr ? n.attr("id") : "" };
},
"error": function (x, s, r) { var err = $.parseJSON(x.responseText); if (err!="") { alert(err); } }
}
}
It seems that JsTree does get the MVC http statusCode and the error, now I need to figure out how to tell the JsTree to stop waiting and remove the spinner image!
I am also looking for a good way of showing the error in JsTree, or should I manage the error message outside of it?
I've solved this problem.
Just a note- the code example above for handling ajax call errors is incorrect, please see a complete example below:
$('#YourTree').jstree({
"json_data": {
"ajax": {
"url": "/Controller/Action",
"data": function () {
return { Parameter1: "Value1", Parameter2: "Value2" }
},
"type": "POST",
"dataType": "json",
"error": function (jqXHR, textStatus, errorThrown) { $('#YourTree').html("<h3>There was an error while loading data for this tree</h3><p>" + jqXHR.responseText + "</p>"); }
}
}
});
And in the actual action, you need to set the http response status code to 1 and write the error. e.g.
Response.StatusCode = 1
Response.Write("Error you want to go into jqXHR.responseText here");
Enjoy :)
Maybe you should look into handling this error a layer above the .jstree. Maybe by handling the window.onerror event you can achieve this. In here you could call a function that will rebuild the tree or something? Be sure to include this script as the first one in your page.
<script type="text/javascript">
window.onerror = function(x, s, r){
alert('An error has occurred!')
}
</script>