ExtJS Ajax Request Method GET - extjs

I need to send a request via GET but ExtJS changes the method for OPTIONS
I changed useDefaultXhrHeader even though I could not send, I also need to disable CORS
https://fiddle.sencha.com/#view/editor
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.Ajax.request({
url: 'http://localhost:8888/api/sign/certificates',
method: "GET",
useDefaultXhrHeader : false,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
success: function (response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function (response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}
});
PRINT

I think you want to eliminate the _dc cache parameter, you can do it like this
noCache: false,
Use this in your Ext.Ajax.request({})
Hope this helps!!

Related

Angular: then execute before http call complete

When I call addCategory, it suppose to add my new category and then call _initAdminController() to go back to my main page and refresh the data there. But what is happening is getcourselist and getsubjectlist in initAdminController are somehow running first and then addCategory runs last. Do you know what can cause this? Am I using then correctly?
function _initAdminController() {
$scope.pageIndex = "adminTab";
console.log("reloading data");
$http({
method : 'GET',
url : 'http://testserver.com:8082/getSubjectListService'
}).then(function successCallback(response) {
$scope.updatedSubjects = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
$http({
method : 'GET',
url : 'http://testserver.hughes.com:8082/getCategoryListService'
}).then(function successCallback(response) {
$scope.categories = response.data;
}, function errorCallback(response) {
console.log(response.statusText);
});
}
$scope.addCategory= function(){
var name = $scope.addCategoryData.name;
var desc = $scope.addCategoryData.description;
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : { 'Content-Type': 'application/json' },
data : {
name: name,
description: desc
}
}).then(_initAdminController(), function errorCallback(response) {
console.log(response.statusText);
});
}
Also when I use then for http get, that case is working correctly. The http get finishes first and then my scope variable get updated.
And lastly before I tried the following code and in that case, successCallback doesn't run at all. So does this mean then only works for GET?
$http({
method : 'POST',
url : 'http://testserver.com:8082/addCategoryService',
withCredentials: true,
cache: true,
headers : {
'Content-Type': 'application/json'
},
data : {
name: name,
description: desc
}
}).then(
function successCallback(response) {
_initAdminController()
},
function errorCallback(response) {
console.log(response.statusText);
}
);
The code:
}).then(_initAdminController(), ...);
Should be:
}).then(_initAdminController, ...);

Accessing API with $http POST Content-Type application/x-www-form-urlencoded

I am trying to access this REST API, which accepts three parameters:
stationId, crusherId, monthYear
I am doing it like this in AngularJS as:
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
//headers: {'Content-Type': 'application/json; charset=UTF-8'},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
url: 'https://myurl../api/getHPData',
method: 'POST',
data: {
stationId: 263,
crusherId: 27,
monthYear: '2016-4'
}
})
.then(function(data, status, headers, config) {
//console.log(JSON.stringify(response));
console.log(data);
})
.catch(function(error){
//console.log("Error: " + JSON.stringify(error));
console.log(error);
})
But I am always getting this:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
OR
{"data":"{\"result\":\"false\"}","status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/x-www-form-urlencoded;
charset=UTF-8","Accept":"application/json"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":"OK"}
If I change header Content-Type to:
headers: {'Content-Type': 'application/json; charset=UTF-8'},
It gives:
Object {data: null, status: -1, config: Object, statusText: "",headers: function}
OR
{"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"headers":{"Content-Type":"application/json;
charset=UTF-8","Accept":"application/json, text/plain,
/"},"url":"https://myurl../api/getHPData","data":{"stationId":263,"crusherId":27,"monthYear":"2016-4"}},"statusText":""}
What I am doing wrong, Please help me.
Plunker is here:
https://plnkr.co/edit/57SiCdBZB2OkhdR03VOs?p=preview
(Edit)
Note:
I can do it in jQuery as:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl../api/getHPData";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST
"https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is perfect. :)
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
The DEMO on PLNKR
The documentation says that the stationId and crusherId parameters should be arrays of strings. Also, it looks like you are sending JSON data, so make sure to set that header correctly.
$http({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
url: 'https://fnrc.gov.ae/roayaservices/api/getHPData',
method: 'POST',
data: {
stationId: ['263'],
crusherId: ['27'],
monthYear: '2016-4'
}
})
When I change the code in your plunkr to use the corrected code above, I get the following response: "The requested resource does not support http method 'OPTIONS'."
As the other (now deleted) answer correctly mentioned, this means that there is a CORS issue. The browser is trying to send a "preflight" request before making the cross-origin request, and the server doesn't know what to do with it. You can also see this message in the Chrome console:
XMLHttpRequest cannot load
https://fnrc.gov.ae/roayaservices/api/getHPData. Response for
preflight has invalid HTTP status code 405

Accessing API with $http POST Content-Type application/x-www-form-urlencoded always gets 'false' results

I have the following REST Service which I have to access on POST Method,
I can access it via jQuery but I don't know how to do it with AngularJS (v1)
<string xmlns = "http://schemas.microsoft.com/2003/10/Serialization/">
<script id = "tinyhippos-injected" />
{
"volumeResult": {
"gyydt": "9771241.17704773",
"gytotal": "29864436.1770477",
"gybudgeted": "29864436.1770477",
"lyydt": "10197350",
"lytotal": "27859381",
"lybudgeted": "10197350",
"cyytd": "6992208",
"lastUpdate": "March-2017"
},
"valueResult": {
"gyydt": "26862094",
"gytotal": "68217952",
"gybudgeted": "68232952",
"lyydt": "0",
"lytotal": "0",
"lybudgeted": "0",
"cyytd": "68217952",
"lastUpdate": "March-2017"
},
"trucksResult": {
"gyydt": "165951",
"gytotal": "497879",
"gybudgeted": "497879",
"lyydt": "168822",
"lytotal": "468814",
"lybudgeted": "168822",
"cyytd": "119442",
"lastUpdate": "March-2017"
}
}
</string>
Here is my controller.js:
angular.module('starter.controllers', [])
.controller('DashCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
//headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
headers: {'Content-Type' : 'application/json'},
url: 'https://myurl../api/getHPData',
method: 'POST',
// data: data,
params: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function (response) {
console.log(response);
})
// I don't have to use .success and .error function as they are [depricated][2]
//.success(function (data, status, headers, config) {
// $scope.greeting = data;
// var Result = JSON.stringify(data);
// var Result = JSON.parse(data);
//})
//.error(function (error, status, headers, config) {
// console.log("====================== Error Status is: " + error);
// console.log("====================== Status is: " + status);
// console.log("====================== Error occured");
//})
}]) // eof controller DashCtrl
.controller('MapsCtrl', function($scope) {})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
What I want is value of:
"volumeResult" > "gytotal"
Problems:
It always return:
Object {data: "{"result":"false"}", status: 200, config: Object, statusText: "OK", headers: function}
and
When I pass monthYear without quotes it process (arithmetic) it as (2016-04 = 2012)
As the service is POST but when I analyze it in Chrome Developers Tool so I get: (Query String, which isn't meant to be POST)
ionic.bundle.js:25005
XHR finished loading: POST
"https://myurl../api/getHPData?crusherId=27&monthYear=2016-4&stationId=263"
Possible solutions:
Either I am using wrong header:
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Accept': 'application/json'
},
Or header may be,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
Or as per my friend says:
When I change your code to use the code above, I get this error:
"{"Message":"The requested resource does not support http method
'OPTIONS'."}" Which means that there is a CORS (Cross-origin Resource Sharing) issue. Chrome is trying to make a "preflight" request to allow
CORS, but the server doesn't know what to do with it.
But I don't think it is because of this as I am receiving:
Object {data: "{"result":"false"}", status: 200, config: Object,
statusText: "OK", headers: function}
from server. Noted that: {"result":"false"} is the message displayed by the server when it didn't find data or you pass wrong parametes. Also bellow jQuery code is proof that I can access the server. :)
Edit
jQuery Snippet:
<script>
$(document).ready(function() {
get_homepage_data(263, 27, '2016-04');
function get_homepage_data(stationIds, crusherIds, date) {
var url = "https://myurl..";
var data_to_send = {
'stationId': stationIds,
'crusherId': crusherIds,
'monthYear': date
};
console.log("Value is: " + JSON.stringify(data_to_send));
//change sender name with account holder name
// console.log(data_to_send)
$.ajax({
url: url,
method: 'post',
dataType: 'json',
//contentType: 'application/json',
data: data_to_send,
processData: true,
// crossDomain: true,
beforeSend: function () {
}
, complete: function () {}
, success: function (result1) {
// I know I can do it in one line but lazy enough to edit it here :p
var Result = JSON.parse(result1);
var value_data = Result["valueResult"];
var foo = value_data["gyydt"];
console.log("Log of foo is: " + foo);
var foo2 = 0;
// 10 lac is one million.
foo2 = foo / 1000000 + ' million';
console.log(JSON.stringify(value_data["gyydt"]) + " in million is: " + foo2);
}
, error: function (request, error) {
return false;
}
});
}
}); // eof Document. Ready
</script>
Output of above script is script is:
Value is: {"stationId":263,"crusherId":27,"monthYear":"2016-04"}
XHR finished loading: POST "https://myurl../api/getHPData".
Log of foo is: 26862094
"26862094" in million is: 26.862094 million
Which is indeed perfect. :)
try to use $http this way ..
$http.post("https://myurl../..",JSON.stringify({
stationId: 263,
crusherId: 27,
monthYear:'2016-04'
})).then(function(res){
console.log(res);
}).catch(function(errors){
console.log(errors);
})
I got answer. Whao.
Thank you georgeawg for his answer:
He says:
When posting form data that is URL encoded, transform the request with the $httpParamSerializer service:
$http({
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
url: 'https://myurl..',
method: 'POST',
transformRequest: $httpParamSerializer,
transformResponse: function (x) {
return angular.fromJson(angular.fromJson(x));
},
data: {
"stationId": 263,
"crusherId": 27,
"monthYear": '2016-04'
}
})
.then(function(response) {
console.log(response);
$scope.res = response.data;
console.log($scope.res);
});
Normally the $http service automatically parses the results from a JSON encoded object but this API is returning a string that has been doubly serialized from an object. The transformResponse function fixes that problem.
Now I am able to get value of gytotal as:
var myData = parseFloat(response.data.valueResult.gytotal);
console.log(myData);

Extjs Store Getting Data from Post

Good Morning,
I have a search endpoint that I that works when I call it like this:
Ext.Ajax.request({
url: '/Search/False',
method: 'POST',
headers: { 'Content-Type': 'application/json' },
params: 'Attribute:ClosedDT;Value:2014-12-16',
success: function(conn, response, options, eOpts) {
alert(conn.responseText);
},
failure: function(conn, response, options, eOpts) {
alert(conn.responseText);
}
});
I want to use a proxy to load it into a store directly. After much googling I have tried this and i get back a POST /Search/False?_dc=1418738135737 net::ERR_EMPTY_RESPONSE
See current code below:
var proxyDefinition = {
type : 'rest',
api : {
read : '/Search/False'
},
actionMethods : {
read : 'POST'
},
reader : {
type : 'json'
},
paramsAsJson:true
};
returnValue = Ext.create('Ext.data.Store', {
model: 'Mdl1',
proxy: proxyDefinition
});
returnValue.load({params: 'Attribute:ClosedDT;Value:2014-12-16'});
The params config needs to be an object, not a string. Extjs will encode it for you because of paramsAsJson: true.
You should use:
params: {
Attribute: 'CloseDT',
Value: '204-12-16'
}

Using $resource with Angular

I have a service that I am calling to get a collection which works fine. Here is the service:
angular.module('clinicalApp').factory('encounterService', function ($resource, $rootScope) {
var EncounterService = $resource('http://localhost:port/v2/encounters/:encounterId', {encounterId:'#id', port: ':8280'}, {
search: {
method: 'GET',
headers: {
'User': 'testuser',
'Content-Type': 'application/json'
}
},
save: {
headers: {
'User': 'testuser',
'Content-Type': 'application/json'
}
}
});
return EncounterService;
});
As I said, I am able to get the collection, but when I try to update a one of the elements in my collection, it is calling out to the wrong url. Here is how I am trying save my resource:
encounterService.save({
id: scope.encounter.id
});
And here is the url that is being hit:
http://localhost:8280/v2/encounters?id=12345
So it is appending the url as if it is a search parameter. How do I get it to append the id to the url like
encounters/12345
as it should?
Try this...
{encounterId:'#id', port: ':8280'}
Change To:
{encounterId:'#encounterId', port: ':8280'}
AND
encounterService.save({
id: scope.encounter.id
});
Change To:
encounterService.save({
encounterId: scope.encounter.id
});

Resources