Ajax JSONP Express parseError from Safari Extension - ajax

First, I've read many posts here but haven't found the issue in my own code, including this one $.ajax and JSONP. ParseError and Uncaught SyntaxError: Unexpected token :
I'm building a Safari extension and need to post/get to my server and handle the response. Safari is throwing this error:
SyntaxError: Unexpected token ':'
and this message
"handle was not called"
where 'handle' is the callback in this Extension code:
var server="http://localhost:3001/api/login";
$.ajax({
type : "GET",
url : server,
data: {"something" : "else"}
dataType: 'jsonp',
jsonp:false,
jsonpCallback: 'handle',
success: function(data, text){
var json = $.parseJSON(data);
console.log(json)
},
error: function (request, status, error) {
console.log(error );
}
});
and the Express.js (2.5.5) code is:
//in the config
app.set( "jsonp callback", true )
app.all('/', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.get('/api/login', function(req, res){
res.json(
{
"success": {"that":"this"}
}
);
});
NOTES: I've tried res.jsonp, setting content types, etc, with same response. I've learned a TON about CORS and Ajax in the process, but my eyes are clearly bleary. Clicking my heels three times hasn't helped either.
Clues? Thanks!

By setting dataType: 'jsonp', it will already parse the JSON for you. jsonp: true is incorrect. This combo should work:
JSONP
$.ajax({
url : "http://localhost:3001/api/login",
data: {"something" : "else"},
dataType: 'jsonp',
success: function(data){
// It is already an object, don't parse it again.
console.log(data)
},
error: function (request, status, error) {
console.log(error );
}
});
with
app.get('/api/login', function(req, res){
res.jsonp({
"success": {"that":"this"}
});
});
// Remove this:
app.set( "jsonp callback", true )
CORS browsers and JSON:
$.ajax({
url : "http://localhost:3001/api/login",
data: {"something" : "else"},
dataType: 'json',
success: function(data){
// It is already an object, don't parse it again.
console.log(data)
},
error: function (request, status, error) {
console.log(error );
}
});
and
// This is 'app.use', not 'app.all'.
app.use('/', function(req, res, next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});
app.get('/api/login', function(req, res){
res.json({
"success": {"that":"this"}
});
});

Related

React AJAX post request does not go to success/error method

I have a React Component which calls an AJAX POST request.
The POST request creates an entry in the database as expected. (status 201 returned) However the success/error methods of the same are not called.
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend: function(xhr) {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success: function(data) {
console.log('success');
this.loadData();
},
error: function(xhr, status, err) {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});
The request is called through a button click. Also the browser hangs once the request is made, and the solution is to open a new tab.
Also i do not see the POST request on the Network tab of Chrome, but see it on the backend.
Any hints?
Try using ES6 arrow functions or bind your functions with this
$.ajax({
url: '/api/put/comment/',
dataType: 'json',
type: 'POST',
data: comment,
beforeSend:(xhr) => {
console.log('before send');
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'));
},
success:(data) => {
console.log('success');
this.loadData();
},
error:(xhr, status, err) => {
console.log('error');
this.setState({data:comments});
console.error(this.props.url, status, err.toString());
}
});

call server-side REST function from client-side

In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',

Can't set Access-Control-Allow-Origin request header

I making an AJAX request to the food2fork api and can't get by the No 'Access-Control-Allow-Origin' header is present error. I've tried setting the header in beforeSend and setting crossDomain: true but it didn't work.
This is my AJAX call:
$.ajax({
type: "GET",
dataType: 'json',
url: url,
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
},
success: function(data){
console.log('in ajax json call');
console.log(data);
$('#info').html(JSON.stringify(data));
}
});
I tried setting the request header server side in node express.js with:
router.get('/test', cors(), function(req,res)
{
res.set("Access-Control-Allow-Origin", "*"); //set header here
res.render('exampleSearch', {title: 'FM | Test'});
});
Cors is an npm package that sets cross-reference permissions but didn't help me solve the problem.
Can you tell me what I'm doing wrong?
Client-side request doesn't work in this case. I had to do the request server side:
router.post('/test', function(req,res){
var callback = function(response){
var str = '';
//another chunk of data has been recieved, so append it to `str`
response.on('data', function (chunk) {
str += chunk;
});
//the whole response has been recieved
response.on('end', function () {
var recipes = JSON.parse(str);
//do something with recipes
});
}
var options = {
host: "food2fork.com",
path: "/api/search?key=[myKey]&q=" + ingredients
};
http.request(options,callback).end();
});
Used code from nodejitsu.com

While converting from jquery to angularjs why am I getting this error?

Jquery Code
$.ajax({
url: '/ad_creation/get_campaign_objective/'+id,
dataType: 'text',
success: function(response) {
var campaign_objective = 'Error. Please refresh and try again.';
if (response == 'WEBSITE_CONVERSIONS')
campaign_objective = response;
if (response == 'WEBSITE_CLICKS')
campaign_objective = response;
$('select[name=campaign_objective]').val(response).hide();
$('#existing-campaign-objective').html(campaign_objective).show();
$('#campaign-objective-select').show();
if (campaign_objective == 'WEBSITE_CONVERSIONS'){
// Show pixel block again.
$('#select-pixel').show();
}
hideAjaxLoader('existing-campaign-loader');
},
error: function(xhr, ajaxOptions, thrownError) {
console.log('Invalid response', thrownError, xhr, ajaxOptions);
hideAjaxLoader('existing-campaign-loader');
}
});
Angularjs code
$http({
method:'get',
dataType:'text',
url:'/ad_creation/get_campaign_objective/'+Number(id)
})
.success(function(data){
console.log(data);
})
I get the error Unexpected token w. I have also tried not casting the id to number but still get the error.
Check the content-type of the response headers.
If it is 'application/json' angular tries to parse the response.
The error might be because of it.

Ajax Call with PUT method

i am trying to make ajax call with PUT method. Below is the code, but i am getting with the error XML Parsing Error: no element found Location: moz-nullprincipal:{c847a4af-f009-4907-a103-50874fcbbe35} Line Number 1, Column 1:
$.ajax({
type: "PUT",
async: true,
url: "http://localhost:8080/karthick/update",
data: JSON.stringify(params),
contentType: "application/json",
dataType: "JSON",
processdata: true,
success: function (json) { //On Successfull service call
},
error: function (xhr) {
alert(xhr.responseText);
}
});
return false;
};
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
But this service is working Good with Rest-client jar. Also my POST method works fine in my browser. Please help me in this.
Regards
Karthick
Usually, this error comes, when making a cross browser request. Try data: JSONP and see if it helps.

Resources