First of all I shows the errors in your current code.
You use onchange="getStudents(this)
. It means that the parameter of getStudents
will be initialized with DOM element of the select #semester
. It means that you need use $(semester).val()
to get the value of selected option inside of getStudents
function instead of usage just semester
(see 'getStudents/?semester='+semester
).
The next problem is the following. The code $table.jqGrid({...});
creates the grid. The empty table <table id="students_list"></table>
will be converted to relatively complex structure of dives and tables during creating the grid. Because of that one can't make the same call at the second time. Such call will be just ignored. Instead of that one have to destroy the grid by usage of $("#students_list").jqGrid("GridUnload");
or better to create the grid ones and to reload it later.
You use mtype: 'POST'
option in jqGrid. It means thet jqGrid use HTTP POST to send some parameters to the server and place there in the body of the HTTP request. It's recommended to send custom parameter semester
in the same way. In the case you can use
var $table = $("#students_list");
$table.jqGrid({
url: "getStudents",
datatype: "json",
mtype: "POST",
postData: {
semester: function () {
return $("#semester").val(); // 1 or 2 from value attr of option
}
},
colNames: ["id", "Student", "Semester"],
colModel: [
{name: "studentId"},
{name: "studentName"},
{name: "semester"}
],
viewrecords: true,
gridview: true
});
The code will always send the current value of semester
select to the server. For example if the user will click on the column header to sort by it of to click on the next page button then new request with the current selected semester
will be sent to the server. I'd recommend you to read the old answer which describes the usage of functions in postData
more detailed.
To refresh the grid content immediately after changing the option one can use change
handle which trigger reloadGrid
:
$("#semester").change(function () {
$table.trigger("reloadGrid");
});
If you do need to place selected semester in the URL then you should remove postData
parameter from the option used during creating the grid and to use the following code in change
event handler:
$("#semester").change(function () {
$table.jqGrid("setGridParam", {
url: "getStudents/?semester=" + encodeURIComponent($("#semester").val())
}).trigger("reloadGrid");
});