How to add text to JSON with PHP [duplicate] - javascript

This question already has an answer here:
Print JSON with PHP, without making multiple roots and making it pretty
(1 answer)
Closed 5 years ago.
My website takes in text messages as input, and I want to store these messages in "messages.json" on the server. Every time somebody enters a new message, I simply want to append messages.json with one more entry.
As of now, I can get the user's message ($message) properly sent to "save-message.php", but I couldn't find a way to properly add that $message string into messages.json in the correct format. One issue I was running into when experimenting with json_encode($message) was I could add the elements themselves to the file, but not inside the outer JSON brackets and with a comma after all them except the last one, etc.
Note: If solution requires a call to a JavaScript function, could you show how to adjust the HTML form and the PHP code accordingly to?
Here is my HTML form I am using:
<form action="/save-message.php" method="POST">
<textarea name="message" placeholder="Enter your anonymous message here!"></textarea>
<input id="submitNoteButton" type="submit" value="Submit mystery note"/>
</form>
</div>
Current save-message.php that can properly save strings to a .txt file:
<?php
$file = 'messages.txt';
$message = $_POST['message'];
file_put_contents($file, $message, FILE_APPEND | LOCK_EX);
header('Location: /note_submitted.html'); // Redirect
?>
Goal JSON:
{"messages": [
{"message":"This is what somebody would enter"},
{"message":"This is what somebody else would enter"}
]}

One way to do it would be to decode the existing JSON string into a PHP array and add the new message(s) to it. Then just encode it again and overwrite the existing file:
<?php
// Used as an example. Replace with file_get_contents();
$json = '{"messages": [ {"message":"This is what somebody would enter"}, {"message":"This is what somebody else would enter"} ]}';
// Decode the json string to a PHP array
$decode = json_decode($json, true);
// Push the new data to the array. Used an example here
// Just replace "This is a test" with $_POST['message'];
array_push($decode['messages'], array("message" => "This is a test"));
// To see the result as an array, use this:
echo "<pre>";
print_r($decode);
echo "</pre>";
// Encode the array back to a JSON string
$encode = json_encode($decode);
// To see the result, use this:
echo $encode;
// Put it back in the file:
file_put_contents("messages.json", $encode, LOCK_EX);
?>

Related

Passing PHP array to Javascript w/o showing up in source

I'm working on a historical database with 2,000+ photos that need to be categorized of which about 250 are loaded. I've created a MYSQL database with 26 fields to hold this data.
I'm using PHP to access the database and retrieve the information.
I'd like to use JavaScript to manage the rest of the form. All of the code is in one php file.
The problem I'm running into is when I
//$result is the php associative array holding the photo information
<div id="dom-target" style="display: none;">
<?php echo json_encode($result); ?>
</div>
<script>
var div =document.getElementById("dom-target");
var photo_array = JSON.parse(div.textContent);
It works but, I get the entire database structure and data embedded in the source html output. Obviously this won't do especially as the photo count increases.
How can I prevent this?
If I were to split this one php file into two, one containing php accessing the database and returning an array, and the other page containing all of the input boxes etc., and use AJAX passing the array as a JSON; would that work? I'd hate to go down that path unless it'll be successful. I've read where you can't pass the array if all of the code is on one page.
Or, should I just stick with doing everything in php?
Thanks, Eric
Edit: What I want to do is to pass a php array to js without having all of the data in the array included in the source. By source I mean when someone "views source". I also think that once I get up to 2,000 photos is is going to be unwieldy....(2,000 photos) x (26 fields) = a lot of stuff needlessly included in the web page.
I have no objection to using AJAX. But all of the examples I've seen have the request on one page and the response on another. Do I need to split up my code onto two pages; one to handle the php and MySQL and the other to handle the html and js?
What I envision is a screen showing the selected photo at 800x600 with the input fields below that. A person enters the title, caption, description etc and that is saved in the db with the photo's name. Below that I would have 20 thumbnail photos which a person could pick from to enter that photo's information. I would loop through the database 20 or so, photos at a time. Only the file names are stored in the database, the actual photo jpg is stored on a hard disk and retrieved via an statement.
How can I do this without all of the data in the database array being on the html source page?
Edit 2: I've been asked to include more of my php. Sorry I couldn't make it neater.
<?php
$stmt_select->bind_result(
$select_array['fhs_pkey'],
$select_array['file_name'],
$select_array['caption'],
$select_array'post'],
$select_array['photo_type'],
$select_array['last_name'],
$select_array['first_name'],
$select_array['middle_name'],
$select_array['honorific'],
etc., etc., etc
);
// put all of the database info into an array. Filename field is for full size photos
$j=$stmt_select->num_rows;
for ($i=0;$i<$j;$i++)
{
$stmt_select->data_seek($i);
$row = $stmt_select->fetch();
//put all of the column data into the array
foreach ($select_array as $key=>$value)
$result[$i][$key]=$value;
//in a separate php file resize the photos and save them
//put full path with appended filename to retrieve later
$result[$i]['resized'] =
"../images/fhs_images/800x600_photos/800x600--" .
$result[$i]['file_name'] ;
$result[$i]['thumb'] = "../images/fhs_images/200x150_photos/200x150--" .
$result[$i]['file_name'] ;
}
$stmt_select->close();
$stmt_update->close();
$stmt = null;
$conn = null;
echo '<figure id="photo_figure">';
$filename = $result[2]['resized'];
echo "<img src = "."'".$filename."'" ."/>";
?>
<script>
//below is where I get the entire array printed out when I view source
var photo_array = <?php echo json_encode($result); ?>
var testing = photo_array[40]['thumb'];
//take care of spaces in filenames
testing = encodeURI(testing)
document.write('<img src=' + testing + '>')
</script>
Edit 3 #trincot
Something's not right. I moved all of my MYSQL db setup and retrieve into a new file called fhs_get_photos.php. In my jQuery ready function I added the below. See my comments on what gets displayed
var myarray;
$(document).ready(function()
{
$('.tooltips').powerTip();
$(".radio1").on('click',(function()
{
var photo_type = $("input[name='photo_type']:radio:checked").val();
if(photo_type == 2)
$(".person").hide();
else
$(".person").show();
}));
$.getJSON("fhs_get_photos.php", function(photo_array)
{
if (photo_array.jsonError !== undefined)
{
alert('An error occurred: ' + photo_array.error);
return;
}
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
//$.each(photo_array, function(i, obj){
// $("#dom-target").append(obj.fhs_pkey + " " + obj.file_name + ", ");
//this displays correctly on a screen but not with anything else.
//Seems as if it's rewriting the page and only this is displaying which
//may be how it's supposed to go
document.write("In js. photo_array 2,caption is: " + photo_array[2] ['caption']);
});
});
In my main php I put
document.write("photo_array 2,caption is: " + photo_array[2]['caption']);
but it's not displaying anything. I suspect photo_array is not being passed into the page. In the js file, I then created a global variable 'myarray' and in the .getJason function I added
myarray = photo_array;
thinking it would pass into the main file but it didn't.
There are in principle two ways you can think of to get data in JavaScript:
1. Ajax request
With this solution use your current PHP file for generating the HTML page only, so without generating JSON, and create another PHP file which will generate the JSON only.
So let's say your JSON-generating PHP file is called fhs_get_photos.php, then it would have this code (no HTML!):
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
echo json_encode($result);
?>
See the last section in my answer for treating JSON encoding errors.
Make sure there are no line breaks or spaces before the opening <?php, and that you do not echo or print anything else than that one JSON string.
Your database query would also be in this new file. Note that currently you have a mix, like with this line:
echo "<img src = "."'".$filename."'" ."/>";
This line belongs in the non-JSON file, but it also depends on the query. So either you make an include file that does the query, include it in both PHP files, or you move the logic of defining the image tag (or at least the image's source) to the JavaScript part (better!).
Then in the original PHP file, remove the JSON output, and add some JavaScript, using jQuery (I understood you were already using it, so you have it included):
$(function(){
$.getJSON("fhs_get_photos.php", function(photo_array){
// photo_array now contains your array.
// No need to decode, jQuery has already done it for you.
// Process it (just an example)
$.each(photo_array, function(i, obj){
$("#dom-target").append(obj['fhs_pkey'] + " " + obj['file_name'] + ", ");
});
// or things like:
$("#caption_input").val(photo_array[2]['caption']);
});
});
This function will get executed once the HTML DOM has been built, so evidently after the first PHP file has finished execution. It will make the request to the second PHP file. Once that request is answered by PHP, the inner call-back function will receive the data. Note that there is no need to decode JSON here, as jQuery has already done that for you.
2. Generate JavaScript with data
Here you keep your current PHP file, but move the part where you inject the JSON encoded data to the JavaScript block:
<script>
var photo_array = <?php echo json_encode($result); ?>;
// ... process it
</script>
There is no need to wrap JSON in a JavaScript string to then parse it.
From json.org:
JSON is a subset of the object literal notation of JavaScript. Since JSON is a subset of JavaScript, it can be used in the language with no muss or fuss.
2.1. Valid JSON that could be invalid JavaScript?
Although not a problem in the context of this question (see below), there is an incompatibility between JSON and JavaScript syntax. It concerns whether or not the non-ASCII characters U+2028 LINE SEPARATOR and U+2029 PARAGRAPH SEPARATOR are allowed to appear unescaped in quoted strings:
JSON syntax allows this, as stated in the ECMAScript® 2015 Language Specification, section 24.3.1:
JSON allows Unicode code points U+2028 and U+2029 to directly appear in String literals without using an escape sequence.
JavaScript syntax does not allow this, as indicated in the ECMAScript® 2015 Language Specification, section 11.8.4:
All code points may appear literally in a string literal except for the closing quote code points, U+005C (REVERSE SOLIDUS), U+000D (CARRIAGE RETURN), U+2028 (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR), and U+000A (LINE FEED). Any code points may appear in the form of an escape sequence.
PHP's json_encode however, follows the possibility offered in that last line, and escapes all non-ASCII characters, including the problematic U+2028 and U+2028, except if you explicitly tell PHP not to do so with the JSON_UNESCAPED_UNICODE flag:
JSON_UNESCAPED_UNICODE (integer)
Encode multibyte Unicode characters literally (default is to escape as \uXXXX). Available since PHP 5.4.0.
So, a json_encode call without this flag will not produce instances of this problem.
3. Catch json_encode failures
According to the manual on json_encode the method can return a non-string (false):
Returns a JSON encoded string on success or FALSE on failure.
When this happens echo json_encode($result) will output the empty string, which is invalid JSON.
This error condition should be captured in PHP, for example like this:
<?php
header("Content-Type: application/json");
// Collect what you need in the $result variable.
// ...
// and then:
$json = json_encode($result);
if ($json === false) {
$json = json_encode(array("jsonError", json_last_error_msg()));
if ($json === false) {
// This should not happen, but we go all the way now:
$json = '{"jsonError": "unknown"}';
}
}
?>
And then in JavaScript, this condition should be handled as well, for example like this:
if (photo_array.jsonError !== undefined) {
alert('An error occurred: ' + photo_array.jsonError);
return;
}

Sending a JSON encoded PHP variable to JS with Laravel 4

I am having some trouble passing a JSON encoded php array to javascript in Laravel 4. I am sending it to my view from my controller, populating a value field in HTML, and then pulling that value with JS. Code is below:
Controller:
$artist_likes_profile = Fanartist::profile_fan_likes(Auth::user()->get()->id);
$artist_likes = json_encode(array("name"=>$artist_likes_profile));
return View::make('artists.show', compact('artist'))
->with('artist_likes', $artist_likes);
HTML:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="<? php echo $artist_likes ?>">
JS:
var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);
However, running this, I only see the artist_likes variable in the console appear as "{" instead of the actual json string.
When I add these two lines (to try to decode the json variable in js):
var artist_likes_decoded = $.parseJSON(artist_likes);
console.log(artist_likes_decoded);
I get the error:
Uncaught SyntaxError: Unexpected end of input
I know the JSON string is populating the value field, because I see this in the page source:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{"name":[{"id":215,"fbid":"19538277626","stage_name":"311","city":"","state":"","image_path":"http:\/\/graph.facebook.com\/19538277626\/picture?width=720&height=720",
"description":"311 was formed in 1990 in Omaha, Nebraska."},{"id":18,"fbid":"14591271531","stage_name":"Beck","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/14591271531\/picture?width=720&height=720",
"description":""},{"id":47,"fbid":"137029526330648","stage_name":"Disclosure","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/137029526330648\/picture?width=720&height=720","description":""},
{"id":11,"fbid":"152513780224","stage_name":"Arcade Fire","city":"","state":"","image_path":"https:\/\/graph.facebook.com\/152513780224\/picture?width=720&height=720","description":""}]}">
Any ideas what I"m doing wrong? Thank you.
It's because JSON string contains quotas (") and that breaks html parsing. You need to escape those first.
<?php echo str_replace('"', '\"', $artist_likes) ?>
Alternative solution is to pass JSON directly to js variable if this hidden input is only to make value available for js.
var artists_likes_decoded = <?php echo $artist_likes ?>

Sending PHP Strings Variables to a Javascript String Variables

Hi I am trying to send a long string of numbers from a file to Javascript. One I get it in Javascript as a string the rest will be easy.
This is the PHP code that grabs the series of numbers. It does grab them properly because it prints it out perfectly if I instruct it to do so.
$data = readfile($dataFile);
This is the Javascript Code:
var data = <?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;
When ever I run it the variable "data" is set to a random number. I assume it is the the number of characters in the sequence. I am relatively new to PHP and Javascript so a nice and clear explanation would be greatly appreciated. Thanks in advance.
Readfile reads the contents of the file and outputs them. It returns the byte length of the file, so $data is the number of the read bytes. link.
The number that is set in the variable $data is the number of bytes read by readfile. This is because readfile only reads the file and outputs its content to the standard output. To get the actual data in the file and assign it to a viariable, you can use file_get_contents(), like this:
$data = file_get_contents($dataFile);
Then the javascript assignment is good ;)
You need quotes if you want it to be a string in Javascript:
var data = '<?php echo json_encode($data, JSON_NUMERIC_CHECK); ?>;';

pass php array of email addresses to javascript

I have a php array containing email addresses that needs to be passed to a javascript function, but when javascript is trying to handle the addresses, i am getting a syntaxerror: illegal character error relating to the '#' in the email addresses...
How can I get round this? Is there a way of converting the email addresses to strings prior to them being passed to javascript? Or would I need to iterate over the array once it has been passed to js, and create a new array in js and convert them to strings then?
Ok, so the array is created by the user selecting the emails addresses from a list using checkboxes, this is then posted to a second page.
Heres the php code to create the array on the first page:
while ($row = mysqli_fetch_array($students_results)) {
echo'<div class="form-group"><div class="checkbox"><label><input type="checkbox" name="parentsemails[]" value=' . $row['parent_email'] . '">' . $row['parent_name'] . ' (Student: '. $row['student_name'] . ')</label></div></div>';
}
This is then posted to a seond page to be passed to the js function. The php to assign the array to a php variable is:
if (isset($_POST["parentsemails"])) {
$pe = $_POST['parentsemails'];
}
The the JS code inside the function:
email_a = new array(<?php echo implode(',', $pe); ?>);
The email addresses appear to be passed to JS correctly, in the error log I can see the individual emails, but with the illegal character highlighted...
Any help appreciated.
Thanks.
You are not enclosing the e-mails in quotes, which causes the syntax error you are getting.
You can add the quotes manually, but you can use the json_encode function instead.
The json_encode encodes a PHP object or array in JSON. As a JSON array is a valid JavaScript array, this will work well in your case.
Just change the JS line to:
email_a = <?php echo json_encode($pe); ?>;
As others have said, it looks like you need to surround the strings in quotes before putting them in the Javascript. Something like this.
<?php
$_a = array();
foreach($pe as $str)
$_a[] = "'${str}'";
?>
email_a = new array(<?php echo implode(',', $_a); ?>);

How do I take an unknown number of elements from a session array in php and use them as separate variables in JavaScript?

I a webpage written in php/html that adds the contents of a text box to a session array each time a submit button is pressed. What I need to be able to do is take the unknown number of elements in the session array and have access to each of them in the javascript portion of my code.
Here is the php portion of my code so far:
<?php
session_start();
if(!isset($_SESSION['answers']))
$_SESSION['answers'] = array();
?>
<?php
if (!empty($_POST['submit'])) {
unset($_POST['submit']);
$_SESSION['locations'][] = $_POST;
}
if (!empty($_POST['display'])){
foreach ($_SESSION['locations'] as $array){
echo "<script type='text/javascript'>alert('{$array['lat']}')</script>";
}
}
?>
This will display each as an alert, but I need them as variables that can be accessed in javascript.
Thanks in advance
Just encode your data as JSON. It will be parsed as JavaScript array/object literal by the browser:
var locations = <?php echo json_encode($_SESSION['locations']) ?>;
Having a variable for each element of the array is not a good solution.

Categories