Ajax call throws parse error - json

I am getting a parse error when trying to perform the following call:
$.ajax({
cache: true,
url: "http://localhost:3000/app/test/result1",
data: "{}",
type: "GET",
jsonpCallback: "testCall",
contentType: "application/jsonp; charset=utf-8",
dataType: "jsonp",
error: function (xhr, status, error) {
alert(error);
},
success: function (result) {
alert(result);
},
complete: function (request, textStatus) {
alert(request.responseText);
alert(textStatus);
}
});
If I paste the request url in the browser address bar directly, the result returned is seems to be valid JSON:
{
"name": "The Name",
"description": "The Description"
}
I am using IISnode, NodeJs & Express JS. I have tested both scenarios:
// NODE JS CODE
var app = express();
app.get('/app/test/result1', function (req, res) {
res.send({ name: "The Name", description: "The Description" });
});
app.get('/app/test/result2', function (req, res) {
res.send(JSON.stringify({ name: "The Name", description: "the Description" }));
});
Any advice is appreciated, thanks in advance.

Your dataType is listed as jsonp. However, your response from node.js is not a properly formatted JSON-P response. JSON-P responses need to be wrapped in a callback, like so:
testCall({ name: "The Name", description: "The Description" });
The node.js code would look something like this:
res.send(
'testCall(' +
JSON.stringify({ name: "The Name", description: "the Description" }) +
');'
);
(Also note that you don't need the data: "{}" line since the request is a GET request and doesn't include any data. It shouldn't hurt anything, but might be nice to remove to avoid confusion).

Related

How to post Handsontable data into WordPress REST API?

I'm trying to post the data from Handsontable into WordPress using WP REST API. This is what I tried :
$('#publish').on('click',function(e){
var data = JSON.stringify(hot.getDataAtRow(0));
$.ajax({
url: 'domain.com/staging/wp-json/wp/v2/posts/',
method: 'POST',
crossDomain: true,
dataType: 'json',
contentType: 'application/json',
data: data,
beforeSend : function(xhr) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
success: function( data ) {
console.log( data );
},
error: function ( error ) {
console.log( error );
}
});
});
I get this response :
{"code":"empty_content","message":"Content, title, and excerpt are
empty.","data":{"status":400}}
However, the output of JSON.stringify(hot.getDataAtRow(0)) is looks like this :
["John Doe","Sample text","publish"]
I tried manual way by set the data like this, it works :
data: {
"title": "John Doe",
"content": "Sample text",
"status": "publish"
}
So my question is :
How to get the data from Handsontable on that format? I need to set which field is the title, content, status, excerpt, etc.
The output of your JSON.stringify(hot.getDataAtRow(0)) gets you an array of strings, whereas API expects an object with 3 fields.
Try:
var data = {
"title": hot.getDataAtCell(0, 0),
"content": hot.getDataAtCell(0, 1),
"status": hot.getDataAtCell(0, 2),
};
And then in your AJAX call:
data: JSON.stringify(data),

Error:In JSON data submission unexpected character

I am trying to send a push notification using onesignal.In that process i got an error
"error":"There was a problem in the JSON you submitted: unexpected character at line 1, column 1 [parse.c:652]"}
My Code is as follows:
var jsonBody = {
"app_id": "OneSignal App ID",
"include_player_ids": ["Onesignal Playerid"],
"headings": {
"en": "Sump"
},
"contents": {
"en": " Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: jsonBody,
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
Can anyone help me where i am going wrong.
Thankyou.
Hi try to create an object then stringfy it to json.
var jsonBody =
{
app_id: "OneSignal App ID",
include_player_ids: [ "Onesignal Playerid", "Secondsignal Playerid"],
headings :
{
en: "Sump"
},
contents :{
en: "Sump Level is 'Sumpper' "
}
};
var request = $.ajax({
url: "https://onesignal.com/api/v1/notifications",
headers: {
'Authorization':'Basic REST API Key',
'Content-Type':'application/json',
'Access-Control-Allow-Headers': 'SDK-Version',
'Access-Control-Allow-Origin': '*'
},
type: "POST",
data: JSON.stringify(jsonBody),
dataType: "json"
});
console.log(request);
request.success(function(msg) {
console.log("success");
});
request.error(function(jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});

GitHub API AJAX POST returning 422

I'm trying to post an issue via the GitHub API and keep getting a 422 error. I've tried various approaches over the past few days with no luck - I'm hoping this is a simple mistake that someone can spot quickly?
My call is below - I'm using my Personal Access Token for authorization.
$.ajax({
type: "POST",
url: `https://api.github.com/repos/MYUSERNAME/MYREPONAME/issues?access_token=MYACCESSTOKEN`,
contentType: "application/json",
dataType: "json",
data: JSON.stringify({
"title": "Found a bug",
"body": "I'm having a problem with this."
})
}).done(function( data ) {
console.log( data );
});
Thanks in advance.
FYI finally got this to work with the code below to POST to the GitHub API (creating an issue):
$.ajax({
url: 'https://api.github.com/repos/USERNAME/REPONAME/issues',
type: 'POST',
dataType: 'json',
headers: {
Authorization: 'token MY_PERSONAL_TOKEN'
},
data: JSON.stringify({
"title": "Found a bug",
"description": "Bug description"
}),
success: function (response) {
console.log(response);
}
});

Alchemy sentiments text API json parse error

Hi I am making the call for alchemy sentiments API as given below:
function getAnalysis(sentence)
{
$.ajax({
url:alchemy.baseUrl,//http://access.alchemyapi.com/calls/text/TextGetTextSentiment`enter code here`
type: 'POST',
dataType:'jsonp',
contentType:'json',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
outputMode:'json'
//outputMode:'xml'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
I am getting status 200 OK. But error in parsing : is returned from ajax call. I have validated JSON it is correct.The json is below:
{
"status": "OK",
"usage": "By accessing AlchemyAPI or using information generated by AlchemyAPI, you are agreeing to be bound by the AlchemyAPI Terms of Use: http://www.alchemyapi.com/company/terms.html",
"url": "",
"language": "english",
"text": "sachin is a good batsman.",
"docSentiment": {
"type": "positive",
"score": "0.50098"
}
}
Please help me.
I have solved the question just by modifying the ajax request and adding the callback as given below:
function getAnalysis(sentence)
{
$.ajax({
url: alchemy.baseUrl,
type: 'POST',
dataType:'jsonp',
contentType:'json',
jsonpCallback:'callback',
data:{
apikey:alchemy.acessKey,
text:sentence,
showSourceText:1,
jsonp:'callback',
outputMode:'json'
},
context: this
}).done(function(data){
console.log('Sentiments Analysis sucessfull..');
console.log(data);
var text=data.text;
if(data.docSentiment.type==="negative")
{
displayNegetiveAnalysis(text);
}
else if(data.docSentiment.type==="positive"){
displayPositiveAnalysis(text);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log('Sentiments Analysis error:', textStatus, errorThrown);
});
}
/*
* Function:Callback
* Description:passing callback to URL Call
*
*/
function callback(json){
console.log(json);
}

Ajax post data store with json and jsonData

i want to write a data store, that gets its data by an ajax call. The ajax call has to be a http post message and has to contain some data in json format.
Thats what I have so far:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
proxy: {
actionMethods : {
read : 'POST'
},
type: 'ajax',
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
url : apiUrl + 'Files/GetFileInfo',
jsonData : '{"file": "myfile"}'
}
});
The call to the webservice works, but the variable "file" is always empty. What is wrong here?
Got it by writing a custom proxy
store:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
requires: ['MyApp.proxy.FileContent'],
proxy: {
type: 'FileContent'
}
});
proxy:
Ext.define('MyApp.proxy.FileContent', {
extend: 'Ext.data.proxy.Proxy',
alias: 'proxy.FileContent',
create: function (operation, callback, scope) {
//Here goes your create logic
},
read: function (operation, callback, scope) {
Ext.Ajax.request({
url: apiUrl + 'Files/GetFileInfo',
method: "POST",
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
jsonData: '{"file": "myfile"}',
success: function(response){
var json = JSON.parse(response.responseText);
},
failure: function(){
alert("fail");
}
});
},
update: function (operation, callback, scope) {
//Here goes your update logic
},
destroy: function (operation, callback, scope) {
//Here goes your delete logic
}
});