Refresh the Grid with the latest Data in DATABASE - jqxgrid

I am using a grid where I am passing the values to the controller class and saving the data to Database, but if I refresh the page the new changes are gone. The datas that were present before saving the grid will be displayed again.
Here is my Code Snippet of ajax call.
$("#btnSaveJobCode").click(function(){
var rowscount = $("#activityCodeRatioDistribution").jqxGrid('getdatainformation').rowscount;
var postdata = "";
var rows = $('#activityCodeRatioDistribution').jqxGrid('getrows');
$.ajax({
url : "saveActivityCodeRatio.htm",
cache : false,
type : "POST",
contentType : "application/json",
async : false,
dataType : "json",
data : JSON.stringify(rows)
}).done(function(data) {
alert("Save Successful.");
$('#activityCodeRatioDistribution').trigger( 'reloadGrid' );
}).fail(function() {alert("fail");});
});
What should I do to get the latest data from Database at each refresh? I am using Spring MVC and JQX grid. Thanks in advance.

to reload grid use below code after ajax call
$("#activityCodeRatioDistribution").jqxGrid('updatebounddata', 'cells');
If your jqxGrid source attribute is retrieving values from DB then above mentioned reload will update the latest values from DB.

The ajax call mentioned above are pretty well. I don't think it has any problem.
Are the data being saved in the database? First of all check that manually.
If no, then correct the code in the controller to save data.
If yes, then, you have to check the source of the jqxgrid which you haven't mentioned here.
In source, check the 'id' that you have mentioned. jqxgrid doesn't display rows if two rows have same 'id'.
So, it would be better if you had given the snippet of jqxgrid too.
Thanks

Related

Rails Frontend Trying to save autogenerated data to database without form

I'm new to ruby on rails. I'm trying to save data that is generated by itself to the database. i have looked into and found I was meant to use ajax, however all the videos/forums i have seen are example of ajax that use form and not refreshing page. i want to save data automatically without pressing submit.
Assume that the project is fresh project with postgresql as the database. I have created a database that can hold geo points by using postgis. i have created another page where it has map implemented where i can manully pin location. I want to save the manuuly pinned location to the database.
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
The e.latlng holds the geopoint, but i dont know how to save it the database if the user clicks anywhere on the map.
You don't need submit form to use ajax.
Basically what you want is add event listener to the map, and when user click then send ajax request to the controller.
For example, let's say that your map is inside div with id my-map.
If you use jQuery you can write something like this:
$('#my-map').on('click', function() {
# add your logic here
$.ajax({
url: 'your-url',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
'let': data you want to send to backend
})
}
Hope it works!
EDIT:
After I looked your code I found that you can not have jQuery in your project so you can not use jQuery ajax. You need use vanilla javascript. So instead this snippet above, you can write this.
var xhttp = new XMLHttpRequest();
const params = { saving_location: { geoPoints: e.latlng } }
xhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(http.responseText);
}
}
xhttp.open("POST", "/saving_locations", true);
xhttp.setRequestHeader('Content-Type', 'application/json', 'Accept', 'application/json');
xhttp.send(JSON.stringify(params));
Also add protect_from_forgery with: :null_session in your application controller and skip_before_action :verify_authenticity_token in your Saving Location controller.(under before_action).
Here is good blog post why you need this https://blog.nvisium.com/understanding-protectfromforgery
Please notice that you wan't save your database, because your geoPoints type in database is type of point and you send string to rails controller. I never work with points in rails so I can not help you here.(You can always add two columns in db, one for longitude and one for latitude and then store numbers instead point)

Axios Filter table returns counts but not data

I am currently working on ASP.Net MVC project. I am using Vuejs- Axios to get out data from entity data models. So...axios.get (gets the API) and now I am displaying my chart based on the value received.I am also on the same page showing table of data(same api results). The table has a search box, as user enter details to search a particular product my chart should show respective data. The problem is : I am in my javascript for table data: created api request , computed and used method(for filtering data). Now in the same filter method...when I do console.log(response.length)...I get correct filtered records....but when I write response.data….I get msg as undefined...
Kindly let a beginner like me know...how I can use this filtered data to create new chart...
If the filtered data can show correct length...it should be able to show data as well..
Thanks.
Edited: code here...
Javascript for chart( Vue-Chartjs):
var app = new Vue({
el:"#abc"
data:{
chart:null,
loading:false
},
created function(){
this.loading = true
axios.get('api/Work')
.then (function(response){
console.log(response.data)
calculated fields required.....
var ctx= document.getElementById("chart1")
chart....labels, datasets..etc....
Javascript - Loading table)
var app = new Vue({
el:"#abcd",
data(){
return:
fields:[
]},
created function(){
axios.get('api/Work')
.then (function(response){
console.log(response.data)
},
computed:{
mounted(){
this.totalrows= this.totalrows.length
}
},
methods:{
onfiltered(filteritems){
console.log(filteritems.length) =====returns correct table search - i.e filtered table length.....
console.log(filteritems.data)
=====returns undefined...........Stuck up here......
Once I get the filtered data , I can make the new chart based on the filtered values. So this is the place where I need clarifications.
Thanks.

ajax post to external database from Rails app

I am trying to insert data from a form built with Ruby on Rails to my SQL Server database. I have connected my database correctly and can pull data from it. I am now trying to post back to it. I am needing help with figuring out how to get the data from the form into the correct columns in my table in the database.
My ajax:
<script>
$('#Favorites').on('submit',function(event){
    var $form = $(this),
    data = $form.serialize();
    var url = 'http://localhost:3000/welcome/insert';
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(){
            
alert('Your form has been successfully submitted!');
document.getElementById('Favorites').reset();
window.location.reload();
        },
        fail:function(){
            alert('something went wrong...try again');
        }
    });
return false;
});
</script>
My controller function:
def insert
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link)
values ('I am cool','www.google.com')")
end
Currently I just have a dummy insert statement here to make sure that I can insert into the tables and I can. I just need to know how to break out the form values sent to the controller and how to tell Rails what table and columns to put those values into.
Rails will format the data for you. In controller like this:
{'Report_Name': 'some name', 'Report_link': 'www.example.com'}
and will be accessible via the params.
Your job is now to format the data correctly for the manual execution of the SQL query.
insert_values = "('%s', '%s')" % params['Report_Name'], params['Report_link']
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link) values #{insert_values}")
For the problem of which table to add to your DB server you could specify this in hidden fields in your form and every fieled should have a name, When you say $form.serialize(); it turns it to something like FirstName=Amr&SecondName=Adel and so on where FirstName is the name of the field and Amr is the value of the field, Then you put this serialization into a form of JSON format like {"data": $form.serialize()} and add dataType: "JSON" to your post request, In your Insert function you can get it through params[:data] and split it with& to be something like ['FirstName=Amr','SecondName=Adel'] and every element split it with = so you can get something like this [['FirstName','Amr'], ['SecondName','Adel']].
Hope this helps.

Client side processing in asp.net mvc 2.0

We are looking on an implementation in which data is processed at client side. Need inputs on how to process the data in JSON or any other type at client side in ASP.Net MVC 2.0.
Details: Inputs are accepted from the user and required to be saved in a list (or any other object) at the client side. Once the user actions are complete, the list object is required to be posted back to the server.
This is to avoid round trip to server and once all the data is ready in the list(objects) send it to server for processing
e.g. Accept Item(object) details as item name and item description. For first time add; in the same page store item in the list of object in client side itself. Every time item added, it is saved in list. At the same time list item is displayed on the same page in table format. After adding all the items when user submit data, list of object is posted back.
How can we achieve this in ASP.Net MVC 2.0 in a load balanced environment?
Any pointers would be very helpful
what kind of a list are you refering to here? like a bunch of check boxes? and in what format do you want to send the data to your server?
If you're using a bunch of checkboxes just post that data from the form straight to your action. I would suggest you just keep them in an array in javascript or add the values separated by a char like '|' or a ',' in a hidden text field and separate the items on the server side.
ASP.NET MVC 2 ships with the jQuery library, which you could use to perform this rough example...
var dataItems = new Array();
function AddDataItem(myDataItem) {
dataItems[dataItems.length] = myDataItem;
}
function SendDataItems() {
var data = "{";
for (var i = 0; i < dataItems.length; i++) {
data += ' question' + i + ': "' + dataItems[i] + '",';
}
// Remove the trailing comma:
data = data.substring(0, data.length-1) + "}";
$.ajax({
type: 'POST',
url: 'YourPage.html',
data: data,
success: function(response) {
alert(response);
},
dataType: "json"
});
}

jQuery Dialog posting of form fields

I'm trying to do some data entry via a jQuery modal Dialog. I was hoping to use something like the following to gather up my data for posting.
data = $('#myDialog').serialize();
However this results in nothing. If I reference just the containing form instead myDialog then I get all the fields on the page except those within my dialog.
What's the best way to gather up form fields within a dialog for an AJAX submission?
The reason this is happening is that dialog is actually removing your elements and adding them at root level in the document body. This is done so that the dialog script can be confident in its positioning (to be sure that the data being dialog'd isn't contained, say, in a relatively positioned element). This means that your fields are in fact no longer contained in your form.
You can still get their values through accessing the individual fields by id (or anything like it), but if you want to use a handy serialize function, you're going to need to have a form within the dialog.
I've just run into exactly the same problem and since I had too many fields in my dialog to reference them individually, what I did was wrap the dialog into a temporary form, serialize it and append the result to my original form's serialized data before doing the ajax call:
function getDialogData(dialogId) {
var tempForm = document.createElement("form");
tempForm.id = "tempForm";
tempForm.innerHTML = $(dialogId).html();
document.appendChild(tempForm);
var dialogData = $("#tempForm").serialize();
document.removeChild(tempForm);
return dialogData;
}
function submitForm() {
var data = $("#MyForm").serialize();
var dialogData = getDialogData("#MyDialog");
data += "&" + dialogData;
$.ajax({
url: "MyPage.aspx",
type: "POST",
data: data,
dataType: "html",
success: function(html) {
MyCallback(html);
}
});
}
Form element inside dialog is removed from form and moved to the end of the body. You need something like this.
$("#dialog_id").dialog().parent().appendTo($("#form_id"));
jQuery("#test").dialog({
autoResize:true,
width:500,
height:600,
modal: true,
bgiframe: true,
}).parent().appendTo("form");
This works like charm

Resources