Can't create and pass jsonp data - javascript

I am new to Node.js and I have created a method that should asynchronously fetch jsonp data via ajax and display the retrieved content in a graph. This method works fine when the url points to a static js file (in this case productsData.js) containing jsonp data:
function loadChart(destElementId, alertId) {
$.ajax({
url:'http://localhost:3000/products/data/productsData.js',
type: "GET",
data: {prodId: prodId},
jsonp: true,
dataType : 'json',
jsonpCallback: "jsonpCallback"
});
window["jsonpCallback"] = function(data) {
populateData(data, destId);
}
}
As in normal applications, I want to pass real data fetched via an external web service. I have created the following js file (data-client.js) that retrieves data from a specific web service. When calls are browser-based, the data is fetched successfully as a normal json and is displayed accordingly in the browser.
var express = require('express');
var router = express.Router();
var http = require('http');
var yaml_config = require('node-yaml-config');
var config = yaml_config.load(__dirname + '/../config/app-config.yml');
router.get('/data/:id', function (req, res, next) {
var opts = {
host: config.alertService.host,
port: config.alertService.port,
method: 'GET',
path: '/DataService/rest/receiveData/' + req.params.id
}
var reqGet = http.request(opts, function (dataResponse) {
var responseString = '';
dataResponse.on('data', function (data) {
responseString += data;
});
var response = {x:[],y:[],z:[],t:[]};
dataResponse.on('end', function () {
var responseObject = JSON.parse(responseString);
var accs = responseObject.data.listPCS;
for(var i in accs){
response.x.push(accs[i].accX);
response.z.push(accs[i].accY);
response.y.push(accs[i].accZ);
response.t.push(accs[i].timestamp);
}
res.json(response);
});
});
reqGet.end();
reqGet.on('error', function (e) {
console.error(e);
});
});
module.exports = router;
The first step for using live jsonp data is to replace the previous url value with:
url: 'http://localhost:3000/products/data/'+productId,
The second step is to replace in the data-client.js:
res.json(response);
with:
res.jsonp('jsonpCallback('+ JSON.stringify(response) + ');');
Somehow the data is not fetched. When I try to get the data via the browser (i.e. by entering http://localhost:3000/data/ID937) however I get the following result:
"jsonpCallback({\"x\":[1,1,1],\"y\":[2,1,4],\"z\":[0,0,9],\"t\":[1462790772000,1462790772010,1462790772020]});"
Can someone please tell me where the problem may be? I would be very thankful.

It looks like you are using Express.
jsonp() expects to be passed your raw data, not a string containing the complete response. It also expects to read the callback name from the query string, which jQuery will generate for you if you let it.
So the first thing to do is to fix your client side code so it passes the callback name correctly
On the client
$.ajax({
url: 'http://localhost:3000/products/data/' + productId,
dataType: 'jsonp',
}).done(function(data) {
populateData(data, destId);
});
The changes here are:
GET is the default (and, for JSONP, only option) so there is no need to specify the type.
You are passing the data as a URL path part, not a query string. Drop the data property that you aren't using.
The jsonp property is used to override the callback name. That's harmful, don't do that (likewise, don't specify jsonpCallback). jQuery will generate one for you and add it to the query string.
If you are dealing in JSONP then specify that as the data type, not JSON.
Don't create your own global manually. Pass your function to done and let jQuery make it a global (with a generated name to match the callback).
On the server
Just pass the data structure you want to send back to jsonp().
res.jsonp(response);
The callback name will be read from the query string by Express.

Related

Ajax can success() handle two type of return?

Working in a C# ASP.NET project with JavaScript/Jquery/jqGrid.
New task is to have a page to i) accept an Excel input file, ii) use the column ID to look up additional information, and iii) generate a new Excel file using some columns from input file and all columns returned from database.
I have completed that, but just want to do a bit more error handling. In the stored procedure, if everything works fine, it returns a data table (or in Oracle term, a CURSOR). If there is an error, I have added a catch block and return an error message.
I modify the AJAX call. Beside adding dataType as 'text', I expect the return as XML.
$.ajax({
// POST
// URL: url to call that stored procedure
dataType: text,
success: function (response) {
// now the response is XML (don't know why...
// specify dataType as 'text', but get XML...)
// If response contains 'string' tag, report error.
},
failure: ...
})
Here is what I used to do. I don't specify the dataType but somehow that works.
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
Download( response )
// The file is already and placed in Download directory.
// Call 'Download()' will actually make the download happen
// But here response is just a path to the Download directory +
// download file name.
And Download() is:
function Download(url) {
document.getElementById('my_iframe').src = <%=ResolveUrl("~/")%> +url;
return false
};
How can I have the success function handle both type of response?
(Just for your information: The front-end page is ASP.NET. Button click will call a JavaScript function. The function calls a web service function via $.ajax(). As there are many rows, the web service function calls a function in a database class many times - each time pass in just one ID. The function will in return call stored procedure.)
Edit: Thanks for solution from Mustapha Larhrouch. Here are some points that I have to adjust:
Add dataType.
If response is XML, check if error.
If not XML, just download.
And here is my code:
$.ajax({
// POST
// URL
dataType: "text",
success: function (response) {
if (isXML(response)) {
var xmlDoc = $.parseXML(response);
$xml = $(xmlDoc);
var errMsg = $xml.find("string").text();
if (errMsg != "" ) {
// pop up a dialog box showing errMsg
}
}
else {
Download(response);
}
you can check if the response is an xml if it's parse it, if not the response is a string. and you can use this function to check if the response is an xml :
function isXML(xml){
try {
xmlDoc = $.parseXML(xml); //is valid XML
return true;
} catch (err) {
// was not XML
return false;
}
}
$.ajax({
// POST
// ... rest is same but without the dataType
success: function (response) {
if(isXML(response){
Download( response )
}
else{
//report as error
}

Ajax call don't receive html content from MVC Action

This is my action:
[HttpGet]
public virtual ActionResult DesignItemsList(int dealId, string sort)
{
return View(MVC.Designer.Views._DesignItems, _designerService.GetDesignItems(dealId, sort));
}
The GetDesignItems() method is working correctly.
$(document).ready(function() {
$('.product__filtr__form__select').change(function(e) {
var sort = $(this).val();
var urlFilter = $('#url-filterPanel-hidden-field').val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
$.ajax({
type: "GET",
data: {
dealId: dealId,
sort: sort
},
url: urlItems,
success: function (result) {
console.log(result);
$('#Product-Items-Container').html(result);
}
});
});
});
Request is working too, but I don't receive the response and get only 500 code.
500 error code means, Internal server error. Your action method failed to process thie request you sent.
Since it is a GET action method, You may add the query string parameters to the url.
var sort = $(this).val();
var dealId = $('#dealId-hidden-field').val();
var urlItems = $('#url-items-hidden-field').val();
urlItems = urlItems+"?dealId="+dealId+"&sort"+sort;
//Let's write to console to verify the url is correct.
console.log(urlItems);
$.get(urlItems,function(res){
console.log('result from server',res);
$('#Product-Items-Container').html(res);
});
Try to replace the view name inside your controller:
return View("YourControllerView", _designerService.GetDesignItems(dealId, sort));
Because I was tested your ajax request and find out that it works fine.
And pay attention to view location. This view must be located inside the directory with the same name as your controller or inside the shared dictory

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

Setting object properties using AJAX

I am newbie in OOP and I try to build an object using ajax request. What I need is to get 'responseArray' in JSON format and than work on it.
function adres(adres) {
this.adres_string = adres;
var self = this
$.ajax({
type: 'POST',
url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
success: function(data) {
self.responseArray = eval('(' + data + ')')
}
})
//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
return lonlat;
}
}
The problem starts when in appilcation code I write:
var adr = new adres('Zimna 3, Warszawa');
adr.getLonLat();
This returns nothing as there is no time get the response from the server.
How to write it properly in the best way? I've read about when().then() method in jQuery. This may be OK for me. I just want to get know best practise
This is how AJAX works (notice the A-synchronous part). You are right, the moment you call adr.getLonLat() response did not yet came back. This is the design I would suggest: just pass callback function reference to adres constructor:
function adres(adres, callbackFun) {
//...
success: function(data) {
var responseArray = eval('(' + data + ')')
var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
callbackFun(lonlat)
}
and call it like this:
adres('Zimna 3, Warszawa', function(lonlat) {
//...
})
Few remarks:
adres is now basically a function, you don't need an object here.
do not use eval to parse JSON, use JSON object.
Are you sure you can POST to http://nominatim.openstreetmap.org? You might hit the same origin policy problem
where is the i variable coming from in responseArray[i]?

Categories

Resources