I am using datatables and am using colReorder and need to save the state of the columns without using statesave(I am not allowed to use localcache). I do however have a preference table in my database for storing this kind of information in JSON format.
I have looked at colReorder.order() which looks like what I need to get the order.
What I'm thinking so far is on a column change, call colReorder.order() and place that returned array in my preferences table and then on re-initialization use that to re-order the table.
So my question/what I need help on is this: On a change of the colOrder, I need to save the order they're in and update my preferences. How do I do this? I can't seem to find "where" to place the colReorder.order(). I haven't seen an onChange() for datatables or even sure if that would be the best way to approach this
EDIT: David's answer is the ideal solution, however not applicable in my situation due to code already existing and laziness.
My solution/work-around that I found was to stringify and save details.mapping from within this function to my preferences and on initialization of my table I use colReorder.order(savedArray[],true).
Leaving it in case anyone finds themselves in the situation I was in.
Actually DataTables provide methods for storing and retrieving state to and from an alternative location. Look at stateSaveCallback and stateLoadCallback.
I do however have a preference table in my database for storing this
kind of information in JSON format
Then you just need to fill out the "blanks". Lets assume you have a serverside script called statesave that can store and retrieve the state by 'set' and 'get' using an unique userId. The skeleton would look like this:
$('#example').DataTable({
stateSave: true,
stateSaveCallback: function(settings, data) {
$.ajax( {
url: 'statesave',
dataType: 'json',
data: {
action: 'set',
userId: aUserId,
state: data
}
})
},
stateLoadCallback: function(settings) {
var state;
$.ajax( {
url: 'statesave',
dataType: 'json',
async: false,
data: {
action: 'get',
userId: aUserId
},
success: function(data) {
state = data
})
})
return state
}
})
It sounds like you are using the server-side processing option. If that's the case, you can add the column reorder array to the sent parameters object and save it that way.
Related
This is my first time attempting filtering and searching the mySQL database. From my research I have found out I need an AJAX call and some PHP query that will help my achieve the filtering I want to achieve.
This is what I want the AJAX search to do:
Have an Apply button. When I click the button I want a URL to get generated and the AJAX call to happen.
Only reload part of the page where the data queried is contented.
So far I have managed to create this:
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(data){
$('#data-holder').html(data);
}
});
});
This manages to create the URL one of the filters, but it does not take the other filters into consideration. I also did not manage to create the button. I am guessing you would need a where statement in the PHP to filter the database?
Would anyone be willing to assist me in creating the AJAX call and PHP query for the filters?
In total I have three filters, and when I click a button I want an AJAX call to filter my database with the three filters and return the results without having to reload the whole webpage.
EDIT: Here is my JS AJAX query:
$("#apply").click(function() {
$country=$('#filter-country').val();
$type=$('#filter-type').val();
$year=$('#filter-year').val();
$.ajax({
type: "GET",
url: "{{$launchsitename->site_code}}",
data: {'country':$country, 'type':$type, 'year':$year},
success: function(data) {
$('#data-holder').append(data);
}
});
});
Now I just need to create a PHP query.
you can use propriety called .Append() instead of .html() ,also here you are getting one element value on change , if you want to get the three of them at one button click , you can make it the same way that you got the val of the first one , and just adding it to the request and handle it back in PHP to divide and execute each one or just pass the three of them to your procedure , depends on what you have
$("#filteridname").change(function() {
$value=$(this).val();
$.ajax({
type: "get",
url: "{{$myurl}}",
data: {'search':$value},
success: function(response){
$('#data-holder').append(response);
}
});
});
Read about .append()
I'm developing an application that is essentially a search bar. The source is a SQL table that has about 300,000 records.
Ideally, I would like to have some sort of autocomplete feature attached to this search bar. I've been looking into several ones like jquery autocomplete.
However, as one can imagine, loading all of these records as the source for the autocomplete is impossible. The performance would be abysmal.
So my question is, what is an efficient way to implement a search autocomplete feature for a source that contains thousands and thousands of records?
I thought of something like this. Essentially I'm querying the database each time they type something to get a list of results. However, querying a database via ajax doesn't seem optimal.
$( "#search" ).keyup(function( event ) {
$.ajax({
//query the database when the user begins typing, get first 1000 records
//set the source of the autocomplete control to the returned result set
});
});
You should not start querying the db on very first keyup, (not even in three-four) keyup.
For example, User is typing Albatross. When He hit 'A', if you do a Query search it will send you almost 300,000 results right away, cause every set of data must have the letter "A".
So, should ignore first few (3-5) letters. it will be better, if you can store the search keywords. Cache the top results, when 1-3 keyup you show the top search keywords. Auto complete might not be good feature for searching in a that big DB,
Last Tips for the problem, Your users use google and facebook everyday. They are more then 300,000 result for each of search in any of the applications above. Google or facebook does not show 1000 result at once. It is not good for UI Design or your Servers bandwidth. Just think, how can you categorizes and present the data to user, so that they get what they want and you keep your servers bandwidth and processing cost optimal.
always, remember the context.
Do not bind any events yourself. jQuery Autocomplete already performs bindings.
The proper way to implement this is to set the source: object to a an AJAX callback:
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});
}
I am assuming you have added indexes to your table, if not that would be your first step, then if performance is insufficient and if your queries often repeat, you might want to look at this.
http://memcached.org/
or some other caching mechanism.
Upon request of some key you would return that key and add it to the cache, opon subsequent request for same key data would be read from cache instead of hitting database. That would reduce the load and increase the speed.
source: function (request, response) {
$.ajax({
url: 'yourQueryUrl.php', // <- this script/URL should limit the number of records returned
async: true,
cache: false,
type: 'GET',
data: {q: $('#searchBox').val()},
dataType: 'json',
success: function (data) {
response(data);
}
});
I'm trying to lessen manual update work by using Yahoo Pipes and jQuery to update a table with upcoming events from a different domain. I have created this Pipe to gather the data, and it seems to work.
Now I am reading the JSON file with the following jQuery Script taken from this tutorial:
$.ajax({
type: "GET",
url: "http://pipes.yahoo.com/pipes/pipe.run?_id=57aa32bf3481c8dca0c07afcf9b9dc29&_render=json",
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
$('body').append(data.query.results.a.content);
}
});
The jQuery append failes, I guess because 'data.query.results.a.content' does not relate well to the JSON structure created by the pipe.
I've tried altering both the pipe and the append in several ways and am just short of giving up, I'd be very grateful for your Input.
Think you are parsing the json result incorrectly.
On viewing the json object here http://jsonviewer.stack.hu/
You will observe content node for each item is at value.items[0].a.content
i.e. try something like this :
$('body').append(data.value.items[0].a.content);
You will need to iterate the items array like this
$.each(data.value.items, function(index,element) {
$('body').append(element.a.content);
});
Try it on fiddle : http://jsfiddle.net/EFvJf/
I'm trying to save dynamically created elements in my application.js file to the database. Would the code look something like this?:
$.ajax({
type: "POST",
data: { title: 'oembed.title', thumbnail_url: 'oembed.thumbnail_url'}
});
Is there anything I'm missing? Assume that oembed.title and oembed.thubnail_url hold the values I want to save, and that title and thumbnail are the database columns.
First problem I see is your data is strings. Get rid of the ' quotes
$.ajax({
type: "POST",
data: { title: oembed.title, thumbnail_url: oembed.thumbnail_url}
});
I'm going to assume you need to incorporate some user-supplied data into the new DB object - otherwise, it would be way easier to just create it from Rails.
If you're using entirely user-supplied data, you can use the serialize() method (use hidden fields for server-generated stuff):
jQuery.ajax({
url: '/path/to/whatever',
data: $('#MyForm').serialize(),
type: 'POST'
});
Or you could use the jQuery Form Plugin - it'll let you easily combine user-supplied data with server-generated data. For example:
$('#MyForm').ajaxForm({
//Hardcoded/server-generated stuff goes in here
//(and will be added to the data from the form inputs):
data: {title: oembed.title},
type: 'POST'
});
The ajaxForm() function will set up the form and its defaults, and sends an AJAX call when the user hits the submit button (see also: ajaxSubmit()).
On the Rails side, everything should work exactly the same as if the user had submitted the form normally (though you might want to just respond with a status code/message - no call for a redirect or page render).
Hope this helps!
PS: From your example, it looks like you might be able to use data: oembed in your AJAX calls. This will submit all oembed's attributes...
so I'm trying to figure out how to use the returned json information. I want to pull the city and state information, then reference the city, and state in an autofill concept elsewhere in my html. Problem is, I don't have an object to reference.
This is where I'm at so far, using a AJAX request
$.ajax({
dataType: "json",
url: ("http://ZiptasticAPI.com/" + $("#zipcode").val()),
data: {},
success: function (resultdata) {
console.info(resultdata);}
If you want to fill a form with the data retrieved of the AJAX, depending of the type of data (if it is a input, checkbox, select, etc) option. As I see that you are using jQuery.
Example, to set the value to a input text:
$('input.foo').val(resultdata.city);
in case that input is select:
$("select").val(resultdata.state); // this only works if the value of the option is CA
And so on.
After your console.log add this:
data = JSON.parse(resultdata); // declare data elsewhere to make available
You can then access it with
data.country
data.state ... etc
and use those values to populate your form.