ng-grid does not refresh with $resource service - ng-grid

ng-grid is not updating my list.
I am trying to create a object in one view and on creating I redirect my page to list view where i want to see all my added objects. I am able to create a new object through api call and on success I call the view which should ideally show list of all objects, however I dont see the latest added object (On refresh I do see the same object)
Save function call in my create view:
$scope.save = function() {
SERVICE.$save();
$location.path('listview');
}
ListViewCtrl has and init() function which sets the ng grid option
SERVICE.query().
$promise.then(function (data) {
$scope.ngGridOptionVariable = data;
});
I dont see the new data that is being added
Any clue how to handle this issue?

Related

How do i request an Array from the controller from inside a javascript code

I am using Spring boot, JPA with mysql, and thymeleaf and openlayers for the map.
So i have a map, and on this map there are dynamically generated markers for different places. What I want is when I click any of those markers to send the name of the marker to my controller and in response get an array of fishes that can be caught in this specific area and then display the names and pictures of the fishes in a dynamically generated list located on the sidebar . I cant think on how I can achieve that. Ive made a HTML page to show how I want it to look.
I was thinking about making a get request and giving the name as a path variable but then idk how I can do that request from the javascript when the button is clicked. Any ideas or concepts that I can read about are apreciated.
Most DOM elements in html are accessible in javascript via something like document.getelementbyid and typically if I remember this correctly most of the objects you can do something like domobject.addEventListener("click", myScript); and in myScripy make an http call to spring requesting the list of fish. I recommend setting some breakpoints in your JavaScript code via the dev console in your browser and looking through some of the objects that are produced
You can make a get request like described here. developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Clicking on the markers would be similar to this example https://openlayers.org/en/latest/examples/icon.html, but instead of showing a popup you make a GET request for more data
map.on('click', function (evt) {
const feature = map.forEachFeatureAtPixel(evt.pixel, function (feature) {
return feature;
});
if (feature) {
const name = feature.get('name');
// now make get request
// ....
}
});
If you are requesting an image you could use xhr as in https://openlayers.org/en/latest/apidoc/module-ol_Tile.html#~LoadFunction or you could use fetch, similar to:
fetch(url).then(function(response) {
if (response.ok) {
return response.blob();
}
}).then(function(result) {
if (result) {
const imagesrc = URL.createObjectURL(result);
}
});

ej-grid grid in .net core auto generate after ajax call

I am trying to use a syncfusion ej-grid to auto generate a grid using data retrieved from an ajax call. In doing so, I am running into a problem.
I am getting an error message when the page first renders saying "DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid". While I understand this, I am struggling because I don't know anything about the datasource until after the ajax call is returned.
This is a .NET CORE 5 razor page....
My razor page:
(note: 'data' below is a json serialized System.Data.DataTable).
<ej-grid id="gridResults" allowPaging="true"></ej-grid>
<script type="text/javascript>
function ajaxResponse(data) {
$('#gridResults').ejGrid({
datasource: data
});
}
</script>
So my questions are two-fold:
First, is there a way to bypass the initial error I am getting about the datasource not being set (since I don't have a datasource yet)...
Second, Will my approach of providing a serialized DataTable work, or do I need to do something different to pass the data via Javascript like this?
Right now when I return from the ajax call, I don't get any errors, but nothing happens...
Thanks in advance!
Greetings from Syncfusion Support.
Query 1: I am getting an error message when the page first renders saying "DataSource must not be empty at initial load since columns are generated from dataSource in AutoGenerate Column Grid".
This issue will occur when we do not bind dataSource and define columns to the Grid. For rendering Grid, we should either define columns or bind data source at the initial rendering.
Since you are not binding data in initial rendering, we suggest you to define columns so that Grid will be rendered without any errors.
Query 2: Will my approach of providing a serialized DataTable work, or do I need to do something different to pass the data via Javascript like this?
For binding data table to Grid after serializing it, we should call the dataSource method of grid and pass the data as parameter to it as shown in below code,
<ej-button id="repeatButton" text="click" size="Medium" show-rounded-corner="true" click="btnClick" />
<ej-grid id="FlatGrid" allow-paging="true">
<e-columns>
<e-column field="No" header-text="Order ID" is-primary-key="true"></e-column>
<e-column field="Name" header-text="Employee ID"></e-column>
</e-columns>
</ej-grid>
<script>
function btnClick(args) {
$.ajax({
url: '/Grid/DataSource',
dataType: "json",
type: 'POST',
success: function (data) {
var grid = $('.e-grid').data("ejGrid"); // grid instance
grid.dataSource(data);
// update grid data source by calling dataSource method and passing data
}
})
}
</script>
[HttpPost]
public ActionResult DataSource()
{
System.Data.DataTable dt = new DataTable("Table1");
DataColumn cl = new DataColumn("No");
dt.Columns.Add(cl);
cl = new DataColumn("Name");
dt.Columns.Add(cl);
DataRow dataRow = dt.NewRow();
dataRow[0] = 1;
dataRow[1] = "John";
dt.Rows.Add(dataRow);
var data1 = Utils.DataTableToJson(dt); // method to serialize data table
return Json(data1); // fetching and returning boolean column
}
In the above code example, we have fetched data using ajax call in button click and bind it to grid using dataSource method.
Please check the below API help documentation,
https://help.syncfusion.com/api/js/ejgrid#methods:datasource
Kindly get back to us for further assistance.
Regards,
Padmavathy Kamalanathan

backbone.js , waiting for external post request to complete

I have an image uploader on my index.php page, when the image starts uploading (initiated by dragging image onto upload box) , the POST request is created (FYI HTML5 + php Uploader)
POST http://localhost:8888/backbone_images/post_file.php
Inside of my post_file.php , I retrieve the URL of my uploaded image by inserting it in my exit_status, than later in my script assigning it to a global javascript variable 'globe'
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status($pic['name']);
}
Inside of my backbone script file, I check for the drop event into the dropbox, which works,
App.Views.AddImage = Backbone.View.extend({
el: '#addImage',
events: {
'drop': 'submit'
},
so the image has been dragged onto the dropbox, and I call my submit function to create a new model
and assign the url of the new image (which I pass through a javascript variable)
to the url of my new model
submit: function(e) {
e.preventDefault(); // preventing default submission..
var newImage = globe; // assign globe --url of the newly created image--to new model
var imager = new App.Models.Person({ url: newImage });//creating a new img object
this.collection.add(imager);
}
The problem is that when my backbone submit function is triggered after an image is dropped, my POST to /post_file.php hasn't run yet, as a result my variable 'globe' doesn't contain the new URL, and my newly created model ends up lacking a url
So question: is there any way for me to wait for the POST to finish within my backbone events before executing my 'submit' function, after an image drop?
I tried to use: $.when( $.ajax("/post_file.php") ) inside of my submit function, but all this does is run another POST request, leaves my variable value, than run the original POST request retrieving the image URL that I'm waiting for.
My preferred workflow would be
a. drag/upload image, (POST performs)
b. new model is added to
collection with URL of uploaded image,
but I end having to add an additional click function first otherwise the POST doesn't finish
a. drag/upload image, (POST peforms)
b. click on a submit button
c. model is added to collection

Backbone JS where to put Application main logic

Using Backbone i'm starting to build an App where i have everything cleanly separated. But now i have the following question. Where should i put the App main logic, in the views or in the model.
For example i have a view and a model, which are binded to a button and when i click that button i have to make
$.ajax(params)
do i put that in the view or the view calls a method with :
this.model.doAction(params)
which do you think is the best approach?
You can define an events property in the view which is of the format {"event selector": "callback"} for eg. {"click .collapse": "collapse"} where collapse would be a function defined as a property of the view. Then write your ajax request code in this callback function.
Also, unless I am missing something, "binding a view and model to a button" doesn't sound correct Backbone way to me. Instead you should think of one instance of model associated with one instance of the view. Whenever an attribute of the the model instance changes, a model change event will be triggered. You can bind a view function to this event so that change in the model is reflected in the view. Here is a quick example
var Book = Backbone.Model.extend({
// ...
});
var BookView = Backbone.View.extend({
initialize: function () {
this.model.bind('change', this.render, this);
},
render: function () {
// here, make changes to the dom as per changes in model
}
});
To associate a model with a view instance, you can pass the it while instantiating a new
view object..
var book = new Book({
title: "A great book"
});
var view = new BookView({model: book});
view.model.set('author', 'AGreatAuthor');
The set function call will fire change event and will result in render function of view
to be called.
Refer to the annotated source of Todos app example for a complete example.

How to bind events to element generated by ajax

I am using RenderPartial to generate CListView and all the contents generated properly and good pagination is working fine too. But when I added my custom JS to elements generated by the CListview it works fine for the the fist page content but when i use pagination and click to page 2 then the JS binding fails.
Is there any other way to bind custom event to elements generated in YII CListview I had tried using live, and on nothing work for me here is my js file.
I think I have to call my function on every ajax load in but how can I achieve in yii
This is the script I am using to update ratings on server with button click and this the element for which these forms and buttons are defined are generated by CListview in yii
$(document).ready(function(){
$('form[id^="rating_formup_"]').each(function() {
$(this).live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
});
You can also try CGridView.afterAjaxUpdate:
'afterAjaxUpdate' => 'js:applyEventHandlers'
The $.each method will loop only on existing elements, so the live binder will never see the ajax-generated content.
Why don't you try it like this:
$(document).ready(function(){
$('form[id^="rating_formup_"]').live('click', function() {
alert("hi");
var profileid= $(this).find('#profile_id').attr('value');
var userid= $(this).find('#user_id').attr('value');
console.log(userid);
var data = new Object();
data.profile_id=profileid;
data.user_id=userid;
data.liked="Liked";
$.post('profile_rating_ajax.php', data, handleAjaxResponse);
return false;
});
});
This problem can be solved by two ways:
Use 'onclick' html definitions for every item that is going to receive that event, and when generating the element, pass the id of the $data to the js function. For example, inside the 'view' page:
echo CHtml::htmlButton('click me', array('onclick'=>'myFunction('.$data->id.')');
Bind event handlers to 'body' as the framework does. They'll survive after ajax updates:
$('body').on('click','#myUniqueId',funcion(){...});

Resources