Fitting json data in a single query string variable - javascript

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.

Related

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

passing integer into url as parameter php/javascript

i want to save my website from url injection for that purpose i am using the following line to call another page with an integer id as an parameter here's the code
'<button onclick=window.location.href="admin_leadbox2.php?id=' + alert(typeof(parseInt(data[i].client_id))) + '">VIEW DETAILS</button>';
the alert is showing me that infact the data being passed in the url is a number
now when i get the id from the url and check its type in php it is giving me an string here's the php code
$id=$_REQUEST["id"];
echo "<script>console.log('".gettype($id)."')</script>";
i know that i can convert the string received in the url into integer like i did in javascript to do my work but for my case to prevent url injection i only want to receive an integer type data! what is the problem? thanks in advance
A URL is a string. A URL, or query parameters within it, has no types. Here, this is what your URL looks like:
admin_leadbox2.php?id=42
This is all the information that the computer has too. There's no hidden flag to mark "42" as an integer. It's just the characters 4 and 2. In a string. No different from "42foo", which would quite obviously be a string.

Converting data into JSON

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()+'"}}';

converting Google Visualization Query result into javascript array

The url to the spreadsheet I am querying is
docs.google.com/spreadsheets/d/1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y/edit?usp=sharing
The query url being used is
https://spreadsheets.google.com/tq?tqx=out:&key=1EIBhBQY1zbdBEKXsJIY1uyvdQw0b1cIBSrBE_tZvA6Y&gid=0&headers=1&tq=select%20B%2CC%2CD%20where%20(A%20matches%20%22DIS%22)
Is there a way to convert or store this result in a JavaScript array?
var dis = ["The Walt Disney Company","Entertainment",.1]
I need to be able to manipulate the data at one point and add the new data to the visualization.
Data from one of multiple queries --> Convert to array --> Manipulate data ex: multiplying an input --> data.addRows(manipulated input);
Your query does return a string containing JSON wrapped in a function call:
var responseText = 'google.visualization.Query.setResponse({…});';
This is because you specified out: as an argument for tqx (see Google Developers guides).
If you want it all raw, you can extract and parse the JSON of multiple queries and push the data to an array, so you end up with an array of arrays of row data. For your single query, you could start from something like this:
responseJSON = JSON.parse(
responseText.replace(/(^google\.visualization\.Query\.setResponse\(|\);$)/g,'')
);
var rowsArray = [];
responseJSON.table.rows.forEach(function(row){
var rowArray = [];
row.c.forEach(function(prop){ rowArray.push(prop.v); });
rowsArray.push(rowArray);
});
console.log(rowsArray); // === [["The Walt Disney Company", "Entertainment", 0.1]]
There is a more straightforward solution to this. What you get in the response is a JSONP string whose data is hold within a callback function, just as #dakab has mentioned.
Besides this, recently Google has included some extra text in the response to help with some anti-content-sniffing protections to their API. You can read more about this in this Github thread. The response you get now is an unparseable string in this form:
/*O_o*/
google.visualization.Query.setResponse({…});
One way to deal with both issues (the "comment" string and the data hidden inside the callback function) is to evaluate the function. Whether this is risky or not is something intrinsic to the JSONP format, so you must be aware of where your response comes from and decide if it's worth the risk. But, considering it comes from a request to a Google server, and in terms of parsing, it works.
So in your case, what you could do is just declare the callback function (note that you can pass your own function name in the query string, as also mentioned in the Google Developers guides) and then evaluate it. I take inspiration on this thread:
//Declare your call back function
function callback(data){
return data;
}
//Evaluate and store the data in your callback function
var result = eval(UrlFetchApp.fetch(url + uri, options).getContentText());
In "result" you'll have an already parsed JSON that you can convert to whatever you wish.
According to Google's documentation on their Visualization API for response formats, you can add a header in your request that will return JSON without the function or comment.
If you add a header named X-DataSource-Auth in your request, the Visualization API will respond in JSON format rather than JSONP format, which is the default format of the response and includes the JSON wrapped in a function handler.
However, even with this header present, the API prepends a strange string to the response: )]}' which I think has to do with the anti-content-sniffing mentioned by #Diego. Okay, Google — even with an OAuth token do you really need to do that?
So, to get at the actual JSON in that response, you can use the following Javascript to get around it. Assume responseBody is what the API actually returns to you, and that data is storing the JSON you want.
var data = JSON.parse(responseBody.replace(/^\)]\}'\n/, ''));
Assuming str is the returned JSONP formatted response:
var str = `/*O_o*/
google.visualization.Query.setResponse({"version":"0.6","reqId":"0","status":"ok","sig":"403123069","table":{"cols":[{"id":"A","label":"Timestamp","type":"datetime","pattern":"dd/MM/yyyy HH:mm:ss"},{"id":"B","label":"AskGod Search Query","type":"string"}],"rows":[{"c":[{"v":"Date(2020,9,25,12,30,5)","f":"25/10/2020 12:30:05"},{"v":"لا أعرف لماذا"}]}],"parsedNumHeaders":1}});`
console.log(JSON.parse(str.match(/(?<=.*\().*(?=\);)/s)[0]))

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))

Categories