Converting data into JSON - javascript

I have a node server. It takes ajax calls and uses the data in this format.
{"action":"login","data":{"uname":"fas4","password":"jaltheband"}}
I am using a local ajax call and converting my username and password in this format but when I console.log req.body, it shows me a strange format. This is how I am converting data in JSON.
var data = '{"action":"login","data":{"uname":"'+$("#username").val()+'","password","'+$("#password").val()+'"}}';
And then I console.log(req.body), this is displayed.
The formats are different. Why is that so?

After the "password" key, a double quote followed by colon is missing and the comma is misplaced, try this -
var data = '{"action":"login","data":{"uname":"'+$("#username").val()+'","password":"'+$("#password").val()+'"}}';

Related

Fitting json data in a single query string variable

I am writing a web application to exchange contact information fast via QR.
I use a QR api wich is formatted like this:
`http://api.qrserver.com/v1/create-qr-code/?data=MyData&size=400x400`
I have json data formatted in a string, example of output:
`http://[myapp-url]/RecieveContact.html?Name=John%20Diggle&Title=IT%20Consultant&Organisation=testcomp&Telwork=0498553311&Telhome=&Gsm=0498553311&Email=testemail#mail.be&Website=www.testwebsite.be&Birthdate=24/04/97&Addresswork=&Addresshome=`
JSON data:
{"Name":"John Diggle",
"Title":"IT Consultant",
"Organisation":"testcomp",
"Telwork":"0498818587",
"Telhome":"",
"Gsm":"0498818587",
"Email":"testemail#mail.be",
"Website":"www.testwebsite.be",
"Birthdate":"24/04/97",
"Addresswork":"",
"Addresshome":""}
The problem is when you put this url in the QR generator it only recognises the Name parameter. I understand why this happens.
The question is is there a way using javascript to convert all this data in a string and convert it back on the recieving end?
Or does anyone know another potential fix for this problem?
You need to URL encode data with special characters you put into a URL:
var url = 'http://[myapp-url]/RecieveContact.html?Name=John%20Diggle&Title=IT%20Consultant&Organisation=testcomp&Telwork=0498553311&Telhome=&Gsm=0498553311&Email=testemail#mail.be&Website=www.testwebsite.be&Birthdate=24/04/97&Addresswork=&Addresshome=';
var query = 'http://.../?data=' + encodeURIComponent(url) + '&size=400x400';
This way you can represent characters like & inside a query string.

Posting data using javascript with ODATA format

I'm facing an issue when converting ODATA string into JSON while posting on my Dynamics CRM.
When I'm trying to serialize that way:
var phoneCallAssociationJsonData = '{'
+'"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls('+ phoneCallUid +')"'
+'}';
And serialize it in the request like that: JSON.stringify(phoneCallAssociationJsonData);
I get a BAD REQUEST response. But When I use POSTMAN to post data and I copy the following JSON:
{"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls(12a59ec0-76b5-e611-80ed-5065f38a8ad1)"}
It works perfectly.
Does someone know if there is a special way way to serialize string with odata format ?
I've tried to create a javascript object but adding a object.#odata.id is not possible because # is not an allowed character.
Firstly, rather than creating a string, which you then stringify, create an OBJECT
var phoneCallAssociationJsonData = {
"#odata.id" : "https://contoso.crm4.dynamics.com/api/data/v8.1/phonecalls("+ phoneCallUid +")"
};
then
JSON.stringify(phoneCallAssociationJsonData);
should now work

JSON stringify adds quotes "" in the float type data

I am parsing a float data from my controller to a js function via JSON, following is the JS function:
function fetchbal(){
$.ajax({
url: "/count/ew",
dataType: "json"
}).success(function(data){
$('#bal').html(JSON.stringify(data.sum));
});
}
but I am getting an output with quotes around the figure.
I have checked the value returned by the controller, and it is not passing the quotes, so it has to do something with JSON stringify!
for cross checking this is the controller(Symfony):
$repo = $em->getRepository('SystemBundle:Admin');
$user = $repo->findOneBy(array('id'=>$session->get('id')));
$sum = $user->getWallet();
return new JsonResponse(array('sum'=>$sum));
here $sum is fetching a float val from the db (doctrine)
I have also tried this post's solution but it instead stops displaying the value on the page
I don't want quotes to be displayed around the fetched value, any suggestion for that? also ask for more elaboration if you want.
Json stringify adds the quotes, since it's intended to serialize data before sending them to server.
You probably want to invoke json.parse, or even just do nothing, as jquery will parse the json for you.

Sending special characters in Ajax POST and JSON

#SOLVED
As explained by James M. Lay, I should change my content-type from application/x-www-form-urlencoded to application/json
it implied in an error because it seems that only UrlEnconded types generates POST arrays in server side (at least in PHP). So I had to change the way I receive/deal with the request in my server script
$json = file_get_contents('php://input'); //yes. php://input
if($json) $params = json_decode($json,true);
else $params = $_POST;
I also had to make a few changes in the Javascript code to check the content-type and generate different strings. If it's JSON I just use JSON.stringify
//string to use in the 'send' method
this.getParametersString = function(){
if(this.contentType == 'application/json'){
return JSON.stringify(this.parameters);
}else{}
}
I got a question
I`m building a function that receive parameters to write a list of parameters and send it by POST
The problem is that we can't send special characters, such is +
So I tried to use the function encodeURIComponent to encode them to a URI friendly string.
There comes another problem: if the parameter received is an object, I am loop through the attributes, checking if it is another object or a string, if it is an object, loop again, otherwise encode it.
But it is returning an object of encoded strings. I have to make the object become a string to send it, and for that purpose I use JSON.stringify. It decodes the encoded string. So %2B becomes + again and It is not sent to the server via POST.
on the other hand If I use stringify first and the encodeURIComponent it generates signs like " and { } that shouldn't be encoded and the string is not a well written JSON
How do you that? Is that a way without using jQuery? Do I have to build my own stringify function?!
im using the following and i have no issues
encodeURIComponent(JSON.stringify(object_to_be_serialised))

Json AJAX not working , problem in Response?

I have a servlet application that takes the user input from HTML form , extracts the required data from backend and makes graphs/charts and shows them to user.
The problem I am seeing is that if user selects first option from dropdown, everything works fine, the data is extracted from backend - I can see it in the AJAX response in firebug and then its parsed by json and then maps are created.
The data that is received from backend is (what I see in AJAX response):
{"responseStr":"[47.636597,-122.189495,0,1,47.643647,-122.212038,0,26,47.505288,-122.339112,0,1,47.622741,-122.314592,0,60,47.541612,-122.129318,0,1,47.568435,-122.161237,0,166,47.682308,-122.196004,0,2,47.666673,-122.284099,0,1,47.612953,-122.316700,0,2,47.600605,-122.322286,0,30,47.589557,-122.315608,0,27,47.636351,-122.327213,0,1,47.630270,-122.177084,2,0,47.630432,-122.140126,17,0,47.621644,-122.132080,1,3,47.630808,-122.153539,86,75,47.622367,-122.337023,495,3466,47.630886,-122.306255,1423,45,47.720287,-122.090885,255,82,47.702376,-122.093340,47,4,47.676897,-122.318752,1,0,47.760994,-122.322550,1,2,47.588854,-122.221273,1,0,39.530179,-119.818395,1,1,47.631306,-122.342762,1,0,47.737242,-122.323710,1,0,47.747054,-122.305083,2,0,47.752018,-122.316452,1,0]"}
This is then parsed in json via
function Respond(REQ){
var res = JSON.parse(REQ.responseText);
var myArr = JSON.parse(res.responseStr);
//forward myArr for processing
}
Now when the same user selects option 2, all works fine, the data is extracted from backend and I can see the following in the response
{"responseStr":"[00:00:00-01:00:00,100,30,0,01:00:00-02:00:00,100,29,0,02:00:00-03:00:00,100,34,0,03:00:00-04:00:00,100,5,0,04:00:00-05:00:00,100,7,0,05:00:00-06:00:00,100,23,0,06:00:00-07:00:00,78,29,0,07:00:00-08:00:00,48,17,0,08:00:00-09:00:00,24,35,0,09:00:00-10:00:00,18,29,0,10:00:00-11:00:00,5,28,0,11:00:00-12:00:00,45,57,0,12:00:00-13:00:00,65,69,0,13:00:00-14:00:00,64,58,0,14:00:00-15:00:00,73,46,0,15:00:00-16:00:00,72,27,0,16:00:00-17:00:00,94,9,0,17:00:00-18:00:00,69,15,0,18:00:00-19:00:00,14,9,0,19:00:00-20:00:00,25,13,0,20:00:00-21:00:00,81,38,0,21:00:00-22:00:00,53,74,0,22:00:00-23:00:00,76,55,0,23:00:00-24:00:00,89,16,0]"}
but when it comes to parse this via
function Respond(REQ){
var res = JSON.parse(REQ.responseText);
var myArr = JSON.parse(res.responseStr);
//forward myArr for processing
}
something wrong happens at line 2 of the function and hence user does not see a chart.
If I were to put alerts in Respond function,
function Respond(REQ){
var res = JSON.parse(REQ.responseText);
alert('here');
var myArr = JSON.parse(res.responseStr);
alert('here2');
//forward myArr for processing
}
then I do see first alert, but not the second. However, for the first case, i see both the alerts. So there is definitely something wrong on line 2. Can someone identify this by looking at the AJAX reponse?
It's looking like this is a problem on the server side, not on the Javascript side. When JSON.parse() tries to crunch the value of responseStr, it looks at the first value in the array, which is 00:00:00-01:00:00. As this not in quotes, it's not a valid string, nor is it a valid number, and so JSON.parse is failing. (In the first example, every response value is a valid floating-point number, which is why it works.)
Also, you're currently parsing JSON twice, once as part of the jQuery ajax request, and again with the the string contained in that object. Though there's nothing inherently wrong with that, it is slower and can create bugs. You should be able to encode everything into a single JSON string on the server side, and then just use the object directly in your Javascript.
Allrit, so in order to make the above a valid string, each of the 00:00:00-01:00:00 (similar ) strings should be enclosed in double quotes. So at a place in my servlet that was fetching this data from database, earlier I was doing
resultSet.getString(1);
now I changed it to
"\"" + resultSet.getString(1)+ "\"";
and it works.

Categories