I am beginning to learn writing apps using Monaca and I have a sample application I am editing which is written in Onsen and Angular.
I would like to be able to get data from a remote file on my server when needed as data will change regularly.
What is the correct way to get the data via Ajax or HTTPRequest? THe following doesn't seem to work.
function getDataPullCheck() {
alert("getDataPullCheck");
angular.request({
url: "https://***my file***",
method: 'POST',
success: function (data) {
console.log(data);
alert{data};
},
error: function (x, t, m) {
alert{'Error'};
}
});
}
Could someone correct my code or point me in the direction of a good tutorial for getting remote data into the app?
Many thanks.
So I realised this can be done in simple JS.
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = false;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
displayResult(jsonResponse,ptype);
}
};
xhttp.open("GET", <<MYFILE>>, true);
xhttp.send();
Related
i am getting response error please any one try to solve my problem. i am trying to solve that but i didn't solve this. please help me.
thanks in advance
$scope.init = {};
var Call = $resource('../api/Home', {}, { query: { method: 'POST', isArray: false} });
$scope.init = function () {
//alert("hi");
$scope.selected = "";
var x = $('#txtSearch').val();
var _ReqObj = new Object();
_ReqObj.id = x;
_ReqObj.Meth = "GJ";
Call.query({}, _ReqObj,
function (response) {
alert(response);
alert(_ReqObj);
if (response == '') {
// alert('no data');
window.location.replace("index.html");
}
else {
//$scope.click = response;
$scope.init = response;
}
},
function (error) {
window.location.replace("index.html");
}
);
};
The error message says: "Expected response to contain an object but got an array"
this means: Your request (Call.query) does expect a single object (you are setting isArray: false). But the server sends an array. So the server is not sending what the function expects!
There is some hints I want to give you:
Why are you using query? A query is normally used to get an array from the server, not a single object. Why are you using query at all?
Do you really want a single object or do you want a list of objects?
What is the server sending? Open the development console in your browser (ctr+alt+I in Chrome) and click on the Network tab. Click on the request (../api/Home) and check the response from the server. You should see the json objects or arrays the server sent as a response to your request.
I'm using staticFilesLoader with partialLoader wich is working really good! So the concept of addPart(home) method in partialLoader says that you do not need to load all the translate table.
Starting for that point. I'm gonna use a rest service now and my question is How to send to the rest service the parameter for just retrieving me the table translate for my specific section, in this example home.
Source Code from angular translate
function $translateUrlLoader($q, $http) {
'use strict';
return function (options) {
if (!options || !options.url) {
throw new Error('Couldn\'t use urlLoader since no url is given!');
}
var requestParams = {};
requestParams[options.queryParameter || 'lang'] = options.key;
return $http(angular.extend({
url: options.url,
params: requestParams,
method: 'GET'
}, options.$http))
.then(function(result) {
return result.data;
}, function () {
return $q.reject(options.key);
});
};
}
The code above doesn't have any extra parameter.
NOTE: Maybe in the specific case of urlLoader with partialLoader you should request all the table translate from the REST and only manage the parts in the frontend. Please tell me about this note if makes any sense.
I am trying to generate pdf and display inside any Div, I am getting binary data from server but when I try to convert that stream it says failed to load pdf.
I googled it and saw response of many people saying use responseType: 'arraybuffer' but I am getting object from server and extracting binary from it so I can't use it, though I tried with this approach as well but it didn't work.
Here is my controller code:
correspondenceService.getCorrespondenceDocument(id).$promise.then(function (data) {
var file = new Blob([(data[0].documentBytes)], { type: 'application/pdf' });
var fileURL = window.URL.createObjectURL(file);
vm.content = $sce.trustAsResourceUrl(fileURL);
window.open(fileURL);
}, function (reason) { });
}
This is Service:
getCorrespondenceDocument: function (correspondenceId) {
return $resource(correspondenceUrl + "getCorrespondenceDocuments").query({ correspondenceId: correspondenceId });
}
and this is my webApi:
[Route("getCorrespondenceDocuments")]
[HttpGet]
public async Task<IEnumerable<Document>> GetCorrespondenceDocumentsAsync(int correspondenceId)
{
var documents = await _correspondenceFacade.GetCorrespondenceDocumentDetailsAsync(correspondenceId);
return Mapper.Map<IEnumerable<Document>>(documents);
}
Trying to display like this on View:
Please let me know where I am doing mistake. Many thanks in advance.
Regards,
Vivek
Finally I managed to do it. Problem is I was passing 3 parameters in $http.get(), now I am passing 2 parameters only.
getCorrespondenceDocuments: function (correspondenceId) {
return $http.get(correspondenceUrl + 'getCorrespondenceDocuments' + '?correspondenceId=' + correspondenceId, { responseType: 'arraybuffer' }).then(function (response) {
return response;
});
}
Though I don't like to pass any parameter using this "?" and specifying id but I couldn't find any solution to this problem.
Many thanks guys for going through my post.
Regards,
Vivek
I'm a newbee to JS , JSON and AJAX. I'm using it to develop a simple apps in my SAP env. I'm bit struck in converting the AJAX response to java array. What is have in the code is:
function addTable()
{
var urls = new Array();
$(document).ready(function ()
{
var params = getURLParam().split('?');
$.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]})
.done(function (data)
{
var url = $.parseJSON(data);
urls.push(JSON.parse(url));
$.each(url, function (i, v)
{
push.urls[i] = v.bay;
});
});
});
alert(urls[2]);
}
but if I loop through "URLS" I do not see any value appended to the array. Please can anyone provide some help to get this fixed?
Try this. My changes are:
Use the "json" dataType argument to $.post so it parses the response automatically.
There's no need to use $(document).ready() inside a function that you call on demand. This is only needed when performing initial actions that have to wait for the DOM to be loaded.
It's not necessary to call JSON.parse(url), as this is already parsed.
The correct way to add to the urls array is urls.push(v.bay).
The preferred way to initialize an array is with [], not new Array().
alert(urls[2]) needs to be in the .done() function. Otherwise you're alerting before the AJAX call has completed.
function addTable() {
var urls = [];
var params = getURLParam().split('?');
$.post("GetBayDetails.htm", {url: getURLParam(), params: params[1]}, "json")
.done(function (url) {
$.each(url, function (i, v) {
urls.push(v.bay);
});
alert(urls[2]);
});
}
DEMO
Should be a fairly easy one here for anyone who knows Angular. I am trying to update the data that is displayed after I make a PUT request to update the object. Here is some code:
Post service (services/post.js)
'use strict';
angular.module('hackaboxApp')
.factory('Post', function($resource) {
return $resource('/api/posts/:id', {id : '#id'}, {
'update': { method: 'PUT' }
})
});
Server side controller function that gets executed when trying to update data (lib/controllers/api.js)
exports.editsave = function(req, res, next) {
var posty = req.body;
console.log(posty._id.toString() + " this is posty");
function callback (err, numAffected) {
console.log(err + " " + numAffected);
if(!err) {
res.send(200);
//res.redirect('/forum');
}
}
Post.update(posty, { id: posty._id.toString() }, callback);
};
This is the console output for the above code:
53c54a0d4960ddc11495d7d7 this is posty
null 0
So as you can see, it isn't affecting any of the MongoDB documents, but it also isn't producing errors.
This is what happens on the client (Angular) side when a post is updated:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
// Now call update passing in the ID first then the object you are updating
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
After the redirect, $location.path('/forum'), none of the data is displayed as being updated...when I look in the database...nothing has changed either...it is like I am missing the step to save the changes...but I thought that update (a PUT request) would do that for me.
I use ng-init="loadposts()" when the /forum route is loaded:
$scope.loadposts = function() {
$http.get('/api/posts').success(function (data) {$scope.posts = data});
};
Shouldn't all the new data be loaded after this? Any help would be appreciated. Thanks!
Your server side output indicate that the update query doesn't match any document in the database.
I'm guessing that you are using Mongoose in NodeJS server side code to connect to mongodb.
If that the case, your update statement seems incorrect.
Instead of { id: .. } it should be { _id: .. }
Also the conditions object and updated object are swapped.
The statement should be like this:
Post.update({ _id: posty._id.toString() }, posty, callback);
If you are not using Mongoose, please eloborate more on which library you are using or better than that, show the code where the Post variable is defined in your server side code.
Ok I got it.
the problem is that you are not using the Angular resource api correct.
This code need to be changed:
$scope.saveedit = function() {
console.log($scope.post._id + " post id");
Post.update({ id:$scope.post._id }, $scope.post, function() {$location.path('/forum')});
};
Into:
// Update existing Post
$scope.saveedit = function() {
var editedpost = new Post($scope.post); //New post object
editedpost.$update(function() {
$location.path('/forum');
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
And as for the server code (taken from my own working module):
exports.update = function (req, res) {
var post == req.post;
post = _.extend(post, req.body);
post.save(function (err) {
if (err) {
return res.send(400, {
message: getErrorMessage(err)
});
} else {
res.jsonp(post);
}
});
};