$http GET URL changes and looks for wrong resource - javascript

I'm developing a single page application. I am making use of Angularjs.v1.2.28. I'm making a HTTP GET request to the backend using this code.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http.get(req);
},
I make use of the promise object that is returned from service in controller.
var categoryPromise = categoryService.getCategories(sessionid,terminalid,tableno,section);
categoryPromise.then(function(payload){
var categories = payload.data;
if(categories.status.code == "1"){
if(Object.prototype.toString.call(categories) === '[object Array]') {
$scope.categories = categories;
categoryService.setCategories(categories);
$scope.pax = tableService.getPax();
$scope.tablechair = tableService.getChoseTableChair();
}
}
else{
$location.url("/login");
$scope.errorMsg = categories.status.desc;
}
},function(errorPayload){
$location.url("/login");
$scope.errorMsg = "Server error while processing the request.Please contact system administrator";
});
It's always the errorCallback is getting called due to the URL getting changed to the browser application URL appended with some malformed characters. The URL which i give is
http://localhost:8080/CafexRestful/menucategories
But, it gets changed to the browser application URL below
http://localhost:8080/CafexMobile/[object%20Object]
I have been debugging in Chrome and Firebug. I couldn't resolve it. It may be something which is happening under the hood. The same code is working with another controller and service, where i fetch a different data. Please let me know if you need anymore information. Thanks.

$http.get in angularjs needs an url string. You should use url string instead of an object
Using $http.get function:
return {
getCategories : function(){
return $http.get("/menucategories"); // using $http.get function.
},
Using $http function.
return {
getCategories : function(sessionid,terminalid,tableno,section){
var req = {
method: 'GET',
url: Config.url+ "/menucategories",
params : {
'sessionid' : sessionid,
'terminalid' : terminalid,
'tableno' : tableno,
'section' : section
}
};
return $http(req); //using $http function only.
},
Please see the document: https://docs.angularjs.org/api/ng/service/$http

Related

CakePHP 4.x Ajax request with CSV-file

I am developing a responsive user interface in CakePHP 4.x which occasionally uses Ajax requests.
My Ajax requests are performing just fine but I am having a lot of trouble incorporating a CSV-file in the request so my controller can handle the data. What I want to accomplish is that that I can choose a CSV-file, press submit and that the Ajax-request sends the file to the controller and uses the independent rows to update the database.
My code:
Javscript:
function importProducts() {
/* Getting form data */
let form = document.getElementById('importProductsForm');
let formData = new FormData();
let file = $(form.products_file).prop('files')[0];
formData.append("csv_file", file);
/* Moving product stock */
ajaxRequest('Products', 'importProducts', formData, processImportProducts);
}
function ajaxRequest(controller, action, data = null, callback = null) {
$.ajax({
url : "<?=$this->Url->build(['controller' => '']);?>" + "/" + controller + "/" + action,
type : 'POST',
data : {
'data': data
},
dataType :'json',
/*processData: false,*/
/*contentType: false,*/
success : function(dataArray) {
let response = dataArray.response;
if (typeof response.data !== 'undefined') {
data = response.data;
if (callback != null) {
callback(data);
}
} else if (response.success == 0) {
data = null;
giveError(response.errorTemplate);
} else {
data = null;
if (callback != null) {
callback(data);
}
}
},
error : function(request,error)
{
console.error(error);
}
});
}
At the moment the controller function does not do anything special but receiving and setting the data:
public function importProducts() {
$this->RequestHandler->renderAs($this, 'json');
$response = [];
if($this->request->is('post')) {
$data = $this->request->getData();
$response['test'] = $data;
} else {
$response['success'] = 0;
}
$this->set(compact('response'));
$this->viewBuilder()->setOption('serialize', true);
$this->RequestHandler->renderAs($this, 'json');
}
After some research I discovered I could use the FormData object to send the file. The error I then received was 'illegal invocation'. After some more research I discovered this had to with automatic string parsing by Ajax. According to some other StackOverflow posts I could resolve this by setting the processdata and contenttype properties to false. This fixed the problem but resulted in an Ajax request which always would be empty (that does not contain any data). I tested this without the CSV-file with a regular data object that contains a variable with a string but also resulted in a empty request (no data send to controller).
So my problem is that without the processdata property as false I get the 'illegal invocation' error, otherwise with processdata as false I literary do not receive any data in my controller. I am looking for solution to resolve this problem so I can send my CSV-file or at least the data within the file to my controller.
Other solutions than using the FormData are also welcome, for example I tried to read the CSV-file in Javascript and turn this into another object (with the jquery csv api) to send to the controller, sadly without success until now.

Can't connect to web service by JQuery

I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .
I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?

Difference in $http response and Api response [AngularJs]

I have an issue on my application when I get an API request from members belongs to a particulary group.
GET /api/organizations/1234/members?group=4321
If I start my navigation with this request, I have the right members but if I navigate in other page with other groupe before, the $http response is full of parasite members whereas the response form API is right (check from network tab in Chrome developper tools).
I think about some cache but I can not find it ! For info, I use jsData for mounting my data but it's not seems to be the problem.
Here the code of my function to send Api Request :
var loadGroupMembers = function() {
return $q(function(resolve, reject) {
var callParams = {
organizationId: $stateParams.OrganizationId,
groupId: $stateParams.groupId
};
sendApiCall('groupMembers', 'get', callParams)
.success(function(data) {
resolve(data);
})
.error(function(data) {
});
});
};
var sendApiCall = function(requestId, method, params, data, queryStringParams) {
params = params || {};
data = data || {};
var apiCallConfig = {
params: config.params,
method: config.method,
url: "/api/organizations/1234/members?group=4321",
data: data,
cache : false
};
$rootScope.fn.setHistory($state.current.name, 'apiCall', 'sendManualApiCall:' + requestId);
return $http(apiCallConfig);
};
Please tell me if you have questions or need more details.
Thanks for your help ! :)
Edit : I add the function that call sendApiCall and I made a little apiary to show you how the data from api are : http://private-52326-groupmember.apiary-mock.com/organization/1234/members?group=4321
It was kind of link with Jsdata and an interceptor created by an other developer. For each api request, the interceptor add some data on the response with the same type ... So the issue is closed.
Thanks for your help anyway :)

Getting factory service data to controller for use in view with promises

I am trying to use the Forecast.io weather API to build a weather application with Ionic. I am having a hell of a time getting the AJAX response data delivered to my controller for use in my view.
My Factory Service:
.factory('WeatherService', function($cordovaGeolocation) {
var posOptions = { timeout: 10000, enableHighAccuracy: false };
return {
// Get current Geolocation position with the configured /posOptions/
getPosition : $cordovaGeolocation.getCurrentPosition(posOptions),
// Query the result of /getPosition/ for /lat/, /long/, and /accuracy/
getCoords : function(pos) {
var loc = {
lat : pos.coords.latitude,
long : pos.coords.longitude,
accuracy : pos.coords.accuracy
};
return loc;
},
// Build the API request URI
getApi : function(lat, long) {
var url = 'https://api.forecast.io/forecast/';
var apiKey = 'foo';
var forecastApi = url + apiKey + '/' + lat + ',' + long + '?callback=?';
return forecastApi;
},
// Execute a request against the API URI to recieve forecast data
getForecast : function(api) {
var forecast;
$.ajax({
url : api,
dataType : 'json',
async : false,
success : function(res) {
forecast = res;
}
});
return forecast;
}
};
})
My Controller Method:
.controller('DashCtrl', function($scope, WeatherService) {
WeatherService.getPosition.then(function(pos) {
var pos = pos;
return pos;
}).then(function(pos) {
var coords = WeatherService.getCoords(pos);
return coords;
}).then(function(coords) {
var api = WeatherService.getApi(coords.lat, coords.long);
return api;
}).then(function(api) {
$scope.forecast = WeatherService.getForecast(api);
console.log($scope.forecast);
});
})
There's probably a lot of things inherently wrong with the above code. From my reading I have been made aware that then() methods really shouldn't be used in the controller method, and all of that logic should be isolated to the Service Method. I will be refactoring to that pattern when I get this working.
I am using the jQuery $.ajax() instead of $http because of CORS issues with Forecast.io when developing locally. $jsonp was throwing syntax errors on the response, so I had to resort to jQuery for the call to get this working locally.
I know I am getting a successful response because if I console.log(forecast) inside the $.ajax call I can explore the weather data. For whatever reason, I am unable to save the response value to the forecast var saved in the parent scope of the ajax call and then return that to the controller for use in my view with the $scope.forecast variable. It is always returning undefined.
I have looked at plenty of SO questions while trying to get this working on my own, and have yet to have any success..
How do I return the response from an asynchronous call?
Get Data from a callback and save it to a variable in AngularJS
Well, if you really really feel the need to use ajax (probably better to track down and fix the jsonp issue) then you should probably wrap the forcast in your very own promise.
.factory('WeatherService', function($q,$cordovaGeolocation) {
...
getForecast : function(api)
{
var deferred = $q.defer();
$.ajax({url : api, dataType : 'json', async : false,
success : function(res) {
defereed.resolve(res);
}
});
return defereed.promise;
}
You already know how to handle promises in your controller code so I won't post those changes.

Fetch data on different server with backbone.js

I can't see what the problem with this is.
I'm trying to fetch data on a different server, the url within the collection is correct but returns a 404 error. When trying to fetch the data the error function is triggered and no data is returned. The php script that returns the data works and gives me the output as expected. Can anyone see what's wrong with my code?
Thanks in advance :)
// function within view to fetch data
fetchData: function()
{
console.log('fetchData')
// Assign scope.
var $this = this;
// Set the colletion.
this.collection = new BookmarkCollection();
console.log(this.collection)
// Call server to get data.
this.collection.fetch(
{
cache: false,
success: function(collection, response)
{
console.log(collection)
// If there are no errors.
if (!collection.errors)
{
// Set JSON of collection to global variable.
app.userBookmarks = collection.toJSON();
// $this.loaded=true;
// Call function to render view.
$this.render();
}
// END if.
},
error: function(collection, response)
{
console.log('fetchData error')
console.log(collection)
console.log(response)
}
});
},
// end of function
Model and collection:
BookmarkModel = Backbone.Model.extend(
{
idAttribute: 'lineNavRef'
});
BookmarkCollection = Backbone.Collection.extend(
{
model: BookmarkModel,
//urlRoot: 'data/getBookmarks.php',
urlRoot: 'http://' + app.Domain + ':' + app.serverPort + '/data/getBookmarks.php?fromCrm=true',
url: function()
{
console.log(this.urlRoot)
return this.urlRoot;
},
parse: function (data, xhr)
{
console.log(data)
// Default error status.
this.errors = false;
if (data.responseCode < 1 || data.errorCode < 1)
{
this.errors = true;
}
return data;
}
});
You can make the requests using JSONP (read about here: http://en.wikipedia.org/wiki/JSONP).
To achive it using Backbone, simply do this:
var collection = new MyCollection();
collection.fetch({ dataType: 'jsonp' });
You backend must ready to do this. The server will receive a callback name generated by jQuery, passed on the query string. So the server must respond:
name_of_callback_fuction_generated({ YOUR DATA HERE });
Hope I've helped.
This is a cross domain request - no can do. Will need to use a local script and use curl to access the one on the other domain.

Categories