Pass a parameter from client-side to server side and get result - json

I knows it sounds basic but I can't seem to get it right. I'm trying to get a data from the API but it needs a parameter in order to obtain the data. How can I pass the parameter and get the result which is a JSON array
$(function() {
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var rt = 'GET';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var param = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, function(param) {
console.log('Success');
});
});

ways to achieve this :
using jQuery.ajax() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.ajax({
url: url,
type: method, //send it through get method
data: params,
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
using jQuery.get() method :
var proxy = 'http://192.168.1.126/lms-dev-noel/proxy.php';
var endpoint = 'account/';
var url = proxy+'?endpoint='+endpoint+'&rt='+rt;
var method = 'GET';
var params = {
'lastsyncdate' : '2016-12-06'
};
$.get(url, params, function(res) {
console.log(res);
});

I just pass parameters as name value pairs like so...
$.get(
"yoururl.php",
{ color: "red", size: "small" }, // your params go here as name / value pairs
function(response){
console.log(response);
}
);

Related

How to make a RESTFUL PUT call angulajrs

Im confused on how to make a RESTFUL API call with 'PUT'. I'm basically trying to save an edited profile but I'm confused on how to make the API call for it. This is what I have so far ...
var edit = angular.module('edit', ['ui.bootstrap','ngResource'])
.factory('editable', function($resource) {
return {
// get JSON helper function
getJSON : function(apicall) {
if(sessionStorage["EditUserId"] == undefined) {
// get the user id
var userid = sessionStorage["cerestiuserid"];
}
else {
var userid = sessionStorage["EditUserId"];
}
// json we get from server
var apicall = sessionStorage["cerestihome"];
// new api
return $resource(apicall + "/api/profiles/", {Userid:userid}, {'PUT': {method: 'Put'}});
}
};
});
This is the controller ...
//editable object
var object = editable.getJSON();
var edit = new object();
edit.UserName = "Hello World";
edit.$save();
Use restagular to invoke put service.
For example
admin.factory('AdminService', ['Restangular', 'AppConstants', 'AdminRestangular', 'WorkFlowRestangular', 'localStorageService',
function(Restangular, AppConstants, AdminRestangular, WorkFlowRestangular, localStorageService) {
var service = {}
service.updateAgency = function(data) {
return AdminRestangular.all(AppConstants.serviceUrls.agency).doPUT(data);
};
return service
}]);

How to make multipart form api requests with requestjs and nodejs?

Trying to interact with the phaxio api using multipart form data. As per the request.js docs for making a post request I do
var request = require('request');
var options = {
uri: 'https://api.phaxio.com/v1/send',
headers: {'content-length':'0'}
};
var r = request.post(options);
var form = r.form();
form.append('api_key', '1234');
form.append('api_secret', '1234');
form.append('to', '1234');
r.on('response', function(chunk){
console.log(chunk);
});
The response body I get from the r.on method is here http://pastie.org/private/wshbn9esendccrkoreeiow I'm unsure how I can see the api response body from the server after submitting the form data. Something like
{
"success": true,
"message": "Fax Sent!"
}
The method request.post() returns a readable stream. Just read the response:
var res = '';
r.on('data', function(data) {
res += data;
});
r.on('end', function() {
console.log(res);
});
You can also pipe the response to another writable stream:
var fs = require('fs');
var writable = fs.createWriteStream('/file');
r.pipe(writable);

Return json object from dojo.xhrget

I am trying to get the json object from a dojo xhrGet call.
What I want is jsonobject = stuff;
I can see the json object in the console, but cannot access it!
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
load: function(json_results){
console.log(json_results);
store = json_results;
return dojo.toJson.json_results;
},
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
console.log("Json is "+JSON.stringify(deferred));
The console.log part that shows the json_results is fine, exactly what I want.
The dojo.xhrXXX methods are asynchronous. This means that the lines following
var deferred = dojo.xhrGet(xhrargs);
Will continue to execute while the call to an external endpoint is processing. This means you need to use the promise API to tell a certain block of code to execute once the XHR request is complete:
var deferred = dojo.xhrGet(xhrargs);
deferred.then(function(result){
//this function executes when the deferred is resolved (complete)
console.log('result of xhr is ',result);
});
Due to the asynchronous nature of the request, for most intents and purposes that value doesn't exist outside the scope of the callback function. One way to structure your code around this is in multiple blocks. for example:
var xhrLoaded = function(results){
console.log('results = ',results);
store = results;
}
var performXhr = function(){
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
deferred.then(xhrLoaded);
}
performXhr();
You can still access variables outside of the scope of the function (for example if store were defined globally).
try this
var xhrArgs = {
url:"MethodName.action?Id="+id,
handleAs: "json",
load: function(Data){
var values = Data;
var count = Object.keys(values).length // gives u all keys count in a json object. In mine it is 0,1,2,3
for (var i =0; i<count; i++){
var temp = values[i]; // values['name']
// do somthing ..
}
}
},
error: function(error){
alert(error);
}
}
dojo.xhrPost(xhrArgs);

Add JSON value to ko.computed in viewmodel

I am busy creating a currency Module for my web app, I am using Yahoo Finance API to return the currency conversion rate of 2 currencies that I have defined in my local DB. I get the JSON data fine from the API, I just want to Bind the JSON data that I have received from the Finance API to my existing Viewmodel using ko.computed. I am not sure if I should be using ko.computed to achieve this, so any advice will help greatly.
Here is my code:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.computed(rates); // I WANT TO BIND THE VALUE FROM API HERE
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedCurrencies =
$.map(Result.d,
function (item) {
getRate(item.CurrencyFrom, item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result from Yahoo Finance API
function getRate(from, to) {
var script = document.createElement('script');
script.setAttribute('src', "http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=rates"); //HERE I CALL THE VALUE TO OBTAIN THE CONVERSION RATE FROM API
document.body.appendChild(script);
}
//I WANT TO ADD THIS TO MY VIEWMODEL
var rates = function parseExchangeRate(YahooData) {
var rate = YahooData.query.results.row.rate;
}
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
$('[rel=tooltip]').tooltip();
})
The JSON returned from parseExchangeRate Function (Yahoo Query Result):
parseExchangeRate({"query":{"count":1,"created":"2013-01-18T06:46:41Z","lang":"en-US","results":{"row":{"rate":"0.1129","name":"ZAR to USD"}}}});
I see you're already using jquery so I'll use jquery for the JSONP too. I'm using a simple ko.observable for the conversion rate, and added a "bare" ko.computed that does the ajax request and asynchronously updates the observable. Let me know if you need any further clarification.
JSFiddle example (with mock data instead of your initial ajax): http://jsfiddle.net/VsW5H/1/
Updated code:
var currency = function (data) {
var self = this;
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(data.ConversionRate);
ko.computed(function () {
var from = self.CurrencyFrom(),
to = self.CurrencyTo();
if (!from || !to) {
self.ConversionRate("N/A");
return;
}
getRate(from, to).done(function (YahooData) {
console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
self.ConversionRate(YahooData.query.results.row.rate);
});
});
}
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push(new currency({
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
}));
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function (Form) {
alert("Could Now Save: " + ko.utils.stringifyJson(self.Currencies));
};
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
// Current Page, Method
data: '{}',
// parameter map as JSON
type: "POST",
// data has to be POSTed
contentType: "application/json; charset=utf-8",
// posting JSON content
dataType: "JSON",
// type of data is JSON (must be upper case!)
timeout: 10000,
// AJAX timeout
success: function (Result) {
var MappedCurrencies = $.map(Result.d,
function (item) {
return new currency(item);
});
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
//3rd Party JSON result from Yahoo Finance API
function getRate(from, to) {
return $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=?");
}

how to get value JSON in google API

I have google API, it return a JSON file
http://maps.googleapis.com/maps/api/geocode/json?latlng=10.75,106.667&sensor=false
I want to get "long_name" : "Hồ Chí Minh", "long_name" : "Việt Nam" and "short_name" : "VN"
I don't know JSON, I do like this
var API = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=10.75,106.667&sensor=false';
var obj = eval("(" + API + ")");
var obj2 = eval("(" + obj + ")");
document.getElementById("City").innerHTML = obj.results[0].obj2.address_components[0].long_name;
But it not working
I think you should read a little more about javascript. You must use a http get request to obtain the json, there is 2 ways to make this, using synchronous request or ajax request.
Try this :
//the json url
var API = 'http://maps.googleapis.com/maps/api/geocode/json?atlng=10.75,106.667&sensor=false';
//this function add the long_name
function addLongName(data){
var long_name = data.results[0].address_components[5].long_name;
document.getElementById("City").appendChild(document.createTextNode(long_name));
}
Using synchronous request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", API, false);
try {
xmlHttp.send(null);
responseText = xmlHttp.responseText;
var data = JSON.parse(responseText);
addLongName(data);
} catch (ex) {
console.error(ex);
}
Using ajax request
var ajax = $.ajax({
type : "GET",
url : API,
dataType: 'jsonp',
success: function(data) {
addLongName(data);
}
});