Atom Editor: Error when PHP is inside Javascript - javascript

I have the following code in a PHP page in ATOM:
<html>
<head>
<?php $testvar = "Test"; ?>
<script>
var test = <?php echo $testvar; ?>;
</script>
</head>
<body>
<p> This is a test. </p>
</body>
</html>
The page is doing exactly as planned on the PHP page but in Atom, everything after the </script> line is highlighting in red as in an error. What's going on here?
Here is a screenshot of the actual code I'm using. The above is an example but also has the same problem.
I have opened a Issue claim on the Atom support but I would like to try here as well to see if it's anything within the code.
Thanks!
Image

This is a bug in your code, not in Atom. Your echo statement produces an unenclosed string:
<script>
var test = Test;
</script>
This results in a JavaScript error ("Uncaught ReferenceError: Test is not defined") because you are telling the interpreter to use a variable named Test, but none exists.
You need to produce a properly enclosed string, which you can do with json_encode():
<script>
var test = <?php echo json_encode($testvar); ?>;
</script>
Based on your comment, you're actually trying to build an array, not just echo a string. You have this code:
var main_categories_array = [<?php echo '"'.implode('","', $main_categories_array ).'"' ?>];
If your array contains any quotation marks, like the simple "Test" example, you will get errors. So, your code should be:
var main_categories_array = <?php echo json_encode($main_categories_array); ?>;

That was an actual bug fixed in 1.13, released yesterday : 10th of January.
Sources :
https://github.com/atom/atom/issues/13532
http://blog.atom.io/2017/01/10/atom-1-13.html

This is a bug with Atom.
Posted here: https://github.com/atom/atom/issues/13532

Related

PHP Variable from String with Javascript popup

In /var/www/html/msg.txt is just one word "Test".
Can someone please tell me why this doesn't work?
echo "<script>alert('$tes');</script>";
Complet php code:
<?php
$ma="Test";
$tes = file_get_contents("/var/www/html/msg.txt");
echo "$tes"; //works
echo "<script>alert('$ma'); //works
</script>";
//but if this
echo "<script>alert('$tes'); // doesn't work!!!! Why?
</script>";
?>
how can I do it?
Most likely you have a line break in that file, so the resulting code is:
<script>alert('Test
');
</script>;
Which is wont work, you can confirm this by looking at the source, and/or it will be erroring out in the browser console.
The problem is with your file_get_contents. Probably you are setting an incorerect path, or the file that you are trying to access doesn't have the right permissions

Call Javascript Date Code Into PHP Buffer

ISSUE:
I am attempting to call a JavaScript 'date_code' file (to get current YYYY/MM) to use as part of my 'directory URL' to store some .php files.
EXAMPLE:
"../Directory/2017/07.php" would represent the .php 'directory' file for the month of July, 2017.
NOTE:
A similar process works successfully if I am using it within a 'form submission'...
However, in this particular case, I am constructing a Cron Job, so a form will not be part of the process.
ATTEMPTS:
Among other things, I have attempted to use...
<?php $dateIndex = "path_to_date_code.js"; ?>
(as shown in the demo code below).
RESULTS:
So far... I have had no success at all being able to call in the JavaScript 'date code' or output the files to their proper destination.
SUMMARY:
If anyone could advise me what I am doing wrong or point me in the right direction, I would greatly appreciate it. Thank you in advance.
DEMO:
<?php ob_start(); ?>
<html>
<head>
</head>
<body>
<?php echo "Some Content" ?>
<?php $dateIndex = "path_to_date_code.js"; ?>
</body>
</html>
<?php echo ''; file_put_contents("../Directory/$dateIndex.php", ob_get_contents()); ?>
You are confusing the roles of PHP and Javascript. PHP runs on the server, while Javascript and your date code file only run IN THE BROWSER. The Javascript will do nothing on the server.
I don't really understand what you are trying to do, but how about constructing a path like this:
$date = date("Y/m"); // Y is 4 digit year, m is two digit month
$path = "../Directory/{$date}.php";
The braces are not really needed. They are used to isolate a variable when embedded in a string. I've added them so the variable stands out.
If you need to make a path for a given date, use this type of thing:
$date_to_use = "2015-12-12"; // whatever
$date = date("Y/m", strtotime($date_to_use));
$path = "../Directory/{$date}.php";

PHP Preg_Match_All Returning No Results

I am using Simple HTML Dom Parser to scrape a script tag from a webpage and then attempting to parse certain data from said tag using preg_match_all(). However, when I print preg_match_all, no results are returned.
Below is the code I'm using:
<head>
<?php
require_once "toolkit/http.php";
require_once "toolkit/web_browser.php";
require_once "toolkit/simple_html_dom.php";
?>
</head>
<body>
<?php
$prod_url = 'http://www.domain.com/subpage.html';
$html = file_get_html($prod_url);
$script = $html->find('script', 17);
//echo $script;
preg_match_all('(?<=\d":)\w++', $script, $matches);
print_r($matches);
?>
</body>
I can see that the HTML Simple Dom code is working correctly, as I get the results I expect when echoing the $script variable. The results are:
<script type="text/javascript">
var PRODUCT_JSON = {
"Def":{
"default":202705111,
"Listing:[{
"label":"Includes",
"options":[
{label:"All", id: "884"},
{label:"None", id: "485"},
]
}],
"Lookup":{
"1":202705111,
"0":202493236
}
}
};
</script>
So, the issue appears to be with the regex I'm using in preg_match_all(). The goal of the regex is to return the two numbers, 202705 and 202493, near the end of the script tag. It may have to do with escaping the double quote or parentheses, though I've also tried preg_match_all('\(?<=\d\":\)\w++', $script, $matches); with the same result. Any ideas on what I'm doing wrong?
If you keep forgetting about delimiters, you can use T-Regx, which automatically adds delimiters.
$matches = pattern('(?<=\d":)\w++')->match($script)->all();

Is it possible to use the same variable in two different javascript blocks?

I am developing a web that has to show an sql view, so I did the query with PHP, but I have to show the result in charts, and I am trying to use the google geochart. So basically what I want to do is:
Select the data from an SQL view with PHP.
Get the data from PHP into a javascript variable so I can use it in the chart.
Get the value of the javascript variable to put in the google chart api, so it show what I want.
So far, I've got the point 1 and the point 2 (I think) done. But when I am trying to use the javascript variable again in another part of the code it has no value, so no data is showing, I am getting undefinedon the explorer.
Relevant Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?php
//connections and stuff
$tsql="SELECT count(*) as Qty, ShipCountry FROM [Orders Qry] group by ShipCountry"; // yes, is the Northwind database example
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query table: ".$tsql);
}
else
{
$json=array();
$i=0;
echo "<script type='text/javascript'> var countries = []; </script>";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";
$i=$i+1;
}
//echo "<h1>". $json["ShipCountry"] ."</h1>"; //I was testing, so the problem is not in retrieving the data from the database.
sqlsrv_free_stmt($stmt);
}
?>
<p>
<script type="text/javascript">
document.write(countries[0]);
</script>
</p>
</body>
</html>
You forgot to quote $row['ShipCountry'] (seems to be a string);
echo "<script> countries[".$i."]= '". $row['ShipCountry'] ."';</script>";
Note the new quotes.
You might want to consider using AJAX to query a different file from within your javascript, cf. http://www.w3schools.com/ajax/ajax_php.asp.
If you have your PHP file return JSON to the AJAX request, javascript will have an object that it understands and you can use it there. This way you can have all your javascript in one place. E.g. this pseudo code:
Javascript.js
function gimmeACountry(i){
var countries = AJAX.get('countries.php');
return countries[i];
}
PHP.php
<?php
$result = mysql_stuff(...);
print json_encode(result);
?>
HTML
<html>
<head>
<script src='Javascript.js'>
</head>
<body onload="document.write(gimmeACountry(0));">
</body>
</html>
If you really want to use just one file, a few thoughts:
You don't need to open and close a statement every time you write javascript. All of your PHP could be embedded in one.
You can output most of your javascript outside of the block, instead of echoing everything. I think the PHP is clearer then. E.G.
<script>
<?php $foo = 'bar'; ?>
var foo = <?php echo $foo ?>;
document.write(foo); // writes 'bar'
</script>
If you are still have scope issues, you can try adding your variable to the window object, e.g.
window.countries = []
This might be problematic if you end up doing more stuff with javascript later. I really do recommend you use AJAX.
You should use push method and Array() Construct
var countries = [];//nope
var countries = new Array();//yep
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";//nope
echo "<script> countries.push(".$row['ShipCountry'].");</script>";//yep
push method documentation
Distributing javascript over two blocks works fine:
<html xmlns="http://www.w3.org/1999/xhtml">
<head />
<body>
<script>
countries = ['foo'];
</script>
<script type="text/javascript">
document.write(countries[0]);
</script>
</body>
</html>
But the problem is that your PHP isn't generating valid java script. Have a look at your browser's JS console, and you'll see ReferenceErrors because you didn't quote the country names.

Passing value throught php, javascript and html

Take in mind the following; the code below and programs associated at it is runs perfectly.
<script>
window.vorderby = "YEAR"
exibelivrosAJAX();
</script>
but, when I did the modify below gave me the following error: Uncaught ReferenceError: YEAR is not defined
<script>
window.vorderby = <?php echo $_POST['formorderby']; ?>;
exibelivrosAJAX();
</script>
Looking for and reading tons of messages I did the following:
<script type="text/javascript" src="funcoesJS.js">
window.vorderby = <?php echo $_POST['formorderby']; ?>;
exibelivrosAJAX();
</script>
and the error was solved. But, the function exibelivrosAJAX() don't run.
Below you can see the two pieces of code that I think can help you to understand a little better.
1st piece of code in the primary file:
echo " ";
2nd piece of code in another php file:
window.vorderby = ;
exibelivrosAJAX();
Could you help me to understand it? Thanks a lot! Marcos.
You still need the JS quotes:
<script>
window.vorderby = "<?php echo $_POST['formorderby']; ?>";
exibelivrosAJAX();
</script>
In the 2nd example, your code is not executed [and therefore you get no error] because of the src attribute of the script tag.
You forgot to enclose the outputed variable with qoutes
window.vorderby = "<?php echo $_POST['formorderby']; ?>";

Categories