Why does the PHP file not read the javascript properly? [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 3 years ago.
I'm making a website, and have been trying to write javascript in a PHP file to create an alert, then depending on if the user clicks "ok" or "cancel", it takes them to different pages. I got a javascript code that should work in an HTML file, but the PHP file doesn't read it for some reason.
This is for a XAMPP server, running MySQL, PHP, HTML, CSS, javascript, and Apache. I tried pasting this into my PHP file, but it doesn't read properly.
if ($sessioncode != "Admin-placebojoe" || "Mizzy-renegade") {
loginFail();
} else {
loginSuccess();
}
function loginFail() {
var txt;
var r = confirm("Account does not exist. Either check credentials and try again, or press ok to Sign Up.");
if (r == true) {
txt = header("refresh:6; url=Signup.html");
} else {
txt = header("refresh:0; url=Login.html");
}
}
The PHP file rejects the line where it says var txt; on line 8. The error message reads:
Parse error: syntax error, unexpected 'var' (T_VAR) in C:\xampp*****
on line 13
(I left out a few lines at the beginning that's why it's line 13). This tells me that the error is the PHP file cant read the JavaScript.
How can I make the PHP file read and execute all of the JavaScript code?

PHP doesn't read or execute JavaScript. JavaScript runs in the browser.
If you include a JavaScript block in your .php file, PHP will (just as it would if you include a raw HTML or CSS block in a .php file) simply pass that code as-is to the browser in the response it gives to the HTTP request coming from that browser.
However if you are getting the error mentioned it implies that you tried to put this code inside a <?php block. This means the PHP interpreter will try to execute it as PHP code on the server. But as you said yourself: it isn't PHP code, it's JavaScript. Therefore (obviously I hope) the PHP interpreter cannot understand it and you get a syntax error.
If you want to include some JavaScript code to run in your browser, then move it outside the <?php ... ?> tags and put it inside a <script> block instead, e.g.
<script>
alert("Hello, World");
</script>
P.S. For background you may want to read this popular and informative thread: What is the difference between client=side and server-side programming?

Related

Run a python script using requirements with browser JavaScript

My main goal here is to execute a python script I have written when I run a function triggered through HTML. Here is how I have things currently set up:
I have a JavaScript File containing python run functions:
const PythonShell = require('python-shell').PythonShell;
class AHK {
static async runScript() {
PythonShell.run('/ahk/script.py', null, function (err) {
if (err) throw err;
console.log('finished');
});
}
module.exports = AHK;
I have my main.js file which would be the js code for the HTML to handle. I'd like for it to take in the module AHK. Something simple like this:
const AHK = require('./ahk');
function runFunction(x){
if(x = 1)
AHK.runScript()
}
And then I have some HTML with a javascript tag
<script type="text/javascript">
let x =1; //this is just to show x is getting populated. In the actual code it's constantly changing values
async function predict() {
if(x > 1)
runFunction(x)
}
</script>
Biggest issue I'm facing:
I've become aware that browser javascript doesn't like requirements/modules. For example, the main.js file doesn't like having a requirement at the top. I've tried using things like requirejs, but I can't seem to figure out how to make something like this work. I basically need it so that when the requirement is met and the function runFunction is run, the python script is executed on my machine.
Important to note that this is all running for a personal project on my computer, so it will never not be local.
Make the application on your pc an API and use the web page to send a request to the API telling it which python script to run. I haven't used python too much but I believe you can make an API with it. Then you can just make buttons for each python program you want to run and have these buttons send a request to the API.

php response text empty when using password_hash or password_verify

I have an application that uses javascript to get a string and POST it to a receiver php file on the server for further processing. The receiver's job is to parse the string, pass things along, and report to javascript how stuff is going. Recently I've tried to add password-based security to this whole shebang, but now receiver.php passes back an empty response.
What I'm finding is that if I call password_verify anywhere in the receiver (no matter what I do with it... I could even just call it without using it) the following echos in the script don't run - any responseText from those echos will be empty - and I've no idea why. Though, if I just run the php script raw from command line, everything DOES work.
Before continuing, I would note that I am pretty new to web development and password-based security, so don't skewer me too hard. Good news, though - unlike every OTHER problem I can find on the web, I AM getting correct hashes and correct verify-responses.
Using php 5.6.23
A scaled down version of the JS file "test.html":
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function reviewAndSubmit() {
//bigOlString is usually built as a result of TONS of script on this page, use this as a test
var bigOlString = "password=1234 name=test otherParams=barglebargle"
var postString = new XMLHttpRequest();
//build function to receive post response
postString.onreadystatechange = function() {
if (postString.readyState == 4) {
window.alert("responseText: " + postString.responseText)
}
}
postString.open("POST", "receivertest.php", true);
postString.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
postString.send(bigOlString);
}
</script>
</head>
<body>
<button class="button" id="pushMe" onClick="reviewAndSubmit()">Why does PHP hate me so bad?</button>
And receivertest.php:
<?php
//hashed version of '1234' and debug name 'test'
$debugPass = '$2y$10$b.08/4NfawKOwrBYJqguc.AWsI3mQiGGaz1eYvfc9Uid1auQKKABm';
$debugName = 'test';
//get incoming string
$inString = file_get_contents('php://input');
//get challenge content
$challengePass = substr($inString, strpos($inString, "password=") + 9, strpos($inString, "name=") - 10); //10 because of the space
$name = substr($inString, strpos($inString, "name=") +5, (strpos($inString, "otherParams=") - strpos($inString, "name=") - 6)); //ugly!
//begin authentication
$auth = False;
echo $name;
echo $challengePass;
password_verify($challengePass, $debugPass); //yes, I'm not doing anything with this. Doesn't matter.
echo "this line won't echo";
?>
If you comment out the 'password_verify' line in receivertest.php, everything echos perfectly. If you don't, no luck - the 'alert' window in test.html just spits out 'responseText test123'. If you run receivertest.php in console (php receivertest.php), however, everything echos correctly.
Why is my responseText empty?
EDIT: I've edited the php script to better illustrate the problem. Yes, I know I'm not USING password_verify for anything. It doesn't matter. The 'this line won't echo' line doesn't echo out in test.html like the other lines do. My question is: why NOT?
The code is all fine. I made a quick edit in my httpd.conf file and restarted apache, and everything started working. I undid that edit to check and restarted - everything still worked. So I guess all I needed was an apache restart.
Apache seems to have more to do with php than I thought, I guess?

Disable syntax errors for PHP code inside JavaScript file in Aptana Studio 3

I am having PHP code inside my JavaScript file, which is processed by the server by setting the handler for the .js file extension to php5-script using a .htaccess. I tried opening the .js file in Aptana Studio using PHP Source Editor and JavaScript Source Editor, however, both editors highlight the php code as syntax error. I couldn't find an option in the settings where I can set the file type to a mix of PHP and JavaScript, or disable syntax error highlighting for PHP code in JavaScript, or anything else.
I have found a similar question but this is just related to the PHPStorm IDE which I do not want to use.
The content of my .js file currently looks like this:
<?php
header('Content-type: application/javascript');
$app_base_path = $_GET['_app-base-path'];
$app_route = $_GET['_app-route'];
?>
$(function() {
var APP = {
// syntax errors are thrown here
// the single quotes could be escaped to reduce syntax errors
// looking for a way to make a code like this possible without any syntax errors
base_path: '<?= $_GET['_app-base-path'] ?>',
route: '<?= $_GET['_app-route'] ?>'
};
$('body').append('APP.base_path: ' + APP.base_path + ' --- APP.route: ' + APP.route);
});
I previously read your question wrong. My bad. If php is NOT parsing the <?= ?> tags, make sure it's enabled in php.ini
Unless the string data in the $_GET parameters contain strings with single quotes in them, you shouldn't have an issue.

changing a js file location only when the source-code is showed

i'm trying to change a js file location when a visitor shows the source-code
, depending on that :
javascript functions don't work when the visitor shows the source-code
.
my idea is creating a file , put a javascript code to delete the file , in this situation the file won't be deleted if someone showed the source-code :
$check="$ip-$views-$id";
fopen("$check.txt","w"); //CREATING A FILE
// DELETING THE FILE ABOVE BY JAVASCRIPT , IT WON'T BE DELETED IF SOMEONE ENTERED VIA THE SOURCE-CODE MODE
?>
<div id="countno"></div>
<script type="text/javascript">
$('#countno').load('del.php?name=<?echo $check;?>&location=' + ' #countno');
</script>
<?
if (file_exists("$check.txt")) { //IF SOMEONE SHOWED THE SOURCE CODE
$new_location="fake_location.js";
}
else{
$new_location=$old_location;
}
?>
<script src="<?echo $new_location;?>"></script>
the problem now , is that the file_exists php function shows that the file still exists even though it was already deleted by the javascript code .
the file_exists function was executed before the javascript code !
any help / solution to make that php function check the file after that javascript code ? i know it's kinda impossible but it worth it !
What you are describing is not possible. php is a server side language while javascript is a client side language. Thus, the PHP on your page will always execute before the Javascript on your page executes. There is no way to make your Javascript execute first when you have it this way.
Instead, what you could do is to separate the PHP and Javascript. Have your file_exists check in another page. e.g. check.php.
if (file_exists("$check.txt")) {
echo "fake_location.js";
} else {
echo $old_location;
}
Then use an ajax call to make a request to check.php, and load your other script depending on what check.php outputs.
<script>
$.ajax({
method: "GET",
url: "check.php"
})
.done(function(script) {
$("#check").attr("src", script);
});
</script>
<script id="check"></script>
However, if your goal is to prevent people from figuring out where your javascript is located, it is not possible. Most browsers nowadays can inspect the HTML as it changes. They can see the loaded script without having to load the source separately.

How to include JavaScript file into JSP?

I have the following script tag in my JSP file:
<script src="/js/CCTUtil.js"></script>
with the following function in it:
function disableButton(buttonID) {
document.getElementById(buttonID).setAttribute("disabled", "true");
return true;
}
and in my jsp I call it with:
onchange="disableButton('datasourceForm:cancel');
datasourceForm:cancel is just the ID, so don't worry about that.
This works if I hardcode the JS function in my JSP, but when exporting it to a file, it doesn't work. It recognizes the valid filepath (otherwise the server throws an exception) so it can see the file just fine, but when testing it in Internet Explorer the error is "Object expected", and points to the end of the JSP file, which of course isn't telling of anything.
Help please?
The SRC must not be correct then. Are you sure you have set the path correctly? It's not supposed to be "../js/CCTUtil.js" is it?
Instead of including script file, directly add javascript function in the jsp file.
Then try, if you are getting the same issue, might be some issue with javascript or ur id datasourceForm:cancel

Categories