Backbone.js without REST using ASP .net webservice - javascript

(sorry for the english)
I have a ASP .net webservice that get data from a oracle database returning JSON data.
TestWebService.asmx/getUserData
I test this using simply ajax request with jQuery
$.ajax({
type:"POST",
data:"{}",
dataType:"json",
contentType:"application/json; charset=utf-8",
url:"TestWebService.asmx/getUserData",
success:function(data){
console.log(data.d);
}
});
This work.
But now i want to try use Backbone.js
The Application have this: User data, Articles and Buy Order where a Buy order is a collection of Articles, so i think in this models for Backbone
User = Backbone.Model.extend({})
Article = Backbone.Model.extend({})
ArticleCollection = Backbone.Collection.extend({})
BuyOrder = Backbone.Model.extend({})
BuyOrderCollection = Backbone.Collection.extend({})
The Views are just 2. A Form where i show the User Data and inputs to add Articles and create the Buy Order and a Visualize view to show the Buy Orders where the user can see an check the content of one buy order clicking in the code.
The UserData, and part of the Article Data are get from the service: (User Data like name and Article Data like code, description, price, etc).
¿How can i populate the Backbone models with this data?
Thanks in advance.

So, basically, you want to override Backbone.sync. It is the thing that is currently doing your RESTful stuff (GET/POST/PUT/DELETE) via the $.ajax function as well. See how it is implemented by default: http://documentcloud.github.com/backbone/docs/backbone.html#section-134
As you can tell, it is really quite simple... about 30 or so lines of code to map create/update/delete/read to post/put/delete/get in $.ajax.
Now that you have seen how they do it, you just implement your own using the same pattern:
Backbone.sync = function(method, model, options) {
// your implementation
};
Once you do that, you are golden. Your models will do all the CRUD that you want them to, abstracted through your implementation of Backbone.sync.

Related

Ajax Parameter Being Received as {string[0[} in MVC Controller

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

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

WebApi 2.1 + Backbone.js 1.1.2: sync everything at once

Disclaimer: I'm a WebApi/BackBone beginner, so the question might be a bit odd since there is a lot about these components I don't really know and/or understand.
It would be nice to have the possibility to issue just ONE sync() call to the server to synchronize everything. I mean, when I saw sync() method, at first I thought it's used like that, but as soon as I saw the "create", "update", "delete" params I realized it's not. But there is an underlying problem related to Backbones default implementation for DELETE.
I've learned that classic implementation of Backbone.js allows one deleted (destroyed) model at a time to be sync'ed to the server. Created/modified (POST/PUT operations) content is sent in the request body itself, so the JSON is filled with the data and deserialized by WebApi model binding on the server. It doesn't work like that for DELETE, since body is always empty and reference to the model is made by URL parameters in query string. So, I guess to achieve that functionality, the request for DELETE should be sent in body as well as for POST/PUT.
Is there a possibility to change all of this behavior AND make it work with WebApi? I googled for that stuff already, but can't find anything to point me to the right direction.
What I have until now is a Backbone model, collection and a view set up.
Backbone.sync("create", this.collection); is called by the view on button click.
On the server side there is a WebApi controller set up with scaffolded methods:
// GET
public IEnumerable<Ponuda> Get()
{
return _storageService.GetPonude().ToList();
}
// GET
public Ponuda Get(int id)
{
return (Ponuda)_storageService.GetPonuda(id);
}
// POST
public void Post([FromBody]IEnumerable<Ponuda> value)
{
_storageService.CreatePonude(value);
}
// PUT
public void Put([FromBody]IEnumerable<Ponuda> value)
{
_storageService.ModifyPonude(value);
}
// DELETE
public void Delete(IEnumerable<int> value)
{
_storageService.RemovePonude(value);
}
EDIT: I'm reading about Marionette.js and it seems to offer standard model/view related functionalities out of the box. However, I still can't see the possibility to save/sync e.g. the entire modified collection at once.
To sync all contents at once :
For POST and PUT Http methods, you can use Backbone.Sync API.
For DELETE, you can directly use the ajax API for deleting the content in the server and use Backbone Collection remove API to delete the content in the client side.
I have written skeleton code which demonstrates on how to achieve the functionality:
var PersonModel = Backbone.Model.extend({
url: '/demo',
defaults: {
"id": 0,
"name": "",
"age": 0
}
});
var PersonCollection = Backbone.Collection.extend({
url: '/demo',
model: PersonModel
});
var model1 = new PersonModel({"name": "John", "age": 30});
var model2 = new PersonModel({"name": "Joseph", "age": 30});
var collection = new PersonCollection();
// model will be added locally on client side. It will not sync to the server.
collection.add(model1);
collection.add(model2);
// POST. This will create both the models together using a single REST API request.
Backbone.sync('create', collection);
// PUT. This will update both the models together using a single REST API request.
Backbone.sync('update', collection);
// Extract the model ids to be deleted
var modelIds = [model1.get('id'), model2.get('id')];
$.ajax({
method: 'DELETE',
url: '/demo',
data: JSON.stringify(modelIds), // This will add ids to the request body
contentType: 'application/json',
success: function() {
// On successful deletion on server end, delete the models locally.
collection.remove([model1, model2]);
}
});
Regarding the WebApi, since I have not worked on it, will not be able to guide you. Having worked on Spring Rest API, I can tell you above functionality should work with the WebApi.

Ember.js Search Model Verbs

The tutorials & guides that I've found suggest that Ember.js models are very data centric, in that you have data in the browser that is persisted to the server and/or a model is filled with data from the server.
How about something that is more verb centric? For example, my case is that, so far, I have a "Search" model, where a search has a query, a state ("beforesearch","duringsearch", etc...), and, hopefully, some results. I want for the search to then "runQuery", which fires off an ajax request to the server, which returns and fills the model with the results, and changes its state to "aftersearch".
What's the best way of handling such verbs on models? Should the "runQuery" go via ember-data, or just manually fired off using $.ajax or similar? Am I maybe thinking about models in the wrong way, and this should actually go via a controller?
Edit: After reading up a bit on REST, I think what I'm wanting is to POST to a "controller" resource. So, for example:
POST: /searches (to create a search)
POST: /searches/1/run (to execute search 1's "run" controller
Does Ember.js / ember-data have a recommended way of calling controller resources like this?
Ember-data is very oriented around using model objects that contain various information fields and relationships and are defined by a unique id. Half of my API is like what ember-data expects and half is like you described, it is more about data processing or performing a calculation than creating/retrieving/updating/deleting a data object that has an id. It doesn't make sense to treat these calculations the same and assign it an id and persist it in the database.
In my case, since I have both ember-data style data objects and calculation functionality I use a mix of ember-data and custom ajax requests. I have relational data stored that is retrieved by ember-data but I augment the models to include access to the calculation portions.
For example:
App.Event = DS.Model.extend({
name: DS.attr('string'),
items: DS.hasMany('App.Item'),
...etc...
searchData: null,
searchInEvent: function(data) {
var _this = this;
return $.ajax({
url: "/api/events/" + this.get('id') + "/search/",
dataType: 'json',
type: 'POST',
data: data
}).then(function(result){
_this.set('searchData', result);
});
}
});
App.Event is a normal ember-data model and is loaded by the router through the usual ember conventions, and as the various controllers need access to the search functionality they can access it through searchInEvent and searchData that were added to the model.

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

Categories