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";
Related
Please tell me why this code tells me
SyntaxError: unterminated string literal
My code:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo $geladen; ?> ");
</script>
That's a JavaScript error message, which strongly implies one of two things:
the JavaScript that reaches the browser still includes the <?php etc., meaning the PHP didn't get parsed on the server (and thus the browser flipped out on "./testtext"), or
the file testtext (and therefore your variable $geladen) contains quotation marks. Either is possible from the very little information you have posted.
You can figure out which it is by looking at the HTML in your browser.
If it's the former (if you see <?php in the HTML), then you need to fix your server configuration.
If it's the latter (if testtext contains any " marks), then you need to encode it properly before echoing, using json_encode() like this:
<script>
console.log(" <?php $geladen = file_get_contents("./testtext"); echo json_encode($geladen); ?> ");
</script>
All that said, mixing PHP and HTML (not to mention PHP, HTML, and JavaScript) this way is not a great practice. You'd be much better off using a templating engine of some sort (Twig, Blade, etc.).
If the contents of 'testtext' contains a quote mark, it will break the javascript. Try addslashes().
<script>
console.log(" <?php $geladen = addslashes(file_get_contents("./testtext")); echo $geladen; ?> ");
</script>
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;
}
There is some data that I need to get from a local crawled page. It's inline javascript like this:
<script type="text/javascript">
//<![CDATA[
var graph_data = {"query":{"cid":["13908"],"timestamp_from":1402531200,"timestamp_till":1402531200,"views":1138942,"data":
etc, the variable is very long but you get the idea. I want to put "graph_data" into an array called $data. What is the best way to do this? I should add this is all being done by me locally & I don't need to execute any javascript code, just extract the data.
I have make a suggestion purely as an idea with some code worth trying!
As suggested, the DOM Document may provide this much easier, but here's another possible solution for extracting...
I'm guessing that the var graph_data is a JSON string that you want to extract from the HTML page so that you can store as a PHP var. The problem is that your code doesn't show how the variable ends but I'm going to assume that a new line break would be the way to identify the end of the variable being set. It may be a semi-colon though and if it is, instead of "\r\n" try ";"
// Assuming your html code is stored in $html...
preg_match("/var graph_data[^\{]*?(\{[^\r\n]+?)/is",$html,$match);
print "<pre>";
print_r($match);
print "</pre>";
This should result in $match[1] storing the part you need.
You can try passing that into json_decode() but that's touching some wood with crossed fingers.
Good luck...
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 using the Google Places API to supply my application with a list of cities, countries, etc for a dropdown menu. I use an AJAX request to a file containing this code:
$results = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?types=(regions)&language=EN&offset=4&key=" . $key . "&input=" . $input);
$decode = json_decode($results, true);
foreach($decode["predictions"] as $value){
$json_array[] = $value["description"];
}
echo json_encode($json_array);
Everything seems to work okay on this side of things, however when the JSON is returned to the AJAX application, some of the characters appear incorrectly. For example, the "ã" in "São Paulo" appears as ",," or "S,,o Paulo" when I try to display the results. If I alert the result, the characters do display correctly in the pop-up - so I seem to be missing something when I give the results to the javascript to display in the drop down. (What also is irritating is that the incorrectly coded results end up getting entered into my database when the user selects from the drop down.)
I have tried encoding each string with "utf8_encode()" before I add it to "$json_array" (in the PHP file, of course), but this only seems to complicate things - it appears that the results are double-encoded or something when it is finally displayed in the javascript.
Also, I should note that the web page has the UTF-8 charset in the meta tag.
As a follow-up:
I created a simple HTML page which in which I displayed "ã" in a div, and it did show up properly. I also used jQuery to display the same character in another div on page load, and this too showed up correctly. And I didn't even need to set the encoding on that page. So I can only assume, because this test page is plain vanilla HTML, that the problem is coming from my PHP set-up.
I have added the following to the head of another PHP tests page:
mb_internal_encoding("UTF-8");
mb_http_output("UTF-8");
mb_http_input("UTF-8");
mb_language("uni");
mb_regex_encoding("UTF-8");
ob_start("mb_output_handler");
header("Content-Type: text/html; charset=UTF-8");
but I am still seeing the characters incorrectly displayed. So to this point I have added the above, updated the default_encoding to UTF-8 in php.ini, and checked that the meta tag specifies UTF-8. This is really starting to irritate me now!
use one of either header:
header('Content-type: application/json');
header('Content-Type: text/html; charset=UTF-8);
work for me in case of Arabic language.
It might be that the webpage is not recognizing the character. To fix this, use HTML code for this character.
For example, the HTML code for ã is ã.
You can find more information on this here.
Check for special characters in your PHP string and convert these.
$mystring = 'São Paulo';
$findme = 'ã';
$pos = strpos($mystring, $findme);
if ($pos != false) $findme = "ã";
This was the dumbest thing... but I learned a lot about character encoding along the way. It turns out (and I didn't mention this at all because it just didn't seem relevant) that the Helvetica fonts in Bootstrap cannot display these special characters. Yeah, wtf? I had every possible encoding option set to "UTF-8", and all along it was just the stupid CSS font selection. So in the end I just changed the font family to "Arial" and instantly the problem was solved.
Thank to everyone for the input.