How to generate a POST request - javascript

How to write the underlying code given in the Moxtra API in jQuery or JavaScript
POST /v1/UiaduESWsbzFoK9TOldC6zF/binders
{
"name": "My First Binder"
}
{
"code": "RESPONSE_SUCCESS",
"data": {
"id": "B7U3ze39oO08PYO70973lX6",
"name": "My First Binder",
"revision": 3,
"created_time": 1342813061602,
"updated_time": 1342813061602
}
}

Assuming you want to POST the first object and receive the second object as a successful response, here's how you'd do it with jQuery's shorthand AJAX POST function:
var data = {"name": "My First Binder"};
$.post("/v1/UiaduESWsbzFoK9TOldC6zF/binders", data, function(response) {
// Response object contains your response from the server
console.log(response);
});

Related

Javascript parse JSON error, but works fine in validator

When I try to parse this JSON (Discord webhook):
{
"content": "this `supports` __a__ **subset** *of* ~~markdown~~ 😃 ```js\nfunction foo(bar) {\n console.log(bar);\n}\n\nfoo(1);```",
"embed": {
"title": "title ~~(did you know you can have markdown here too?)~~",
"description": "this supports [named links](https://discordapp.com) on top of the previously shown subset of markdown. ```\nyes, even code blocks```",
"url": "https://discordapp.com",
"color": 16324973,
"timestamp": "2018-12-18T09:22:12.841Z",
"footer": {
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png",
"text": "footer text"
},
"thumbnail": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"image": {
"url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"author": {
"name": "author name",
"url": "https://discordapp.com",
"icon_url": "https://cdn.discordapp.com/embed/avatars/0.png"
},
"fields": [
{
"name": "🤔",
"value": "some of these properties have certain limits..."
},
{
"name": "😱",
"value": "try exceeding some of them!"
},
{
"name": "🙄",
"value": "an informative error should show up, and this view will remain as-is until all issues are fixed"
},
{
"name": "<:thonkang:219069250692841473>",
"value": "these last two",
"inline": true
},
{
"name": "<:thonkang:219069250692841473>",
"value": "are inline fields",
"inline": true
}
]
}
}
Using this code:
var parsed = JSON.parse(req.body)
I get this error:
SyntaxError: Unexpected token o in JSON at position 1
But if I use a website such as
https://jsonformatter.curiousconcept.com
To validate the JSON, it says the JSON is valid.
What is wrong here?
UPDATE
I'm using an express server to simulate discord server, so it sends web hooks to the express server instead, I get the JSON using req.body.
This happens because JSON is a global object (it's the same object where you read the method parse!), so when you invoke JSON.parse(JSON) javascript thinks you want to parse it.
The same thing doesn't happen when you pass the variable to the validator, because it will be assigned to a local variable:
let JSON = "{}";
validate(JSON);
function(x) {
JSON.parse(x); // here JSON is again your global object!
}
EDIT
According to your updated question, maybe it happens because you already use bodyParser.json() as middleware, and when you use it, req.body is already an object and you don't need to parse it again.
Trying to parsing an already parsed object will throw an error.
It would be something like without using JSONStream:
http.request(options, function(res) {
var buffers = []
res
.on('data', function(chunk) {
buffers.push(chunk)
})
.on('end', function() {
JSON.parse(Buffer.concat(buffers).toString())
})
})
For using it with JSONStream, it would be something like:
http.request(options, function(res) {
var stream = JSONStream.parse('*')
res.pipe(stream)
stream.on('data', console.log.bind(console, 'an item'))
})
(OR)
Here is the Some Steps for this issue..
You Can use lodash for resolving this.
import the lodash and call unescape().
const _ = require('lodash');
let htmlDecoder = function(encodedStr){
return _.unescape(encodedStr);
}
htmlDecoder(JSON);

Backbone .fetch() adds one too many models

I am using backbone's fetch method to retrieve a set of JSON from the server. Inside the fetch call, I have a success callback that correctly assigns attributes to a model for each object found.
var foo = assetCollection.fetch({
reset: true,
success: function(response){
var data = response.models[0].attributes.collection.items;
data.forEach(function(data){
assetCollection.add([
{src_href: data.data[0].value,
title: data.data[1].value
}
]);
});
console.log(assetCollection.models)
}
})
Right now I am working with a static set of JSON that has two objects. However, logging assetCollection.models returns three objects: the first is the initial server JSON response, while the next two are correctly parsed Backbone models.
How do I keep Backbone from adding the first object (the entire response from the server) to its set of models, and instead just add the two JSON objects that I am interested in?
The JSON object returned from the server is as follows:
{
"collection": {
"version": "1.0",
"items": [
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://cdn.images.express.co.uk/img/dynamic/36/590x/robin-williams-night-at-the-museum-498385.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Robin as Teddy Roosevelt"
}
]
},
{
"href": "http://localhost:8080/api/assets/d7070f64-9899-4eca-8ba8-4f35184e0853",
"data": [
{
"name": "src_href",
"prompt": "Src_href",
"value": "http://b.vimeocdn.com/ts/164/830/164830426_640.jpg"
},
{
"name": "title",
"prompt": "Title",
"value": "Mrs. Doubtfire"
}
]
}
]
}
}
You should modufy collection.
Probably you should change parse method:
yourCollection = Backbone.Collection.extend({
parse: function(data) {
return data.models[0].attributes.collection.items;
}
})
When you use fetch Backbone parse result and add all elements what you return in parse.

Attempting to parse or assign JSON response: Response is read as [object Object] [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Using Flickr API, Javascript/JQuery, and AJAX, I have the follow code:
function getRequest(arguments)
{
var requestinfo;
$.ajax({
type: 'GET',
url: flickrurl + '&'+ arguments + '&jsoncallback=jsonCallback',
async: false,
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (json)
{
requestinfo = json;
//Parse attempt requestinfo = $.parseJSON(json);
//Old method return json;
}
});
return requestinfo;
}
When the response is received and I attempt to assign the json (the response) data to the variable, requestinfo, (or even if I do a straight 'return json' line) I get an error indicating the returned value is undefined. Upon fooling with the success function, I notice that any attempts to parse the response fails due to 'json' being read as [object Object] instead of the JSON response.
Is the response already in array format? If not, how can I get it to that point?
Here is an example JSON response (there are multiple types as different requests are needed to receive all needed information (Flickr API):
{
"collections": {
"collection": [
{
"id": "122388635-72157643471284884",
"title": "Test Gallery 2",
"description": "Test 2",
"iconlarge": "/images/collection_default_l.gif",
"iconsmall": "/images/collection_default_s.gif",
"set": [
{
"id": "72157643471292484",
"title": "Set 1",
"description": ""
}
]
},
{
"id": "122388635-72157643469075734",
"title": "Test Gallery 1",
"description": "Bing Photos",
"iconlarge": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_l.jpg",
"iconsmall": "http://farm3.staticflickr.com/2888/cols/72157643469075734_b9a37df67c_s.jpg",
"set": [
{
"id": "72157643469056814",
"title": "Test Gallery 1",
"description": "Bing Backgrounds"
}
]
}
]
},
"stat": "ok"
}
So how do I pass the received data to other functions without a disruption in the data?
Code should be much like below
success: function (collections)
{
$.each(collections,function(index,item){
var i=0;
$.each(item.conllection[i],function(index,item){
alert(item.id);
i++;
});
});

Json returns every character as a separate object?

I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);

Using JQuery .getJSON to read in an array

I aam trying to GET an array from a JSON file using JQuery's ajax methods. Specifically, I want to make the ajax request on document load and use the acquired data in other functions.
Here is my code:
$(document).ready(function() {
getJSON();
clickEvents();
});
function getJSON() {
$.getJSON('goods.js', function(data) {
crazyFun(data.Goods);
addScores(data.karma);
});
}
}
function addScores(karma) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
function crazyFun(Goods) {
for (var i = 0; i < Goods.length; i++) {
var alpha= $('#template').clone();
alpha.removeAttr('id');
alpha.find('div.picture').attr('id', Goods[i].picture);
alpha.find('h2').html(Goods[i].header);
alpha.find('p').html(Goods[i].text);
alpha.find('div.notification').attr('id', Goods[i].notification);
$('#repeater').append(alpha);
}
}
karma and Goods are the name of the arrays in the JSON file.
What am I doing wrong?
Here is my JSON array for karma:
{
Goods : [{
"header": "Apple",
"text": "hi"
"picture": "appleImage",
"notification": "appleNote"
}, {
"header": "Pear",
"text": "hi",
"picture": "pearImage",
"notification": "pearNote"
}, {
"header":hi",
"picture": "bananaImage",
"notification": "bananaNote"
}, {
"header": "Dog",
"text": "hi",
"picture": "dogImage",
"notification": "dogNote"
}, {
"header": "Cat",
"text": "hi",
"picture": "catImage",
"notification": "catNote"
}, {
"header": "Snake",
"text": "hi",
"picture": "snakeImage",
"notification": "snakeNote"
}],
karma : [{
"karmaYinYangScore": "200",
"KarmaGiveScore": "40",
"KarmaTakeScore": "99",
"ItemsGiveScore": "20",
"ItemsTakeScore": "77"
}];
}
I can only guess what your data looks like, but since you said "karma and Goods are the name of the arrays", I'm going to assume we're talking about something like this:
{
karma: [{
karmaYinYangScore:'some value',
KarmaGiveScore:'some value',
KarmaTakeScore:'some value',
ItemsGiveScore:'some value',
ItemsTakeScore:'some value'
}
],
Goods: ['more','array','values']
}
If that's the case, we've got a few issues in your code.
First, getJSON returns one data result, so you should be referencing only that data returned.
function getJSON() {
$.getJSON('goods.js', function( data ) {
crazyFun( data.Goods ); // reference Goods array from data response
addScores( data.karma ); // reference karma array from data response
});
}
Then, your .addScores() function doesn't accept a parameter. You need some reference to receive the array being passed.
// Reference to the array being passed to the function
// ---------------v
function addScores( karma ) {
$('#karmaYinYangScore').append(karma[0].karmaYinYangScore);
$('#KarmaGiveScore').append(karma[0].KarmaGiveScore);
$('#KarmaTakeScore').append(karma[0].KarmaTakeScore);
$('#ItemsGiveScore').append(karma[0].ItemsGiveScore);
$('#ItemsTakeScore').append(karma[0].ItemsTakeScore);
}
These are the only errors I see. Beyond that, the solution depends on the actual data structure of the response.
According to jQuery's documentation on the getJSON function (http://api.jquery.com/jQuery.getJSON/), your callback's parameters appear to be misleading. Your callback...
function(Goods, karma) {
crazyFun(Goods);
addScores(karma);
}
...appears to be expecting the arrays of data to be passed to it automatically, but jQuery actually passes the whole JSON result as the first parameter, and the status of your request as the second parameter, regardless of how the JSON is structured. Your callback should probably look more like this:
function(json, status) {
crazyFun(json.Goods);
addScores(json.karma);
}
This assumes that your JSON is well formed, and that the "Goods" and "karma" properties are properties of the root object. You may need to modify the callback if your JSON is structured differently.

Categories

Resources