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;
}
Related
I'm grabbing a number using jquery, from a piece of data in my html, as follows.
This is the html line.
echo "<p class = 'bold center remainingland' data-RemainingLandForFacilities = $RemainingLandForFacilities>Remaining Land For New Facilities : " . ($RemainingLandForFacilities) . "</p>";
I get the data using jquery with this...
var remainingland = $(this).closest('div').find('.remainingland').attr('data-RemainingLandForFacilities');
(after pressing a button, which is 'this'). This works correctly and an alert shows me the number.
I then post to my php script with the usual...
$.post('scripts/upgradefacility.php',
{
remainingland : remainingland
And I collect it with.
$RemainingLand = filter_input(INPUT_POST, 'remainingland', FILTER_SANITIZE_STRING);
At this point, I do have the number, but it's a string (as confirmed by gettype). But when I try to convert it to an integer with...
$RemainingLand = intval($RemainingLand);
I just get a blank. I should point out that I just copy/pasted all of this from previous variables which I'm passing, all of which come through correctly, so this is really odd. I can only assume that I've made some error that I can't spot or that I've been doing something wrong all along but I've somehow got away with it until now.
Your problem isn't that intval() fails converting your data into an integer, your problem is you're returning it with exit().
exit() takes one argument. If it's an integer, rather than printing it out, it uses it as an exit status code.
More information on how exit() works can be found in the php documentation here:-
http://php.net/manual/en/function.exit.php
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 6 years ago.
For a few days now I've been looking for a solution to display UTF8 on my
webpage.
The character currently causing trouble is į (unicode: \u012f decimal: 303) however,
there are over 10,000 records in my database and I cannot guarantee that all others are displaying correctly.
So I'm looking for a solution that should cover all characters.
The į is displaying as a ? in the HTML.
My setup is a HTML page, which uses AJAX to send a request to a PHP file.
The PHP then queries a MYSQL database to find a specific entry,
it then takes a lithuanian word from that entry and echoes it as a response to AJAX.
Back in the Javascript, the response is set as the innerHTML of a HTML element.
This current setup is not using JQuery.
Below is my progress on attempting to fix the issue.
First, I verified that all files I was working with are correctly encoded to UTF8, not UTF8BOM.
Then I opened the MYSQL database in phpMyAdmin to view the entries.
Seeing characters replaced with ? in the entries, I done some research and found the database had the wrong collation.
After changing the collation to utf8_general_ci for the database/table nothing changed, so I looked into it further and found that changing it for individual columns of a table was another solution.
This worked and my database is now displaying the characters correctly.
Next the character š (unicode: \u0161 decimal: 353) would not display in my webpage,
I fixed this by using the following code in PHP which I found on stackoverflow.
function encode_string($string){
$encoded = "";
for ($n=0;$n<strlen($string);$n++){
$check = htmlentities($string[$n],ENT_QUOTES);
$string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
}
return $encoded;
}
I can't say I completely understand this code but it caused the character š to display correctly when it got to my HTML.
However this did not work for the character į.
I have also tried $conn->set_charset('utf8'); to set the connection to use utf8 however this resulted in į being displayed
as į instead, same result for $conn->query("SET NAMES UTF8;");
I have found that hardcoding the į into the Javascript or PHP, allow it to be sent back and displayed correctly, for example echo "į"; works.
So I believe the issue may be related to the database or in the PHP before the echo.
However I don't have the knowledge to identify the problem.
Here is my php code below:
<?php
header('Content-Type: text/html charset=utf-8');
//Connection to database is made. Referred to as $conn
$sql = "SELECT * FROM Words";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
//Loop through the results to find a word with the status of 1
while($row = $result->fetch_assoc()) {
$status = $row["status"];
if($status == 1){
//respond to AJAX with the word
$ltword = trim($row["lt"]);
echo utf8_encode(encode_string($ltword));
//Has also been tested as
//echo encode_string($ltword);
//with no noticeable difference.
break;
}
}
}
function encode_string($string){
$encoded = "";
for ($n=0;$n<strlen($string);$n++){
$check = htmlentities($string[$n],ENT_QUOTES);
$string[$n] == $check ? $encoded .= "&#".ord($string[$n]).";" : $encoded .= $check;
}
return $encoded;
}
?>
At the core my question is, given my current setup,
how do I correctly get an encoded UTF8 character from my database to display on my webpage?
EDIT:
The mb_check_encoding() function of php, verifies that the data received from the database is valid utf8.
php.ini is using utf8 as it's default charset.
Using $conn->character_set_name(); returns the result latin1.
Using $conn->set_charset("utf8"); causes it return utf8, however į is then displayed as į which is still incorrect.
If you're using mysqli, you can call set_charset():
$mysqli->set_charset('utf8mb4'); // object oriented style
mysqli_set_charset($link, 'utf8mb4'); // procedural style
in your case problem was collation, which was modified later. As a good practice try to set table collation as well as column collation same ie. utf8_unicode_ci (general is faster but unicode is much better for sort/display).
Now coming back to problem, the problem lies with already added data which was stored wrong due to non proper collation. For that you need to look & resolve method as you cant be sure it was stored properly.
If you have UTF8 end to end (db > connection > php) you should not have to echo utf8_encode. Just echo the variable and it should display correctly.
Most likely, the character is is messed up in the database because it's still in the original encoding. Try updating the contents of the database with native UTF8 characters now that the collation has been fixed and it should work.
So most likey you will need the $conn->set_charset('utf8') too.
I am taking backend perl variables and using it at the front end for display.
Here is the code.
head1 and head2 are the header names taken from perl script. I use that and display those headers of grid on webpage.
var headname1= "#head1";
var headname2= "#head2";
Now, if there are 100 headers, i would have to assign variables 100 times separately. so its better to make it dynamic. Taking values from backend and assigning it to javascript variable. This task will be dynamic. Here is my attempted code for that.
I hav taken all the headers from backend and assigned it to line_array. #line_arry is the name of that array. If i do #line_arry[0] and so on. appropriate values will be displyaed.
var headname=[];
for(var i=0;i<total_columns;i++) {
headname[i+1]= "#line_arry[(i)]";
}
This code doesnot work. It displays only the first column. i.e.
headname[1] = "Order";
headname[2] = "Order";
Order is the name of the first header. In headname[2], header of second column should be displayed. but it still displays "Order"
If i write the below code, it displays first and second header.
headname[i+1]= "#line_arry[(0)]";
headname[i+1]= "#line_arry[(1)]";
"#line_arry[i]" doesnt work whereas
"#line_arry[0], #line_arry[1] works.
Can anyone suggeest why it is not performing looping action using variable i
Disclaimer: This has a lot of assumptions about the question.
If you are using CGI and you are trying to create JS code in Perl that you will print to the browser, it makes more sense to use JSON. As was suggested in the comments, you can use AJAX, but you can also just use the JSON module to get the JSON representation of your Perl data structure, and incorporate that as a string into your website.
use strict;
use warnings;
use CGI;
use JSON 'encode_json';
my $q = CGI->new;
# make some test headers
my #headers = map { "header $_" } ( 1 .. 100 };
# convert it to JSON representation (a string!)
my $header_as_json = encode_json(\#headers);
print $q->header();
print <<HTML
<html>
<head>
<script>
var headname = $header_as_json;
</script>
</head>
<body>Hello World!</body>
</html>
HTML
I have a database form on a MySql table on which I have a javascript function to populate the options of a select tag. Those options are fetched from a table of clients who have a status of either "Active" or "Inactive", and the return values are of those clients where their status is active. In the event an order is loaded where the client status is inactive, I'm trying to add a handler for inactive clients. The form loads from a php script that left joins the client table to the main table, where clientId in the main table is equal to Id in the client table. So, I have the name and id of the client fetched outside of the function to populate the options list, regardless of their status.
There is one line that is causing me fits. I have searched this site and others and have found many solutions, but none have worked for me so far. This is the line:
var txt = <?php echo $row[`clients`.'name']; ?> ;
What is returned in Chrome and Firefox debuggers is, "Uncaught syntax error: Unexpected token <". The debugger shows: var txt = <br />
I've tried enclosing the php script in single quotes, double quotes, and without quotes, and still no luck. Any thoughts, anyone?
About an hour later--> I found a workaround. I tried all of your suggestions, but none worked in this instance. var_dump and json_encode confirmed what I knew already, that the returned data was valid. Regardless of any of the variations in syntax, they all returned the same error. What I did was to apply the same syntax as above, but in a hidden input:
<input type="text" id="cName" hidden value="<?php echo $row[`clients`.'name']?>" />
Then changed the javascript code to this:
var txt = document.getElementById('cName').value;
Everything else works perfectly. Of course, I still have lingering thoughts about the use of backticks, and would prefer that I had a better, and safer code. As I mentioned somewhere, I simply copied the sql syntax directly from phpMyAdmin. In this instance, if I substitute single quotes for the backticks, the input returns nothing. Well, thanks all. If anyone wants to contribute more, I'll be glad to hear about it.
That's illegal PHP syntax, and very dangerous syntax in general. Try doing a var_dump($row) to see exactly what's in that array. Probably you want something more like
var txt = <?php echo json_encode($row['clients.name']); ?>;
instead.
Note the use of json_encode(). This will ENSURE that whatever you're spitting out in the JS code block is actually syntactically valid javascript.
e.g. consider what'd happen if you ended up with
var txt = Miles O'Brien;
^^^^^--undefined variable;
^--- another undefined var
^--- start of a string
^^^^^^^---unterminated string.
with json_encode(), you end up with
var txt = "Miles O'Brien";
and everything's a-ok.
var txt = "<?php echo $row['clients']['name']; ?>";
var txt = <?php echo $row[`clients`.'name']; ?> ;
Consider how PHP parses this:
var txt = is to be output directly to the client.
Enter PHP mode.
echo the following expression.
Evaluate $row[`clients`.'name'].
First we need to determine the array index, which is the concatenation of `clients` and 'name'.
Backtick in PHP is the execution operator, identical to shell_exec(). So PHP attempts to execute the shell command clients, which probably fails because that isn't what you intended and it doesn't exist. Consequently, at this stage, PHP outputs an HTML error message, starting with a line break <br />.
Your client now has var txt = <br /> (you can verify this by inspecting the HTML source of the page returned to your browser), which it attempts to evaluate in its JavaScript context. This gives rise to the "unexpected token" error that you have witnessed.
As others have mentioned, you probably meant to do something like $row['clients']['name'] or $row['clients.name'] instead—but without seeing the rest of your PHP, it's impossible to be sure. Also, as #MarcB has observed, you need to be certain that the resulting output is valid JavaScript and may wish to use a function like json_encode() to suitably escape the value.
The error comes from the fact that your return value (a string in javascript) must be in quotes.
Single quotes will take whatever is between them literally, escapes (like \n ) will not be interpreted, with double quotes they will.
var txt = "<?php echo $row['clients']['name']; ?>";
is what you want
Change this
var txt = <?php echo $row['clients'.'name']; ?> ;
to this:
var txt = <?php echo $row['clients']['name']; ?> ;
I am currently coding a website that will allow a user to input data into a MySQL database using a WYSIWYG editor. The data stores into the database without a problem and I can query it using PHP and display it on my webpage.
Up to this point everything is working ok until I try to move the HTML stored in the MySQL database into a javascript variable. I was able to get it working using CDATA[], but not for every browser. It works in Firefox, but not IE or Chrome. I am looking for a solution that will be able to work in all of the browsers. Any help would be greatly appreciated.
Since you're using PHP:
<script>
var foo = <?php echo json_encode($htmlFromDatabase); ?>
</script>
The json_encode method, while normally used for encoding JSON objects, is also useful for converting other PHP variables (like strings) to their JavaScript equivalents.
"Safefy" your code, like this
str_replace( array("\r", "\r\n", "\n", "\t"), '', str_replace('"','\"',$str));
The above function clears linebreaks, and tabs so that your code appears in one line. If it breaks into more than one line, then it cannot be parsed as a string in JS and an error is thrown. Also we are escaping " to \", maybe there are more string replacements that need to take place, it depends in your content.
and inline it in javascript,
//<![CDATA[
var myHtml = <?php echo '"'.$stuff.'"'; ?>;
//]]>
keep in mind the '"' part so that it appears like this var myHtml = "test";