ExtJs Add Json Data - extjs

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.

Related

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);

How do I upload Audio+video as one to server?

How to upload RecordRTC based audio+video recordings to server in a single file format?
RecordRTC seems generating two separate files: one for audio (as WAV) and another one for video (as WebM). How to upload both files simultaneously on a PHP server?
Since Chrome >=49, RecordRTC is now using MediaRecorder API to support microphone+webcam recordings into single WebM file format.
Here is how to record both audio+video into single WebM (this works both on Chrome >= 49 and Firefox >= 38)
<script src="https://cdn.WebRTC-Experiment.com/gumadapter.js"></scrip>
<script>
var recorder;
function successCallback(audioVideoStream) {
recorder = RecordRTC(audioVideoStream, {
type: 'video',
mimeType: 'video/webm',
bitsPerSecond: 512 * 8 * 1024
});
recorder.startRecording();
}
function errorCallback(error) {
// maybe another application is using the device
}
var mediaConstraints = {
video: true,
audio: true
};
navigator.mediaDevices.getUserMedia(mediaConstraints).then(successCallback).catch(errorCallback);
document.querySelector('#btn-stop-recording').onclick = function() {
if (!recorder) return;
recorder.stopRecording(function() {
var audioVideoBlob = recorder.blob;
// you can upload Blob to PHP/ASPNET server
uploadBlob(audioVideoBlob);
// you can even upload DataURL
recorder.getDataURL(function(dataURL) {
$.ajax({
type: 'POST',
url: '/save.php',
data: {
dataURL: dataURL
},
contentType: 'application/json; charset=utf-8',
success: function(msg) {
alert('Successfully uploaded.');
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error:' + JSON.stringify(errorMessage));
}
});
});
});
};
function uploadBlob(blob) {
var formData = new FormData();
formData.append('file', blob);
$.ajax({
url: "/save.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Successfully uploaded.');
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error:' + JSON.stringify(errorMessage));
}
});
}
</script>
Here is an example save.php file that reads for video-filename and video-blob:
<?php
foreach(array('video', 'audio') as $type) {
if (isset($_FILES["${type}-blob"])) {
echo 'uploads/';
$fileName = $_POST["${type}-filename"];
$uploadDirectory = 'uploads/'.$fileName;
if (!move_uploaded_file($_FILES["${type}-blob"]["tmp_name"], $uploadDirectory)) {
echo(" problem moving uploaded file");
}
echo($fileName);
}
}
?>
Above save.php requires following FormData:
function uploadBlob(blob) {
var formData = new FormData();
formData.append('video-blob', blob);
formData.append('video-filename', 'FileName.webm');
$.ajax({
url: "/save.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response) {
alert('Successfully uploaded.');
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error:' + JSON.stringify(errorMessage));
}
});
}

Angular resource custom post method

I need to post data to a SharePoint list, and I want to clean up my code by using
a resource factory, until now I have posted data like this:
this.save = function(data) {
data["__metadata"] = { "type": getItemTypeForListName('ListName') };
var restQueryUrl = appweburl + "/_api/lists/getByTitle('ListName')/items";
$.ajax({
url: restQueryUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
};
And so far my resource factory looks like this:
myApp.factory('Entry', function($resource) {
return $resource(appweburl + "/_api/lists/getByTitle('ListName')/items", {}, {
get: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description&$filter=ID eq :ID"
},
query: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description"
}
})
});
How can I 'convert' my save function to a resource method?
Okey, so I was easier than I thought, what I had to do was run the function 'getItemTypeForListName' before calling the save function, this adds the metadata needed to save to sharepoint. And in my resource factory add this:
save: {
method: 'POST',
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
}
And then in my controller call it like this:
$scope.test = new Entry();
$scope.test.Title = 'testTitle';
// function to set metadata
$scope.test["__metadata"] = { "type": getItemTypeForListName('ListName') };
Entry.save($scope.test);

Update db with ajax and CakePHP

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']);
}

jsonp return number

Hi in my succes function im trying to return 6 numbers from my callback jsonp function and pass to a var, something like; im out of ideas thnx P
for (var bw=0; bw < bw_numbers.length; x++) {
$('#_pnl' + bw).innerHTML = bw_numbers[bw];
}
jsonCallback(
   {
"bw_numbers": [10, 12, 15, 24, 27, 41]
}
);
var url = 'http://www.blabla.com/ajax/bw_results_latest.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
//do my array thing!!!!
},
error: function(e) {
alert(e.message);
}
});
you need to write the jsonCallBack function
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
error: function(e) {
alert(e.message);
}
});
function jsonCallBack(data)
{ alert(data); }
If you return like
jsonCallback([10, 12, 15, 24, 27, 41])
you can access it as array from javascript
I got it now, I wasnt sure if the json data was able to be used as an array, it is and here is code! Thanks P
var url = 'http://www.blabla.com/ajax/results_latest.json?callback=?';
$.ajax({
type: 'GET',
url: url,
processData: true,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
processData(data);
}
});
function processData(data){
for (var x=0; x < data.bw_numbers.length; x++) {
document.getElementById('_pnl' + x).innerHTML = data.bw_numbers[x];
}
}

Resources