Javascript: send object with object inside trought post method - javascript

I'm pretty new to javascript and i'm trying to send an object with an other object inside trought post method:
$.post('/posttest', {tableName : 'WSTest', data : {name : "Rachid", age : 42, ville : "Tokyo"}}).done(function(data) {
console.log("data posted : ", data);
});
I can retrieve tableName with req.body.tableName but req.body.data give me undefined. When i console.log(req.body) i got:
{ tableName: 'WSTest',
'data[name]': 'Rachid',
'data[age]': '42',
'data[ville]': 'Tokyo' }
As far as i understand it, javascript takes data as a dico ? How can i make data as an object ?

Standard form encoded data is a flat data structure. It is just key/value pairs.
A non-standard extension to the syntax was introduced by PHP which allows you to describe nested data, but your parser doesn't appear to recognise it.
To access the data you will need to mention the square brackets.
req.body["data[name]"]
// etc
Alternatively, find a parser which does recognise the square brackets as having special meaning.
Assuming you are using the (fairly common) "URL-encoded form body parser" feature of the body-parser module, see the docs:
extended
The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The "extended" syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.
So:
app.use(bodyParser.urlencoded({ extended: true }));
… will probably do the trick.

Related

How can I make HTML fill itself with the content from the JSON file using handlebars?

I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.
I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB
Now I need content to lay initially in a JSON file.
I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.
How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.
What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?
For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?
Try this:
HTML:
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>
JS:
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', "http://date.jsontest.com/");
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById('testData').innerHTML += template(response);
})
JSON:
JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.
JavaScript Object Notation has set of rules.
Starts with open curly braces ( { ) and ends with enclosing curly braces ( } )
ex: {}
Inside baces you can add 'key' and its 'value' like { "title" : "hello json"}
here "title" is key and "hello json" is value of that key.
"key" should be string
"value" can be:
number
string
Boolean
array
object
Can not add JavaScript comments inside JSON (like // or /**/)
there are many online JSON validators, you can check whether your JSON is valid or not, check here.
When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.
here XMLHttpRequest our interface. we usually call XMLHttpRequest API.
In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)
for more information on REST API you can check here
from the url: http://date.jsontest.com/ you can get JSON object like below.
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016"
}
Note: data is dynamic; values change on each request.
So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object, JSON.parse( /* your JSON object is here */ ) converts JSON to js Object
`var responseObject = JSON.parse(xhr.responseText)`
by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.
console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"
console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318
console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"
So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".
'sendGet' function updatedin the above js block with comments please check.
In simple way:
create XMLHttpRequest instance
ex: var xhr = new XMLHttpRequest();
open request type
ex: xhr.open('GET', "http://date.jsontest.com/");
send "GET" request to server
ex: xhr.send();
register load event handler to hold JSON object if response has status code 200.
ex: xhr.onload = function () {
for more info check here
Know about these:
Object literal notation
difference between primitive and non-primitive data types
Existing references:
What is JSON and why would I use it?
What are the differences between JSON and JavaScript object?
Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.
So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.
You can see some examples here to figure out better: JSON example

Storing entire JSON object in PostgreSQL DB

I'm sending a JS object from my front-end to my Java backend, and I'm passing a object like so, which contains different types
wrapperObject = {
JSONOBJ = {
'key': 'value'
},
id: '123',
date: 'exampledate'
}
My java backend then takes this wrapperObject and converts every field inside into a value inside of a hashmap Map. Whenever it reaches the JSONObject, however, it parses it and attempts to insert into the db and I reach a
bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: No hstore extension installed.
What can I do about this, and is there a better way of approaching this?
It sounds like it may be as simple as adding the hstore extension. The PostgreSQL documentation for installation looks pretty straightforward:
Let me know if I'm missing something, hope this helps!

JSON response from Google Analytics api

I am using the google-api-ruby-client to get a response from the Google Analytics api, which is successful, the one thing I am a little confused with though is the response object. I would like to know how to drill down into specific keys and their values or even parse the response to make it more understandable.
Below is what I believe is the relevant part of the JSON response
"{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"query\":{\"start-date\":\"2014-01-01\",\"end-date\":\"2014-07-22\",\"ids\":\"ga:88893966\",\"dimensions\":\"ga:pagePath\",\"metrics\":[\"ga:pageviews\"],\"filters\":\"ga:pagePath==/\",\"start-index\":1,\"max-results\":1000},\"itemsPerPage\":1000,\"totalResults\":1,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"profileInfo\":{\"profileId\":\"88893966\",\"accountId\":\"53082810\",\"webPropertyId\":\"UA-53082810-1\",\"internalWebPropertyId\":\"85713348\",\"profileName\":\"All Web Site Data\",\"tableId\":\"ga:88893966\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:pagePath\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:pageviews\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:pageviews\":\"8\"},\"rows\":[[\"/\",\"8\"]]}"
which is obtained from
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
puts ap(result)
Also when I do:
puts ap(result.data.rows.inspect)
#returns
"[[\"/\", \"8\"]]"
and when i try
response = JSON.parse(result.data.totalsForAllResults)
puts ap(response)
# returns error
TypeError: no implicit conversion of #<Class:0x00000001950550> into String
I am wondering how I can format the response without the backslashes and how I would say get the total page views?
Your syntax is off.
If result is simply a string that is a json object, which it looks like above, what you want is:
response = JSON.parse(result)
ap response["totalsForAllResults"]["ga:pageviews"]
Looking at the google-api-ruby-client the result.data returns an object if parseable from api schema, a hash if you pass the media type "application/json", or a string otherwise. So you need to determine if you are accessing the response data as an object or a Hash. My example above parses the raw string into a ruby hash.
tl;dr; there are multiple ways to attain the data you want.
Yes, your syntax is off. It should look something like this.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:_____&dimensions=ga:date&metrics=ga:impressions,ga:adClicks,ga:adCost&start-date=2015-10-13&end-date=today
BaseUrl, id, metrics, start-date and end-date are required. And don't forget to insert the access_token as well.

How can I send foreign characters with YUI io (XMLHttpRequest)

I'm using YUI io to post data to my server. I have some problems sending foreign characters like æ ø å.
First case: a form is posted to the server
Y.io(url, {
method: 'POST',
form: {
id: 'myform',
useDisabled: true
}
});
This will post the content of the form to the server. If I have a field named "test1" containing "æøå", then on the server I'll see REQUEST_CONTENT="test1=%C3%A6%C3%B8%C3%A5". This can be easily decode with a urldecode function, NO PROBLEM, but...
Second case: data is posted this way:
Y.io(uri, {
data : '{"test1":"æøå"}'),
method : "POST"
});
Now I see this on the server REQUEST_CONTENT="{"test1":"├ª├©├Ñ"}". How can I decode that? And why is it send like that?
I know I can use encodeURIComponent() to encode the string before sending it. But the io request is actually part of a Model Sync operation, so I'm not calling io directly. I'm doing something like this:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {....});
var user = new Y.User();
user.set('test1', 'æøå');
user.save();
So it doesn't make sense to encode/decode everytime I set/read the attribute.
Also I have tried to set charset=utf-8 in the request header, but that didn't change anything.
EDIT
I have done some more debugging in chrome and the request is created with this line of code:
transaction.c.send(data);
transaction.c is the xmlhttprequest and (using chrome debugger) I can see the data is "{"test1":"æøå"}"
When the above line of code is executed, a pending network entry is shown (under the network tab in chrome debugger). Request payload displays {"test1":"├ª├©├Ñ"}
Headers are:
Accept:application/json
Content-Type:application/json; charset=UTF-8
ModelSync.REST has a serialize method that decides how the data in the model is turned into a string before passing it to Y.io. By default it uses JSON.stringify() which returns what you're seeing. You can decode it in the server using JSON. By your mention of urldecode I guess you're using PHP in the server. In that case you can use json_decode which will give you an associative array. If I'm not mistaken (I haven't used PHP in a while), it should go something like this:
$data = json_decode($HTTP_RAW_POST_DATA, true);
/*
array(1) {
["test1"] => "æøå"
}
*/
Another option would be for you to override the serialize method in your User model. serialize is a method used by ModelSync.REST to turn the data into a string before sending it through IO. You can replace it with a method that turns the data in the model into a regular query string using the querystring module:
Y.User = Y.Base.create('user', Y.Model, [Y.ModelSync.REST], {
serialize: function () {
return Y.QueryString.stringify(this.toJSON());
}
});
Finally, ModelSync.REST assumes you'll be using JSON so you need to delete the default header so that IO uses plain text. You should add this at some point in your code:
delete Y.ModelSync.REST.HTTP_HEADERS['Content-Type'];

How to default construct JavaScript object from JSON Schema?

I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);

Categories