Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  183] [ 7]  / answers: 1 / hits: 10830  / 10 Years ago, wed, june 4, 2014, 12:00:00

I have a node server and an application from another server doing a AJAX jsonp request via jquery to get a json array of parameters, but when i request the data the jquery throws this error:



Uncaught TypeError: Cannot read property 'toLowerCase' of undefined 


The request is sent and i get the response, but i can't get the data in the javascript client-side



Node server:



var my_http = require('http');


var databaseUrl = leitordecarga; // username:[email protected]/mydb
var collections = [tables]
var db = require(mongojs).connect(databaseUrl, collections);

var callback = [];
db.tables.find(function(err,values){
if(err || !values){
console.log('error');
}else{
values.forEach(function(value){
callback.push(value);
});
}
});


my_http = require(http);
my_http.createServer(function(request,response){
response.writeHeader(200, {Content-Type: application/json});
response.write(JSON.stringify(callback));
response.end();
}).listen(8080);


Javascript in client-side:



$(document).ready(function(){
$.ajax({
url:'http://localhost:8080/mongo.js',
dataType:'jsonp',
type: GET,
jsonp : callback,
contentType: application/jsonp,
success: function(data){
console.log(data);
},
error: function(data){
console.log(data.getResponseHeader());
}
}).done(function( data ) {
console.log(data);
});
});


im using jquery 2.1.0 but i've tried other versions and the error persists



My question is how i can get the data in the success clause


More From » jquery

 Answers
7

JSONP response differs from JSON response. With JSONP you actually respond with a JavaScript code.



So you have to modify your code like this:



First, require querystring module in the top of your script:



var qs = require('querystring');


And then you have to rewrite your HTTP request handler:



my_http.createServer(function(request,response){  
var funcName = qs.parse(request.url).callback;
response.writeHeader(200, {Content-Type: text/javascript});
response.write(funcName + '(' + JSON.stringify(callback) + ');');
response.end();
}).listen(8080);


You can learn more about JSONP here


[#44819] Tuesday, June 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;