I'm trying to ajax update a record in the DB. Here's my code. I test out by writing $this->request->data to a log, but it's just blank. Any ideas on what I'm doing wrong?
$.ajax({
type: "POST",
url: "http://localhost:8888/cake/tasks/updateStatus",
data: {id: $(this).attr("id"), status: "checked"},
contentType: "application/json",
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
/* controller */
public function updateStatus() {
$data = json_decode($this->request->data);
$this->Task->id = $data['id'];
$this->Task->saveField("status",$data['status']);
}
Related
I need to load data from Veeml into our SAP database.
We already scheduled some loading processes and I wonder if there is a way to query Veeml to transfer data in SAP.
You can use the API /getgrid2 to retrieve data from VEEML in a JSON format.
type: "POST",
url: « //the-url.ofyour.portal/getgrid2",
data: { "jsonstring": JSON.stringify(_jsonstring) },
success: function (data) {
console.log(data);
}
With _jsonstring as :
{
"Token": , -> authentication token
"DataView":"", -> name of the datatable
"Universe":{"column1":"''value1'"},
-> List of restriction if need (current universe)
"Chart":{
"Type":"grid",
"treillis":"",
"Dimension1":["column1 as column1"],
-> List of dimensions
"Dimension2":[],
"Fact":["AVG(Value) as Value"],
-> List of metrics
"LineorColumn":"Lines"
}
Use this endpoint to export data from VEEML.
You will get JSON that you can use in your application.
type: "POST",
data: { "jsontring": jsonstring, "DashboardId": _DashboardId},
url: "//the-url.ofyour.portal/getgrid2",
contentType: "application/json",
success: function (data) {
window.open('//xxx.datatelling.eu/nextractorcsvlink/' + data.uid, '_blank' );
}
Below is a full instance with the authentication to get the turnover by week for the year 2021 :
var _email = 'john.doe#yourcompany.com';
var _password = 'bigfan';
var _hash = CryptoJS.SHA256(_password);
var _data = {"email": _email, "password": _hash.toString()};
var _url = "https://the-url.ofyour.portal/login";
$.ajax({
type: "POST",
url: _url,
dataType : 'jsonp',
data: _data,
error: function(xhr, response, error)
{
console.log(error);
},
success: function(json)
{
console.log(json.success);
_url = "http://the-url.ofyour.portal/getgrid2";
// _jsontring is the request to pass to the API
_jsontring = {"Token": json.success,"DataView":"yourentrypointdb.dbo.
[your_dataview]","Universe":
{"Year":"'2021'"},"Chart":{"Type":"grid","treillis":"","Dimension1":["Week as Week"],
"Dimension2":[],"Fact":["SUM(Amount) as Turnover"],
"LineorColumn":"Lines"}};
_data = {"jsontring": JSON.stringify(_jsontring)};
$.ajax({
type: "POST",
url: _url,
dataType : 'jsonp',
data: _data,
error: function(xhr, response, error)
{
console.log('error');
console.log(error);
},
success: function(json)
{
console.log(json);
$("#result").html(json);
}
});
}
});
Using the code below, I am able to add items in my database, but the table showing the current entries doesn't update (I thought Angular did that automatically?) --- How do I force a refresh of the data?
.controller("addItemsController", function ($scope, $http) {
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyContacts')/items";
var vm = $scope;
var requestDigest = $("#__REQUESTDIGEST").val()
vm.addContact = function () {
return $http({
headers: { "accept": "application/json; odata=verbose", "X-RequestDigest": requestDigest, "content-Type": "application/json;odata=verbose" },
method: "POST",
url: url,
data: {
'Title': vm.LastName,
'FirstName': vm.FirstName,
"__metadata": { "type": "SP.Data.MyContactsListItem" }
}
})
.then(saveContact)
.catch(function (message) {
console.log("addContact() error: " + message);
});
function saveContact(data, status, headers, config) {
alert("Item Added Successfully");
return data.data.d;
}
}
})
NOTE: I tried using $scope.contacts.push(data) as suggested elsewhere in the forum, but contacts came back undefined (?!)
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);
I am trying to make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api
I am facing problem in ExtJs. OnClick function it should load data for one time. But it is replicating the same data on every click.
Here is my code:
function onselectionchange()
{
jQuery.ajax({
type: "POST",
url: "/Maintainer/getfolders",
data: null,
contentType: "application/json; charset=utf-8",
async: true,
success: function (result) {
var store = Ext.getCmp('gridpanel').getStore();
store.loadData(result, true);
},
error: function (p_Result) {
var error = "Error on controller: \"" + p_Controller + "\" in function: \"" + p_ControllerFunction + "\" statusText: \"" + p_Result.statusText;
alert(error);
},
traditional: true
});
}
function onselectionchange()
{
if(clickonce == "")
{
ajax({
type: "POST",
url: "/url",
data: null,
contentType: "application/json; charset=utf-8",
async: true,
success: function (result) {
enter code here
clickonce = 1;
}
});
}
else
{
alert("already selected once");
}
}
What i'am doing here is creating a global variable with clickonce. When you first click on the button the json will get uploaded and the flag on this variable will set to 1 hence it won't be populated again.