My initial grid is build
$("#dims_list").jqGrid({
url: "ajax_get_dims_for_grid.php",
postData: {'dims_guid': $('#dims_guid').val()},
When I refresh the grid with a new parameter the original value is sent (persists)
var dims_guid = $("#dims_guid").val(); // New value for the grid
$("#dims_list").jqGrid('setGridParam',{"dims_guid":dims_guid}).trigger('reloadGrid');
I have monitored this in the Chrome developer window and can see the new value in var dims_guid but the old value is posted to the page that retrieves the data from the database.
I have just moved from freeJQgrid to Guriddo jqGrid
I actually tried the following code
var url="ajax_get_dims_for_grid.php?dims_guid="+$("#dims_guid").val();
$("#dims_list").jqGrid('setGridParam',{"url":url}).trigger('reloadGrid');
And in Chrome the query string was duplicated with the old one taking precedence
Query String Parameters
dims_guid: 100d7c6d-bcba-4b13-8832-f9de7794498c
dims_guid: dbc02dbe-e3d8-4b7d-8389-2678221ea189
_search: false
nd: 1586531572226
rows: 20
page: 1
sidx:
sord: asc
Is this a known issue?
If a postData is used to send parameters to the server this parameter (postData) extend every time the parameters that are posted to the server if a request is made. As per documentation. This array is appended directly to the url.
The problem you have is that you do not have correctly set the new parameter when you trigger the grid. What you do is:
var dims_guid = $("#dims_guid").val(); // New value for the grid
$("#dims_list").jqGrid('setGridParam' {"dims_guid":dims_guid}).trigger('reloadGrid');
This way you append new parameter th the grid and do not have change the existing one. In order to make it correct it is needed to change this in postData like this
var dims_guid = $("#dims_guid").val(); // New value for the grid
$("#dims_list").jqGrid('setGridParam',{ "postData" : { "dims_guid":dims_guid} }).trigger('reloadGrid');
I hope you understand the difference.
Another possible solution is to not use postData (remove postData from options) , but use url only to change the parameter, like you do in your second published code. Like this:
$("#dims_list").jqGrid({
url: "ajax_get_dims_for_grid.php?dims_guid="+$("#dims_guid").val(),
and then
var url="ajax_get_dims_for_grid.php?dims_guid="+$("#dims_guid").val();
$("#dims_list").jqGrid('setGridParam',{"url":url}).trigger('reloadGrid');
Related
First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.
I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.
I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.
//Create array based on the collections list
const collectionsArray = Array.from(collectionList);
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: collectionsArray,
})
.done(function (msg) {
alert('Sent');
});
However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.
Here is the method which is in the Controller, with my mouse hovered over the parameter:
Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.
I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn't made a difference.
I have been Googling the issue & reading other StackOverflow posts. I've tried things like adding/changing contentType, dataType, adding 'traditional: true', using JSON.stringify, putting 'data: { collections: collectionsArray }' in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.
I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I'm sure it's something minor.
UPDATE: Here is the code which explains what the collectionList object is:
//Re-assign SortID's via each row's ID value
var collectionList = document.querySelectorAll(".collection-row");
for (var i = 1; i <= collectionList.length; i++) {
collectionList[i - 1].setAttribute('id', i);
}
What I am doing is getting a list off the screen and then re-assigning the ID value, because the point of this screen is to change the sort order of the list. So I'm using the ID field to update the sort order, and then I plan to pass the new IDs and names to the DB, once I can get the array to pass through.
UPDATE: SOLVED!
I want to post this follow up in case anyone else runs into a similar issue.
Thanks to #freedomn-m for their guidance!
So I took the NodeList object (collectionList) and converted it to a 2-dimensional array, pulling out only the fields I need, and then I passed that array onto the controller. My previous efforts were causing me to push all sorts of junk that was not being understood by the system.
//Create a 2-dimensional array based on the collections list
const collectionArray = [];
for (var i = 0; i < collectionList.length; i++) {
collectionArray.push([collectionList[i].id, collectionList[i].children[1].innerHTML]);
}
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: { collections: collectionArray }
})
.done(function (msg) {
alert('Sent');
});
2-d array is coming through to the Controller successfully
Hi I'm working with djangorestframework-datatables and datatables' JQuery plugin.
I'm loading a large table (about 15000 entries, paginated) with the serverSide option enabled. I enabled this option because client side processing was taking too long to load the table (even with deferLoading).
I want to retrieve data from the following URL:
/api/device_input/?format=datatables&device_id=something
// device_id can be 1, 2, 3 and so on.
The problem is, I can't figure out how I can dynamically change the device_id parameter. That parameter is definitely user input. Here's how I was previously doing it (with client side processing):
1) User enters device ID into a form. Form gets submitted.
2) Django view takes the POST request and returns the filtered queryset to the template.
3) The queryset populates the HTML table values and datatables handles the rest (pagination etc)
But now with server side processing, I don't need the django view to return any querysets. I can just get data through ajax. The behaviour I want is:
1) User opens page, an empty datatable is displayed, with a prompt to enter device ID.
2) User enters device ID, and the datatable is loaded with records for that device id.
But the datatables ajax request only gets invoked when someone messes with the datatable (such as change page or select page length). I want to invoke the ajax request when someone enters device_id into my form and dynamically tell ajax to create the right URL.
Here's what my javascript looks like:
<!-- Javascript function to initialize the datatable -->
<script>
var device_id = document.getElementById("id_input").value
$(document).ready(function() {
$("#device_inputs_table").DataTable({
"lengthMenu": [
[10, 20, 30, -1],
[10, 20, 30, "All"]
],
fixedHeader: {
headerOffset: 62
},
"order": [
[0, "desc"]
],
"serverSide": true,
"ajax": "/api/device_input/?format=datatables&device_id=" + device_id, // need to add a number at the end that user will input
"columns": [
// All my table columns
]
});
});
</script>
I'm sure this is simple to do, but my unfamiliarity with ajax and javascript has me scratching my head, any help is appreciated!
UPDATE: I tried adding a simple variable to get device_id from the form element, but it doesn't get added to my URL... how do I print my URL out on the dom? (I'm only checking through the network tab on chrome dev tools...) Of course my form doesn't even invoke the ajax request so that's another issue.
First you need to declare a variable to hold the DataTable and call it from your javascript.
Example:
var deviceInputsTable = $('#device_inputs_table').DataTable({
// Rest of the table declaration goes here.
})
Then, you create a function that triggers to load data in your deviceInputsTable, something like:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID // (get this from the input)
// do the ajax call here and this is the important part:
success: function(data){
// This is just a rough scratch, but this is how you initially call the first data in the table, consequent calls will now be server-side since your device_id now has a value in the ajax call you showed above.
deviceInputsTable.clear().rows.add(data).draw()
}
}
I hope this helps.
EDIT, concerning your comment below:
You can use a normal jQuery ajax call. Something like this:
function loadDeviceInputsTableData(deviceID){
device_id = deviceID;
$.ajax({
type: 'GET',
url: `SomeURLhereAppendingthedeviceIDParameter`,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
// Transform the AJAX's response here and get the data to add to your data table below
deviceInputsTable.clear().rows.add(data).draw()
}
});
};
To trigger the ajax again on change of the input, you can call the on change function in jQuery.
$('#id_input').on("change",function(){
loadDeviceInputsTableData($('#id_input').val());
});
This issue was solved by using datatable's API, my question was about changing the ajax url dynamically upon user input. Here's what I did:
// Get device ID from wherever user inputs it, in my case it was a button with id: id_input
device_id = document.getElementById('id_input').value;
// Dynamically set your datatable's ajax URL to whatever you want. I concatenated the device id
// string with my url string. ajax.url("your URL") is enough to set the URL
// .load() is for getting data from the new URL you've just set.
$('#device_inputs_table').DataTable().ajax.url(
"/api/device_input/?format=datatables&device_id=" + device_id).load();
Doing this gave me the final URL: "/api/device_input/?format=datatables&device_id=1" (if user inputted 1) fixing my issue.
I set up a datatables that initially gets from server some data and represents it, but then everything is left to the client. Some options are:
serverSide: false,
sAjaxSource: mySource,
My $.fn.DataTable.version is 1.10.2.
Then I need to change, client-side, the aaData under the table because some working on data is performed. I need to update the DT to show the client-altered temporary data without send another request to server (for two reason: prevent useless traffic and because that data is being altered).
I am looking for a way to edit the underlying DT databean to edit it, so then calling again
myTable.draw();
on my table I obtain a refresh realtime without sending another get to the server.
The question is, can I access DT data array, and can I edit it?
How is it done if is possible?
EDIT: I need to feed the table the full bean array as it initially took from the server, same format. So individual row/cell add/edit and client-side building functions are not suitable in my case, unless I manually cicle all objects.
SOLUTION
Use the code below:
// Retrieve data
var data = table.ajax.json();
// Modify data
$.each(data.data, function(){
this[0] = 'John Smith';
});
// Clear table
table.clear();
// Add updated data
table.rows.add(data.data);
// Redraw table
table.draw();
DEMO
See this jsFiddle for code and demonstration.
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
I have a Grid and some options outside of the grid... my proxy is a POST Request to an ASPX page.
_store = new Ext.data.JsonStore({
proxy: new Ext.data.HttpProxy({
url: 'resultpage.aspx?initalparam=1...',
method: "POST"
}),
reader: _reader,...
What I want, it's when any of my options is selected, add that option as query string parameter (or post parameter) and made the post request.
REF: http://www.objis.com/formationextjs/lib/extjs-4.0.0/docs/api/Ext.grid.Panel.html
Note: the fallowing code DOESN'T Work is just ideas.***********
I am looking for something like:
myoption=...; //with DOM get option value
myurl = panelobj.getGrid().getStore().getProxy().getUrl();
panelobj.getGrid().getStore().getProxy().setUrl(myurl+"&myoption=" + myoption);
panelobj.Update();
or something more cool like:
Ext.create('...ON OPTION CLICK...', append("&myoption=" + myoption); submit();..)
Are you looking for this? http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.Ajax-cfg-extraParams
Each proxy has an extra parameters which can be added to each request.
I see this example http://www.sencha.com/forum/showthread.php?9067-Ext.data.HttpProxy-and-extraParams. Assume that ds is datastore:
ds.proxy.getConnection().request({extraParams: { testParam2: 200 }, method: 'POST',url: ds.proxy.buildUrl()});
That make the request but in the server side I can't read testParam2. Request["testParam2"] is null
That way wasn't working for me (I use version 3) so I using params instead of extraParams http://docs.sencha.com/ext-js/3-4/#!/api/Ext.data.Connection (Form Parameter: POST)
ds.proxy.getConnection().request({params: { testParam2: 200 }, method: 'POST',url: ds.proxy.buildUrl()});
other possibility is passing by url (QueryString Parameter: GET)
ds.proxy.getConnection().request(method: 'POST',url: ds.proxy.buildUrl() + '&testParam2=200'});
//***********
Other Problem:
With the code above, I can made the request... but it's totally independent from the grid... the data that is retrieve is unhandled... how make the grid do the request????? I don't know....
//**********
Solution:
Remove previous grid and add new one with new parameters! that work for me!