json stringify, encode and decode - why? - javascript

i have some questions that I want to ask, I building a web site and I send in ajax data and do decode and decode (js to php).
1) I want to ask why we should use in ajax encode and decode on json ?
2) what the json stringify do? I do it like this:
var data = JSON.stringify([category, amount, repeated, note]);
but I not realy understand why I should use this..my freind told me its not secure to send ajax without json encode, is it true?

First, AJAX is not tied to JSON but is the most used. You could use XML, yaml or you own format. On other hand, you always have sanitize and validate any data sent by the user. This is the real security risk.
Second, if you use a library as jQuery or AngularJs, you do not need stringify a javascript object (it is not the same as a JSON) the library does this for you.
// jQuery example
$.ajax({
url: '/save.php',
method: 'post',
data: {
id: 5,
name: 'pollin14'
}
};
// Save.php
$id = $_POST['id'];
$name = $_POST['name'];
Lastly, stringily transforms a javascript object to a javascript string. It is useful if you want to save a javascript object in a cookie, for example. Because a cookie only can save strings. Then when you retrieve the cookie you can use JSON.parse to get a javascript object.

Related

Going mad over encoding bugs with JSON and the differences between JS and PHP

I have a real mess at my hands with encoding-related bugs.
I have a DB with latin1 (which is close to Windows-1252 I believe), a user frontend page in Windows-1252, and an AJAX backend in Windows-1252. These can't be changed atm.
Yet, because JSON expects UTF8 data, I'm running into tons of trouble with German Umlaute.
I'm currently retrieving some escaped example data from the DB on the frontend [{"\u00f6\u00e4\u00fc\u00df"}] and using
foreach($example_array_of_objects as $k => &$v) {
foreach($v as $k2 => $v2) {
$v[$k2] = utf8_decode($v2);
}
}
which results in correct display of the data in input form fields on the frontend.
However, this is where I'm stuck. PHP's json_encode escapes Umlaute to these \u sequences, but in Javascript, JSON.stringify just doesn't.
When I JSON.stringify the input field data and send it to the AJAX script, I get only garbage from a print_r response:
öäüß
encodeURIComponent doesn't do the same type of escaping as PHP does. This is infuriating.
How can I transform "öäüß" to \u00f6\u00e4\u00fc\u00df in JS (or how can I synchronize the way data is handled between JS/PHP/mySQL somehow)?
You can not really modify how JSON.stringify works - providing a replacer function as the 2nd argument will force you to manually encode values (unpleasant thing). Your best bet is to use UTF-8 in the frontend (JavaScript code) and convert from/to CP1252 only in your PHP code.
When sending data to the frontend you should use these flags
json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
which will ensure the cleanest possible UTF-8 output.
To populate your $array you should use mb_convert_encoding($original_data_from_DB, 'UTF-8', 'CP1252') and to get your data after json_decode you should use mb_convert_encoding($data_from_java_script, 'CP1252', 'UTF-8')
Faced this type of issue once but not with PHP and it was solved using encodeURIComponent. If encodeURIComponent is not working for you try using a Base64 encoding decoding on both the sides using atob and btoa.
I managed to do it by letting PHP handle the majority of it now:
JS sends to AJAX:
mydata = JSON.stringify(data);
AJAX Backend:
//decode JS way of JSON with additional slashes etc.
$tmp = json_decode(stripslashes(html_entity_decode($_POST['mydata'])), true);
//re-encode the PHP way
$json = json_encode($tmp);
//save to DB
[...]
User Frontend (Form):
//Retrieval from DB
$mydata = json_decode($db_row['mydata'], true);
//loop through, replace " with " for input fields, decode utf8
foreach($mydata as $k => &$v) {
foreach($v as $k2 => $v2) {
$v[$k2] = utf8_decode(preg_replace('~"~', '"', $v2));
}
}

json_decode expects parameter 1 to be string, says array is given. Why doesn't my string pass properly?

So, I've been struggling with this for the entire weekend and I still can't figure out what's wrong. I'm trying to pass some data through json_decode to be able to save it to a file and I keep getting the error it expects a string but an array is given. I'm using jQuery and PHP.
The data I send through the ajax call is, according to console.log(noBrack):
{"ID":2,"LLID":"LLID2","volNaam":"Test - 0","norm":"Zicht","instalDatum":"17-11-2017","endDate":"18-11-2017","serie":"0","klant":"Testklant","file":"data/Testklant (Heerenveen)/LLID2.json","gelDat":"27-10-2018"}
My Ajax call is:
$.ajax({
url: 'quickGrade.php',
type: 'POST',
data: noBrack,
datatype: 'json',
success:function(data){
alert(data );
}
});
My PHP code is:
$testSave = 'data/gradeTest.json';
$decode = json_decode($_POST, true);
file_put_contents($testSave, $decode);
Can anyone find out what I'm doing wrong? I've tested my string with an online json_decode tester and it said it was valid so I'm kinda hardstuck here.
The way you are sending data will give you $_POST array in php code. So actually you do not need to decode because the data is coming as $_POST array not a JSON string.
You should use json_encode to get JSON string to store in file. Because $_POST is an array, so you can't decode it like a Json string.
Your code will become this:
$testSave = 'data/gradeTest.json';
file_put_contents($testSave, json_encode($_POST));
You can read more about:
http://php.net/manual/en/function.json-encode.php
http://php.net/manual/en/function.json-decode.php

How to post and get javascript document into Database

I've a web page in which i've inserted a ACE- javascript Code Editor. I want to post javascript code into my database and then retrieve.
for example in case of JSON we use json.stringify and json.parse to post and retrieve data. I'm usieng SAPUI5 backend is in javascript.
var conf = model.getProperty("/automation-rule-body");
Is there any rule to post javascript code into database ?
If your backend supports REST API use create method of sap.ui.model.odata.ODataModel
var oDataModel = sap.ui.model.odata.ODataModel(sServiceUrl, mParameters);
oDataModel.create(sPath, oData, mParameters);

Store Javascript object in $_SESSION by Ajax. Array vs JSON string

I'm sending an Ajax request which sends an object objectVariable to a PHP file:
$.post(url, {action : 'function' , object : objectVariable });
Then, the PHP file will store objectVariable in $_SESSION['objectVariable'] (I'm omitting validation to make it clear):
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = $_POST['objectVariable'];
}
When the user goes to other page of the site, the $_SESSION['objectVariable'] will be sent from PHP to the user by Ajax again.
Here, I should encode the array stored in $_SESSION['objectVariable'] to a JSON string:
//inside other Axax callback function
echo json_encode($_SESSION['objectVariable']);
That's working right, but I also could store a JSON string into $_SESSION['objectVariable']:
function function_callback() {
if(!session_id())
session_start();
$_SESSION['objectVariable'] = json_encode($_POST['objectVariable']);
}
And after, just echo $_SESSION['objectVariable'] to send it to the Javascript file.
I wonder what would be a better way: store an array in $_SESSION['objectVariable'], or store a JSON string.
Any suggestion about it?
When sending data between Javascript/PHP I always keep it encoded as a JSON string. It makes things simpler. In fact, I would just JSON.stringify() it right away when you send it to the server the 1st time.
This way you also will always know what type the data will be.

Encode string javascript so that it can be transmitted to a server

I'm trying to send json string in the get request to the server, here is how it looks before encoding :
filters={"groupOp":"AND","rules":[{"field":"countrycode","op":"eq","data":"ARG"}]}
Naturally I end up with null pointer when trying to get this json string, then I googled this encodeURIComponent and it partially encodes this string like this :
filters={"groupOp"%3A"AND"%2C"rules"%3A[{"field"%3A"countrycode"%2C"op"%3A"eq"%2C"data"%3A"ARG"}]}
But this is how it supposed to be in order to work :
filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22countrycode%22%2C%22op%22%3A%22eq%22%2C%22data%22%3A%22ARG%22%7D%5D%7D
How do I get this, entirely encoded string so I can read it at server side properly ?
Reason why I used get instead of post
I'm sending this filter(json) content to the server side, web service gets data from the database and returns pdf document.
Using post, I'm able to send correct data and the response is successfully displayed in my firebug console. But I need to return pdf doc to override the current page or open new window/tab and return in that one.
I think you're overworking this problem. Or encoding too many times. Or something.
You've got a JSON string, and you are trying to JSON encode it. That seems...unhelpful.
A better approach might be to produce a Javascript object, then JSON.Stringify that, and then transmit it as a parameter.
var thing = {
groupOp : "AND",
rules : [
{ field : "countrycode", op : "eq", data : "ARG" },
...
],
...
};
var stringrep = JSON.stringify(thing);
// post via jQuery
$.ajax({
type: 'POST',
url: url,
data: stringrep,
dataType: 'json'
success: function() { ... },
});
Normally for a JSON stringified message to or from the server, you'd want to use HTTP POST. HTTP GET puts all "parameters" in the URL; there is no message body. In contrast, HTTP POST allows you to attach a message body to the HTTP message, which can be "anything". With that approach, you don't need to url-encode the quotes and spaces; the JSON message just gets transmitted as the message body of the HTTP message.
HTTP POST is the way applications upload images, or transmit XML documents, and so on. Anything complex gets transmitted via POST.
var filtersParameter = 'filters=' + encodeURI(JSON.stringify(filters));
var filtersParameter = 'filters=' + atob(JSON.stringify(filters));
Note: atob() method uses base64 algorithm to encode the data. This encoded data can be easily passed to a server where it can be decoded using corresponding decoding methods (in python base64.b64decode(encoded_string) is used).

Categories

Resources