Backbone Model URL responseText - json

I have the following:
DiaryEntries.Collection = Backbone.Collection.extend({
url: '/rest/diary/'
});
So I initiate a collection like so:
var collection = new DiaryEntries.Collection()
And then collection.fetch() returns this:
Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
overrideMimeType: function ( type ) {
pipe: function ( /* fnDone, fnFail, fnProgress */ ) {
progress: function () {
promise: function ( obj ) {
readyState: 4
responseJSON: Array[1]
responseText: "[{"DEID":"1","DEOwnerID":"1","DEClientID":null,"DEDateStart":"2013-06-28 00:00:00","DEDateEnd":"2013-06-29 00:00:00","DEEventLocationID":null,"DEJobID":null,"DEName":"Ricky's test event","DELocation":"Kettering","DEFurtherDetails":"None","DEVisibility":"0","DENotes":"None","DEType":"1"}]"
setRequestHeader: function ( name, value ) {
state: function () {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( /* fnDone, fnFail, fnProgress */ ) {
__proto__: Object
Why is it not just getting the response? I have a mime type of application/json

Call to the server are AJAX calls (asynchronous). What fetch returns is the XHR object, not the response (as the server hasn't responded yet). To do something once the client received the data, use a callback or a listener (or something similar).
For example, you can declare a parse method to see the reponse (it's not the actual goal of the method, but whatever):
DiaryEntries.Collection = Backbone.Collection.extend({
url: '/rest/diary/',
parse: function(response) {console.log(response); return response;}
});

Related

Nested AJAX call in React redux

So I'm working on some demoware and I have two AJAX calls, the first is just a last modified date, to let me know whether to fetch data from the second. This works, but I feel like there's a smarter way to do this for real applications, and I'm just a UI monkey trying to come up in the world, any advice is much appreciated.
componentDidMount() {
this.getJson();
setInterval(this.getJson.bind(this), 1000);
}
getJson() {
const el = this;
const isModified = (date) => {
let mod = false;
if (this.state.lastModified == date) {
console.log('no change');
} else {
mod = true;
console.log({
'previously modified': this.state.lastModified,
'newly modified': date
});
el.setState({lastModified: date});
}
return mod;
}
this.serverRequest = $.ajax({
url: 'URL_LAST_MODIFIED',
success: function(result) {
const lastModified = $.parseJSON(result).LastModifiedDateTime;
if (isModified(lastModified)) {
$.ajax({
url: 'URL_DATA',
success: function(result2) {
const result2Obj = $.parseJSON(result2);
el.setState({data: result2Obj});
},
error: function(xhr, status, err) {
alert(err.toString());
}
})
}
},
error: function(xhr, status, err) {
}
});
}
I think it is realted to this:
https://github.com/reactjs/redux/issues/1676
The idea is create a action for the first ajax call... and on success dispatch another action to execute the second call.

Passing a parameter along with callback?

This is my code:
var title = 'test'
function onlineStatus(callback){
$.ajax({
url: "https://blabla,
cache: false,
success: callback
});
onlineStatus(function(test) {
// doing stuff with `test`
$('#forTest').attr('title', title);
});
The problem is that the onlineStatus call doesn't see title, which is correct, because it is out of scope. Is there a way to pass it into the function, so that the title is seen?
function statusCheck (test) {
console.log(test);
}
function onlineStatus (callback) {
callback (arguments[1]);
}
onlineStatus (statusCheck, "test");

Passing an Object from Angular Post to .Net ASMX

I have been trying to pass an object as a Post parameter to .NET asmx web service. I can pass primitive types such as int, string as parameters but I would like to pass the whole object because my class contains a lot of properties and it is very time consuming to pass each property individually.
My c# web service code is:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL AddContact(ContactBLL Contact)
{
//add contact and return the contact object
}
I have added following statement at the top of the web service class:
[System.Web.Script.Services.ScriptService]
I have a second function in the web service which I call when my page loads in order to get a json ContactBLL object.
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public ContactBLL GetContact(int ContactID)
{
//return contact
}
I use following functions in my factory to call asmx web methods:
factory.GetContactInfo = function (ContactID) {
return $http.post(serviceBase + 'GetContact', { ContactID: ContactID }).then(function (results) {
return results.data;
});
};
factory.InsertContact = function (Contact) {
return $http.post(serviceBase + 'AddContact', { ContactBLL: Contact }).then(function (results) {
return results.data;
});
};
In my controller, the GetContact function is called when the page loads and it returns the correct data to initialise the Contact object. I then call AddContact function and pass the object to factory function. The control doesn't get to the web service and I see the 500 message in chrome with the following message:
Message: "Invalid web service call, missing value for parameter: 'Contact'."
Here is the code for the controller:
var ContactController = function ($scope, $location, $http, $window, ContactService) {
var Contact;
Initialise();
function Initialise() {
Contact = {};
GetContact(-1);
}
function GetContact(ContactID) {
ContactService.GetContactInfo(ContactID)
.then(function (data) {
//do something
}, function (error) {
$window.alert('Sorry, an error occurred: ' + error.data.message);
});
}
$scope.AddContactRecord = function () {
ContactService.InsertContact(Contact)
.then(function (data) {
//do something
}, function (error) {
$window.alert('Sorry, an error occurred: ' + error.data.message);
});
}
}
Please let me know if I am doing anything wrong or an easy way for passing tens of properties via Post call. The GetContact call works fine, however, I get error on InsertContact call.
I have found the reason for the error. I was passing the datatype (ContactBLL) instead of the name (Contact) of the paramter in the AddContact function of my factory. The correct code is below:
factory.InsertContact = function (Contact) {
return $http.post(serviceBase + 'AddContact', { Contact: Contact }).then(function (results) {
return results.data;
});
};

JavaScript, Web API import with D3 (Data Driven Document)

I'd like to import data from an Web API (JSON format) and use it for visualization. As you see in the following code, I've already implemented everything and it works (almost).
Question: The dataExport isn't the same as data. Why? How can I change my code so that dataExport the same like data?
Code:
var dataExport = d3.json("http://link to the Server...", function(error, data){
if(error) {
console.log(error);
} else {
console.log(data);
console.log(data.collection.items);
}
});
console.log(dataExport);
Console.log(data);
Object {collection: Object}
collection: Object
href: "http://link to the Server..."
items: Array[50]
links: Array[1]
queries: Array[1]
version: "1.0"
__proto__: Object
__proto__: Object
Console.log(dataExport);
Object {header: function, mimeType: function, responseType: function, response: function, get: function…}
abort: function (){return c.abort(),i}
get: function (){return i.send.apply(i,[n].concat(Qo(arguments)))}
header: function (n,t){return n=(n+"").toLowerCase(),arguments.length<2?a[n]:(null==t?delete a[n]:a[n]=t+"",i)}
mimeType: function (n){return arguments.length?(t=null==n?null:n+"",i):t}
on: function (){var r=e.apply(t,arguments);return r===t?n:r}
post: function (){return i.send.apply(i,[n].concat(Qo(arguments)))}
response: function (n){return e=n,i}
responseType: function (n){return arguments.length?(s=n,i):s}
send: function (e,r,u){if(2===arguments.length&&"function"==typeof r&&(u=r,r=null),c.open(e,n,!0),null==t||"accept"in a||(a.accept=t+",*/*"),c.setRequestHeader)for(var l in a)c.setRequestHeader(l,a[l]);return null!=t&&c.overrideMimeType&&c.overrideMimeType(t),null!=s&&(c.responseType=s),null!=u&&i.on("error",u).on("load",function(n){u(null,n)}),o.beforesend.call(i,c),c.send(null==r?null:r),i}
__proto__: Object
Thanks!
because you store the whole parsing-process in your dataStore-variable, while the data-variable only contains the data you call within the d3.json - as it should be.
you don't need to use another variable, so just try
d3.json("http://link to the Server...", function(error, dataStore){
if(error) {
console.log(error);
} else {
console.log(dataStore);
console.log(dataStore.collection.items);
}
});
dataStore should contain the wanted results
edit: to access it outside the d3.json
var dataStore; //declare a global variable somewhere at the beginning of your script
and then
d3.json("http://link to the Server...", function(error, data){
if(error) {
console.log(error);
} else {
dataStore=data;
}
});
console.log(dataStore);
console.log(dataStore.collection.items);

jquery -jtable- listAction get object from javascript function

Is it possible that listAction not call server function use AJAX , and the function will call to javascript function that return object ?
$('#ExecActDelays').jtable({
actions: {
listAction://get object from javascript no call server method
},
///...
can help me?
thank
i solve my proble, by edit jquery.jtable.js
my script:
function getObject(){
var result={};
result.Result="OK";
var array=[];
//...
{
array.push(new object...);
}
result.Records=array;
return result;
}
$('#ExecActDelays').jtable({
actions: {
listAction: getObject()
},
and in jquery.jtable.js i change
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
to:(line 442)
if (typeof loadUrl == "string") {
self._ajax({
url: loadUrl,
data: self._lastPostData,
success: function (data) {
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
}
else {//no from server method
self._hideBusy();
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(loadUrl.Records);
self._onRecordsLoaded(loadUrl);
//Call complete callback
if (completeCallback) {
completeCallback();
}
}
my complete my jquery.jtable.js
Try do this
function foo(){
return object;// JSON object
}
$('#ExecActDelays').jtable({
actions: {
listAction: foo()
},
///...
OR try this too
var object = null;
function foo(){
object = objectJSON;
}
$('#ExecActDelays').jtable({
actions: {
listAction: object
},
///...