Get JSON data stored in a hidden input element? - php

I'm building a website that store json data to hidden input element with php
<input type='hidden' class='json_data' name='json_data' value='".json_encode($data[0])."'>
with that code, I have this result:
<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">
but when I try to get the value with jquery.val and trying to show ALBUM_ID, i get this {
anything wrong with my way of putting json into html correctly?
and then get it with jquery / javascript ?
thanks

First go ahead at this open console and see the result. Ctl+Shift+j.
http://jsfiddle.net/techsin/Q2MHA/
You need to do two things fix. ' and "'
Second just this code
JSON.parse($('.json_data').val())[0]
you need [0] because for some reason your json object is wrapped in []..you would know why.
Your html should look like this
<input ... value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]'...>

You need to correctly handle entities in your input's value. If you populate it with PHP, use htmlspechalchars() and use result from this function

inspect the following line carefully.
<input class="json_data" type="hidden" value="[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]" name="json_data">
As you see you have used " for your string enclosement. The json string also includes " which breaks your string enclosement. Use ' to enclose the string.
<input class="json_data" type="hidden" value='[{"ALBUM_ID":"1234","PHOTOS_ID":"1234578"}]' name="json_data">

Try to escape the " with addslashes or htmlspecialchars
or encode the string with base64 and decode it with JS before parsing the string as JSON

Related

Prevent html entity conversion php

I have a form with a url input that I need to prevent from converting, so that I can use $_GET on the target page. I have tried urlencode, urldecode, html_entity_decode, etc, but none of it prevents the html entity conversion (parse_url did nothing but get rid of all the important stuff). This is the only thread I have found that comes close to what I am trying to achieve.
It seems like there should be a simple solution, and this is not happening anywhere else I am using a url like this...
Thanks to anyone who can help!
echo "<option value='seeArtist.php?aid=".$row[0]."&ac=".$row[1]."&img=".$row[2]."'">
(blah, blah)
<input type="submit" style="margin-left:10px" name="submit" value="Go" />';
This is the result from clicking the submit button.
seeArtist.php?art_con=seeArtist.php%3Faid%3D18%26not%3Bac%3D+(aka)+Banksy%26not%3Bimg%3D0&submit=Go
Two variables are integers, so the database content is not url-encoded.
I suspect that since this is not happening anywhere else, and this is the only place where I am putting a link in a select option, that it has something to do with the submit action. In firebug the link shows up exactly the way it is supposed to. When I submit the url gets encoded.
Regardless of the PHP, your HTML is incorrect. You need to encode the ampersands. Your code should resemble this:
echo "<option value=\"seeArtist.php?aid=" . $row[0] . "&ac=" . $row[1] . "&img=" . $row[2] . "\">\r\n";
I also took the liberty of converting single-quotes to escaped double-quotes.

JSON string with some html tag failing at parse

I am taking user input sending it to server using jQuery ajax...after inserting user values in database I am sending response back to client as JSON string as following
echo '{"success":"true","data":"'.nl2br($a).'","type":"text"}';
as user input can contain new line, I am using nl2br so that all new line characters are converted to <br> and also know that JSON doesnt support multi line, thats why I am using nl2br....but parsing is failing at client side
pls tell me what the reason and how can I solve it?
parsing code var obj = jQuery.parseJSON(data);
You should be using json_encode, wich will generate a JSON string that contains \r\n for line breaks. Then you will have to replace each \r\n occurences by <br> tags.
echo str_replace('\r\n','<br>', json_encode(array("success"=>"true","data"=>$a,"type"=>"text")));
echo json_encode(array("success"=>"true","data"=>$a,"type"=>"text")
Use the php function json_encode rather then trying to set the encoding yourself. You'll save yourself a lot of trouble that way. http://php.net/manual/en/function.json-encode.php
nl2br() does not replace the line breaks, only inserts <br> before them.
As such, \n is being returned and therefore creating invalid JSON.
You should use json_encode() when creating JSON strings. For simplicity, you could simply use it on data:
echo '{"success":"true","data":' . json_encode(nl2br($a)) . ',"type":"text"}';

JSON array to PHP / MySQL JSON.parse JSON.stringify how to store double quotes and single quotes

I have a form with fields and a text-area that allows any characters to be entered. I can't just submit the form, because the form is being recycled many times over, so the form values are being stored in associative arrays:
<form name='Theform'>
<input type="text" id="VISITOR_DETAILS_NAME" value="Joe">
<input type="text" id="VISITOR_DETAILS_SIZE" value="Large">
<textarea id='VISITOR_DETAILS_INFO'>
User can enter anything here including double " and single ' quotes
</textarea>
<input type="hidden" name="package" id="package" value="" />
</form>
The text-area value are stored in a JavaScript array along with the other form values:
myArray[0]['VISITOR_DETAILS_NAME'] = document.getElementById('VISITOR_DETAILS_NAME').value;
myArray[0]['VISITOR_DETAILS_SIZE'] = document.getElementById('VISITOR_DETAILS_SIZE').value;
myArray[0]['VISITOR_DETAILS_INFO'] = document.getElementById('VISITOR_DETAILS_INFO').value;
I end up with an array something like this:
{
VISITOR_DETAILS_NAME : "Joe",
VISITOR_DETAILS_SIZE : "Large",
VISITOR_DETAILS_INFO : "User can enter anything here including double " and single ' quotes"
};
I then pass this JavaScript array to the hidden form field using JSON.stringify and then POST this to PHP:
document.getElementById('package').value = JSON.stringify(myArray[0]);
Theform.submit();
(For now I'm just posting to an iframe to test that the JSON is passing the JavaScript arrays properly through POST).
When I get it on the PHP side - it seems good to go. It looks like the JSON.stringify has added the backslash to the double quote (\" ) - and now I want to store the values in MySQL. But I want to first test that I can send/reconstruct the JSON back to the javascript as an array - so I try this:
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
I get an ERROR: SyntaxError: Expected token ')' OR SyntaxError: missing ) after argument list
This is strange to me - because when I try it without POSTING - It seems to work fine like this:
document.getElementById('package').value = JSON.stringify(myArray[0]);
now if I try to just pass back the stringified value back to the array
myArray[0] = JSON.parse(document.getElementById('package').value);
- it seems to work fine - no errors
QUESTIONS:
Why am I getting this error when trying to reconstruct the ARRAY from the
POSTED JSON.stringify() value?
Do I save this JSON.stringify() value in MySQL as is?
Or do I PHP json_decode() it first?
I want to grab the form data - handle it properly - store it in MySQL and then read it back into the form when I need it.
Thanks All :)
parent.myArray[0] = JSON.parse('<?php echo $_POST['package']; ?>');
Here you are are trying to convert a JSON text into an HTML representation of a JavaScript string representation of a JSON text, but you aren't doing anything to escape it for either.
If you have any ' characters in the JSON data, then they will terminate the JavaScript string.
If you have any " characters in the JSON data, then they will be represented as \", but \" is a JavaScript string representation of ". Since you don't do anything to escape the text you put in the JS string, the slash character will be consumed by the JavaScript parser and will be gone before it reached the JSON parser.
If you want to convert data for placing in a JavaScript string then you need to escape it.
However, JSON is a subset (almost) of JavaScript. So the process of converting a JSON text to a JavaScript string so it can be parsed into a JavaScript object is over-complicated. You can skip that can just go straight to:
<script>
var foo = <?php echo $json; ?>
</script>
However, since you are taking in the JSON from the client, echoing out directly will expose you to XSS attacks. In order to deal with this you should filter the data on the server.
This will:
Fail to parse any invalid JSON and so not output bad JSON (but it might output nothing, giving you a JSON syntax error, you should apply tests to see if the parse was successful and output a sensible default case if it fails).
Convert any </script> in the data to <\/script> making it safe to place in a script element (because that is how PHP's json_encode works
Such:
<!-- I don't do PHP, this is untested -->
<script>
var foo = <?php
$unsafe_json = $_POST['package'];
$data_structure = json_parse($unsafe_json);
$safe_json = json_encode($data_structure);
echo $safe_json;
?>;
</script>
Do I save this JSON.stringify() value in MySQL as is? Or do I PHP json_decode() it first?
That depends on what you intend to do with the data. In general when putting things into a database it is a good idea to extra the data from the data format and normalize it. That way you can run queries over it.
If you are only going to store the data and then retrieve it, you might be able to get away with not doing that and storing strings of JSON in the database. That loses you a lot of flexibility though and might bite you in the future.

how to decode something that is encoded with encodeUri()

If you encode something using javascript's encodeURI() method, how do yo get the decoded string in PHP?
I have string name= "salman mahmood" which I'm sending via POST message to my server. When I alert() the string at client side it gives me "salman%20mahmood" after encoding.
At server side I'm decoding it using urldecode() but the result I'm getting is "salman". Do I need a different method to decode? the rawurldecode isnt working either; I just need the value with the space restored back.
Edit: thanks every one for the suggestions but im writing the code as follows and it still doesnt work!!
<input type="text" id="chapterNumber" value=<?php echo rawurldecode("chapter%20Two"); ?> disabled="disabled">
it only prints "chapter"
Put it into quotes ' '
<input type="text" id="chapterNumber" value='<?php echo rawurldecode("chapter%20Two"); ?>'disabled="disabled">

PHP pass a string containing quotations via GET

I am trying to pass a string that already contains quotation marks from one php file to another via a hyperlink and the GET method.
I am retrieving thousands of lines which contain quotation marks in a while loop and saving the output to a variable as follows:
while ($trouble_row = mysql_fetch_array($trouble_result)) {
$ticketid = $trouble_row['ticketid'];
$ticketno = $trouble_row['ticket_no'];
$created = $trouble_row['createdtime'];
$modified = $trouble_row['modifiedtime'];
$title = $trouble_row['title'];
$solution = $trouble_row['solution'];
$hoursattended = $trouble_row['cf_629'];
$hoursbilled = $trouble_row['cf_628'];
$csv .= "$firstname $lastname,$ticketno,$created,$modified,$hoursattended,$hoursbilled,$title,$solution\n";
}
The variable $title sometimes contains an entry that looks like this:
The user "tom" is having problems.
The variable $csv is collecting all the results from each pass and creating a CSV formatted string that I then need to pass to a new php script, which I am trying to do using a hyperlink:
a href="export_csv.php?csv=$csv">Export to CSV</a>
Unfortunately the embedded quotation marks are recognized by the hyperlink and cut off the majority of the output. Any suggestions on how to collect the data differently, store it differently, or pass it differently would be greatly appreciated!
For parameters in links, you need to use urlencode():
echo 'Export to CSV';
note however that GET requests have length limits starting in the 1-2k area (depending on browser and server).
Alternative approaches:
Forms
One method that is immune to length limits is creating a <form> element for each link with method="post" and adding the values in <input type='hidden'> inputs. You would then style the submit button of the form like a link.
<form action="export_csv.php" method="post">
<input type="hidden" name="csv" value=".......">
<button type="submit">Click here </button> <!-- Use CSS to style -->
</form>
Sessions
Another very elegant way to pass the data would be
Generating a random key
Saving the CSV data in a $_SESSION variable with the random key
Passing the random (short) key in the URL instead of the full data
You'd just have to take care of deleting unused random keys (and their data) frequently.
These kinds of links couldn't be bookmarked, of course.
Use urlencode() before creating the hyperlink url, and use urldecode() to get the original string.
use urlencode() for embedding into a link, and html_special_chars() for embedding into form fields.
url_encode and url_decode.
Quickest and easiest solution given what you already have is probably to change this:
Export to CSV
To something like this:
Export to CSV

Categories