Ajax call results in 500 {internal server error} - ajax

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.

Related

Object property name changes when parsing it to node js

I have an object:
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and when i am sending it to node js with ajax the moment it gets into the router.post it transforms into this
{"description":"Κλείσε τις βάνες","closeValves[]":["13/21","12/31","13/12","12/32"]} ..
Any ideas why this is happening? in the node script where i have the router.post i am requiring this
let express = require('express');
let router = express.Router();
Update at comment:
the call the function:
formEvent(json,'events/entry',valvescallback);
and the function AJAX:
function formEvent(data,module,next,e){//the request function
e=e||false;
console.log("form:",data)
if( e ){e.preventDefault();}
var url = './'+module; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: data,
dataType:'json',
success: function (data) {
next(data);
},
error:function (data) {
next(data)
}
});
}
Update at comment 2:
No the data come from postgress SQL in a text type column like this
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and i am using this to transform it into json and parse it:
var json = jQuery.parseJSON(data.task);
json.action = 'getValves';
json.test = json.closeValves;//test to see if it also changes name
I can see that it transformes any property that is an array like this
name:[1,2,3] --> name[]:[1,2,3]
the odd is that when I am console.log the data inside the AJAX function the are in the right form but inside the post they change..
I found it!! the answer is at the definition of the body-parser npm usage:
app.use(bodyParser.urlencoded({ extended: false}));
you just need to make the extended property true and the array name will not change.. so the answer is
app.use(bodyParser.urlencoded({ extended: true}));

amcharts - load ajax data

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

$.ajax() vs $.getJSON() with YQL and cross domain requests

I'm trying to execute a cross domain request for data from a wordpress blog using YQL. This is the code from my first attempt:
var g = {data:""}
function getWP() {
var targeturl = "http://www.mysite.com";
var url = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(targeturl)+
"%22&format=xml'&callback=?";
var successfunc = function(data) {
if(data.results[0]){
g.data = data.results[o];
} else {
var errormsg = '<p>Error: could not load the page.</p>';
alert(errormsg);
}
}
$.ajax({
url: url,
success: successfunc
});
}
When I tried this ajax call, the data object returned was an empty string. However, when I did this:
$.getJSON(url, successfunc);
the proper JSON object was returned. What is the difference between the two calls? And more importantly, why did only the second one work?
The difference is that you are not specifying your data type or content type
Add
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successfunc
});
to your ajax call
$.getJSON() uses data type json while the $.ajax() doesn't. If you want to use standard $.ajax() you'll have to specify datatype explicitly. For cross-domail calls use datatype jsonp instead of json. But I think YQL works with json as well.

Jquery Ajax - Tumblr API v2

I'm trying to delve into the depths of the murky world of Tumblr, and can't understand how to get over the following error:
Uncaught SyntaxError: Unexpected token :
I believe it may be because I'm getting back json, but trying to use jsonp. Here's what I'm trying to send:
$(function(){
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi"
},
success: function(data){
console.log(data);
},
});
});
I get a 200 OK response, and the data but still the above error (which I don't understand and would like to know more about)
Tumblr also kindly points out the following, but I'm unclear on the specifics.
All requests made with HTTP GET are JSONP-enabled. To use JSONP,
append jsonp= and the name of your callback function to the request.
JSONP requests will always return an HTTP status code of 200 but will
reflect the real status code in the meta field of the JSON response.
Any help would be awesome, thanks!
Do what Tumblr is telling you to - add a callback function name to the request
myJsonpCallback = function(data)
{
console.log(data);
}
$.ajax({
type: "GET",
url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
dataType: "jsonp",
data: {
api_key : "MyTumblrApi",
jsonp : "myJsonpCallback"
}
});
========================================================
EDIT: The console.log thing is a syntax error since I didn't actually test this code.
What happens to success? I don't really know. Try and find out :) It will probably be called but data parameter likely be null or something.
The issue here is that jQuery names it's callback parameter callback, where as Tumblr is expecting jsonp. Upon 200 response jQuery likely simply eval()s the response, which is why myJsonpCallback is actually called.
In case you don't want to use jQuery:
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/{blog.tumblr.com}/posts?api_key={your api key}&jsonp=callback");
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
function callback(data){
console.log(data);
}
I've created simple function for this purpose:
function jsonpRequest(opt){
var params = "";
var blogName = "{your blog name}";
var api_key = "{api key}";
if("selector" in opt){params = "id=" + opt.selector;}
if(("offset" in opt) && ("limit" in opt)){params = "limit=" + opt.limit + "&offset=" + opt.offset;}
if("callback" in opt){params += "&jsonp=" + opt.callback;}else{params += "&jsonp=callback";}
params += "&api_key=" + api_key;
var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/" + blogName + "/posts?" + params);
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
}
How to use it:
jsonpRequest({offset: 50, limit: 5});
function callback(data){do stuff here ...}
Alternative usage:
jsonpRequest({offset: 50, limit: 5, callback: "nameOfMyAmazingCallbackFunction"});
function nameOfMyAmazingCallbackFunction(data){do stuff here ...}

DOJO xhrGet how to use returned json object?

How can I access the data returned from the xhrGet outside of the get itself? Firebug shows that the "json" object has an array called results, which stores the json Object from the response, but when I try to access it it is null. So: how do I access the received data on the last code line?
var json = dojo.xhrGet({
url :'/disease_web/graphMlDownload/getEdgeInformation/', handleAs:"json",content : { edgeid : edgeId, graphname:this._canvas.path},
load:function(response){
return response;
}
});
console.log(json.ioArgs);
console.log(json.results);
By default dojo.xhrGet is called asynchronously, so console.log(json.results) is null because it's run just after dojo.xhrGet, but before response comes from server.
var xhrGet = dojo.xhrGet({
url: "/some_rul",
handleAs: "json",
handle: function(response) {
console.info(2,'response',response);
console.info(3,'xhrGet.results[0]',xhrGet.results[0]);
}
});
console.info(1,xhrGet.hasOwnProperty('results'));
The result is:
1 false
2 response - ['some data from server']
3 xhrGet.results[0] - same data as in 'response' accessed via xhrGet
The simplest way to access your retrieved JSON data is to assign it to a document-level variable within the xhrGet load function:
var fetchedData = null;
function parseResponse() { /* do something meaningful */ }
dojo.xhrGet({
url: "{{dataUrl}}dojo/LICENSE",
handleAs: "json",
preventCache: true,
load: function(response){
// save for later
window.fetchedData = response;
// do whatever processing we want with the returned data
parseResponse();
},
error: function(error){
alert("Couldn't fetch your data: " + error);
}
});
Yeah, no. I've since learned a much better way, and forgot to come back and fix this answer, so it deserves the downvotes it's accrued.
The proper way to deal with data fetched from dojo.xhrGet, jQuery.ajax, or any other asynchronous data fetch is to write a function to process its results, and pass it to xhrGet as the load argument, like so:
var request = dojo.xhrGet({ url :'/disease_web/graphMlDownload/getEdgeInformation/',
handleAs: "json",
content : {edgeid : edgeId, graphname:this._canvas.path},
load: doSomethingWithMyEdges
});
function doSomethingWithMyEdges(json_results) {
console.log(json_results);
}

Resources