I am using AMcharts to show the JSON data returned by my web server. I am thinking of using the option like
chart.dataProvider : getData() { ... },
Here, I will make ajax call and return whatever data that the server sends. But the ajax call being asynchronous, I don't know know to how to supply the response data from the success function to the chart.
I contemplated on using dataLoader plugin, by supplying the url option like below..
"dataLoader" : {
"url": "my_server_url"
...
}
but this approach won't work for me, as I have to send some additional auth headers to my webserver, which I can do in my own ajax call.
DataLoader plugin's ajax request doesn't seem to fire my global ajax before send callback, so I cannot hook it to send auth token.
Any help here...
Building off what #martynasma said, here's a sample code snippet that worked for me...
return jQuery.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: 'https://www.example.com/endpoint', //replace with your endpoint url
beforeSend: function(xhr) {
// Add your parameters here
},
})
.done( function( data ) {
// Create the chart with data
var chart = am4core.create( 'chartdiv', am4charts.PieChart );
chart.data = data;
// Add and configure Series
var pieSeries = chart.series.push(new am4charts.PieSeries());
pieSeries.dataFields.value = "liters";
pieSeries.dataFields.category = "country";
})
.fail( function ( err ) {
console.log( err );
})
}
create_chart();
Related
I am trying to send json data through ajax call.
Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.
var filters =
{
"a" : a_filters,
"b" : b_filters,
"c" : c_filters,
"d" : d_filters
};
$.ajax({
url : "query/get-filtered-data",
dataType : 'json',
async: "true",
data:JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
success : function(data){
},
failure: function(data){
alert('got an error');
}
});
EDIT : This is my server-side code.
var express = require('express');
var router = express.Router();
//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {
console.log(req);
var filters = JSON.parse(req.body);
console.log("foo");
var a_filters = filters["a"];
var b_filters = filters["b"];
var c_filters = filters["c"];
var d_filters = filters["d"];
res.send(query);
});
conosle.log('foo') doesn't print anything.
console.log(req) has req.body empty.
Thanks a lot in advance.
Because you are referencing req.body, you need to use a router method that includes a body - post or put.
You may also need to include type: "POST" in your jQuery Ajax method.
There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.
Aim - to get the twitter followers of a particular user using javascript
I have tried the below code as a POC-
$(document).ready(function() {
// Handler for .ready() called.
$.ajax({
url: "https://api.twitter.com/1.1/followers/ids.json?callback=?",
type: "GET",
data: { cursor: "-1",
screen_name: "twitterapi" },
cache: false,
dataType: 'json',
success: function(data) { alert('hello!'); console.log(data);},
error: function(html) { alert(html); },
beforeSend: setHeader
});
function setHeader(xhr) {
if(xhr && xhr.overrideMimeType) {
xhr.overrideMimeType("application/j-son;charset=UTF-8");
}
//var nonce = freshNonce();
//var timestamp = freshTimestamp();
//var signature = sign(nonce,timestamp);
//alert(signature);
//alert(accessToken+"-"+consumerKey);
//alert(oauth_version+"-"+oauth_signature_method);
xhr.setRequestHeader('Authorization','OAuth');
xhr.setRequestHeader('oauth_consumer_key', 'HdFdA3C3pzTBzbHvPMPw');
xhr.setRequestHeader('oauth_nonce', '4148fa6e3dca3c3d22a8315dfb4ea5bb');
xhr.setRequestHeader('oauth_signature','uDZP2scUz6FUKwFie4FtCtJfdNE%3D');
xhr.setRequestHeader('oauth_signature_method', 'HMAC-SHA1');
xhr.setRequestHeader('oauth_timestamp', '1359955650');
xhr.setRequestHeader('oauth_token', '1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl');
xhr.setRequestHeader('oauth_version', '1.0');
}
});
I calculated the signature values from the Twitter OAuth tool ..
This gives me 400 Bad Request error ....
Please let me know what the problem is...
The problem is your request's header, it should be like this:
xhr.setRequestHeader('Authorization','OAuth oauth_consumer_key="HdFdA3C3pzTBzbHvPMPw", oauth_nonce="4148fa6e3dca3c3d22a8315dfb4ea5bb", oauth_signature="uDZP2scUz6FUKwFie4FtCtJfdNE%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp= "1359955650", oauth_token, "1127121421-aPHZHQ5BCUoqfHER2UYhQYUEm0zPEMr9xJYizXl", oauth_version="1.0"');
Btw, this javascript library might help you on OAuth's stuff: oauth-1.0a
It support both client side and node.js
Cheers
The oauth_* fields are all part of the Authorization header string, so they need to be concatenated as shown at the bottom of this page - https://dev.twitter.com/docs/auth/authorizing-request
They should not be presented as separate header fields.
Is there an AngularJS equivalent call to this jQuery ajax POST, with contentType and setRequestHeader?
$.ajax({
url: "http://localhost/songs",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
success: function(data){
console.log(data);
}
});
You'll probably want to use the $http or $resource service. In the $http doc you can see the section on Setting HTTP Headers to set the SOAPAction and the default content type will be set to json already (though you should be able to override that as well).
This might get you started and I'd be interested to see other answers for a better way because this seems limited.
var module = angular.module('myApp', []);
module.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['SOAPAction'] = 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems';
});
function myController($http) {
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data).success(function (data) {
console.log(data);
});
}
Based on this thread I don't believe you can set the headers differently for each call but it looks like a change might be coming to the $resource service that will allow it.
Update: Must have missed it in the documentation but you can most definitely set different actions per call using $http per this post like this:
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data, {headers: {'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'}})
.success(function (data) {
console.log(data);
});
I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request
I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...