Running javascript inside php without echo - javascript

So I have a php file on my server which handles HTTP POST requests. When it receives a post request, it runs a javascript script.
Currently I have the script with echo'...';
But the problem is that with the script inside echo, it simply sends the raw code to the place where the HTTP post was generated from without actually running the script.
Is there a way I can run the script without echoing it back.
Thanks
<?php
define('VERIFY_TOKEN', 'abc');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' && $_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
}
else if ($method == 'POST') {
echo '
<script type="text/javascript" src="parse-1.4.2.min.js"></script>
<script type="text/javascript">
Parse.initialize("ID1", "ID2");
var TestObject = Parse.Object.extend("Test");
var testObject = new TestObject();
testObject.set("key", "post");
testObject.save();
</script>';
}
?>

you can try like this
<?php else if ($method == 'POST') {?>
<script type="text/javascript" src="parse-1.4.2.min.js"></script>
<script type="text/javascript">
Parse.initialize("ID1", "ID2");
var TestObject = Parse.Object.extend("Test");
var testObject = new TestObject();
testObject.set("key", "post");
testObject.save();
</script>
<?php }
?>
else i don't think there is any other way

When your browser receives the response, it's expecting proper HTML (and two <script> tags are not proper HTML). Try wrapping your response in some minimal HTML:
echo '
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="parse-1.4.2.min.js"></script>
<script type="text/javascript">
Parse.initialize("ID1", "ID2");
var TestObject = Parse.Object.extend("Test");
var testObject = new TestObject();
testObject.set("key", "post");
testObject.save();
</script>
</head>
<body>
</body>
</html>';
}

Turns out that I can't really do that since javascript needs browser. And since there is only php file I can't make it work with js so I switched to all php.

Related

How to set php varible set in php and get filenames fromfolder

how do i get a list of all the filenames of files in C:\xampp\htdocs\dump\uploads in php varible them get the value of php varible in js
Serverside
Read the files.
$files = [];
if ($handle = opendir('.')) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
$files[] = $entry;
}
}
closedir($handle);
}
Render the page and echo $files in script tag. like below:
<script type="text/javascript">
const files = JSON.parse(<?php echo "'".json_encode($files)."'"; ?>);
console.log('myFiles', files);
</script>
To pass a variable from PHP to JS
First you need to know that PHP is rendered on server side; However JS is executed on client side; So a way to send vars from PHP to JS is using JSON
<!-- In your file of PHP you have: -->
<!-- some code of php to generate variable of all your files... -->
<?php $files = ['dir1','file1.txt','img.jpg']; ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<!-- here inside the same file you have your script js -->
<script type="text/javascript">
// call your variable with format JSON
var filesJSON = <?php echo "'".json_encode($files)."'"; ?>;
console.log(JSON.parse(filesJSON)); //['dir1', 'file1.txt', 'img.jpg']
</script>
</body>
</html>

How to execute a JS function which is inside PHP tags?

I have this below code in a file named test.php, whose task is to create a JSON object and transfer it to a function in JS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if($row) {
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
var msg = {$encodedJSON};
var ThunkableWebviewerExtension = {
postMessage: function (message) {
if (window.ReactNativeWebView) {
window.ReactNativeWebView.postMessage(message);
} else {
window.parent.postMessage(message, '*');'
}
}
};
ThunkableWebviewerExtension.postMessage(msg);
alert(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>
I have this piece of script, but I can only write it inside PHP - because the value the function requires, is stored in a PHP variable. All it should do is fetch the PHP's encodedJSON variable's value and store it in a local JS variable msg. Then, I created a function whose task is to POST a message, and called it next. All this worked perfectly when run in a separate HTML file, in which JS was written individually.
What should I do, to make the JS piece of code run inside PHP code? Thanks!
Given that $myjson contains the json string in php, then
var msg = {$myJSON};
to understand better above code is equivalent to:
var msg = JSON.parse('{$myJSON}')
is the way to convert it to js object from php variable.
Please see comments in the code for further help.
Please run below code and see how console.log is printing the json object:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Payment Receipt</title>
</head>
<body>
<?php
//started with hard coded data to show a working copy paste example
$row = array('date'=>'09-Oct-2020','txnid'=>1234,'atomid'=>456,'amount'=>21345);
if($row) {
$obj = new stdclass(); //op should add this to avoid warning
$obj->txndate = $row['date'];
$obj->txnid = $row['txnid'];
$obj->atomid = $row['atomid'];
$obj->amount = $row['amount'];
$myJSON = json_encode($obj);
//to see the json encode value in php
//var_dump($myJSON);
//this is not needed in op code
//$encodedJSON = json_encode($myJSON); //final variable in PHP to pass to below function.
//JS begins here
echo <<<JS001
<script type="text/javascript">
//php json string is converted to js object here
var msg = {$myJSON};
//see msg object printed in console
console.log(msg);
</script>
JS001;
} else {
echo 'Incorrect ID';
}
?>
</body>
</html>

Request value with JavaScript and show it on php file

I want to make something like this in order to deliver a JSON:
<?php
header("Content-Type:application/json");
require "data.php";
if(!empty($_GET['name']))
{
$name=$_GET['name'];
$price =$_GET['value'];
if(empty($price))
{
response(200,"Product Not Found",NULL);
}
else
{
response(200,"Product Found",$price);
}
}
else
{
response(400,"Invalid Request",NULL);
}
function response($status,$status_message,$data)
{
header("HTTP/1.1 ".$status_message);
$response['status']=$status;
$response['status_message']=$status_message;
$response['data']=$data;
$json_response = json_encode($response);
echo $json_response;
}
The "value" on the data.php file is found by a JavaScript like this:
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
</script>
But I don't know how to pass it from the JavaScript variable to the $price variable in this php file... could you help me?
As Andrew suggests in his comment, you can use Ajax to get the data from your PHP-Script:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <!-- add jQuery for easy AJAX functions -->
<script src='/web3.min.js'></script>
<script type='text/javascript'>
var web3 = new Web3(new Web3.providers.HttpProvider('https://example.com'));
var value = web3.xxx.getValue('xxxx');
$.get("/path/to/file.php?name=&value="+value, funtion(data) { // get data from PHP-Script
data = JSON.parse(data);
if (data.status_message === "Product Found") // if a product was found, set "price" to the price
var price = data.data
});
</script>

Correct way to set cookie from jQuery and read from php

I've tried to read the cookie values in PHP that are set via jQuery. But it's not read in first time page load. But I saw it's already set by the jQuery and can read the same value from the jquery.
When trying to read that cookie value from PHP it's not display the value when page rendered first time. But again refresh the page it's give the value from php.(I need to refresh page 2 time to get the correct value)
I used both head tag and onload method to place the setCookie() function. But result was same.
I used this jQuery library to write cookie.
Here's code I used to read and write the cookie.
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
body{
background: #666666;
}
</style>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.cookie.js" type="text/javascript">/script>
<script>
setCookie();
function setCookie() {
console.log('on Load');
var data_spl = $(location).attr('href').split('#?camlist=')[1];
if (data_spl != undefined) {
var len = data_spl.split(',').length;
$.cookie("len", len);
console.log($.cookie("len"));
} else {
console.log('undefined');
}
}
</script>
</head>
<body>
<?php
for ($i = 0; $i < 100; $i++) {
echo "<script>console.log('START');</script>";
echo "<script>console.log('" . $_COOKIE['len'] . "');</script>";
echo $_COOKIE['len'];
echo "<script>console.log('END');</script>";
}
echo "WIDTH & HEIGHT :" . $_SESSION['width_x'] . "-" . $_SESSION['height_y'];
?>
</body>
</html>
EDITED:
I used another php page to set session value that are came from java script and call that page via jQuery like shown in bellow.
var len = $(location).attr('href').split('#?data=')[1].split(',').length;
$.post('set_session.php', {params: len}, function (retparams) {
if (retparams.has) {
console.log('sucessfuly sent the paramlen!');
} else {
alert("can't read camarauids for grid making");
}
}, 'retparams');
set_session.php
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
$_SESSION['urllen'] = 0;
}
if (isset($_POST['params'])) {
$_SESSION['urllen'] = $_POST['params'];
echo json_encode(array('retparams' => 'has'));
echo json_encode(array('datalen' => $_SESSION['urllen']));
} else {
echo json_encode(array('retparams' => 'error'));
}
?>
Then I try to read the session value ($_SESSION['urllen']) from index.php page. But it's also same as the above.(I need to refresh page one more time to get the correct value that are set from the jQuery post function.)
As already mentioned in the comment section your Cookie isn't present on first page Load because it isn't set yet. (If you set the Cookie directly in JS or via AJAX is essentially the same)
The only way to effectively get the Information is ether with a page reload or a redirect or via AJAX request (depends on what fits your needs). For Example you could redirect in JS after the Cookie got set with:
//set your cookie in JS
window.location = location.host;
more Information about JS redirects can be found here or you search your way thru Google.
You can also set your Cookie in PHP and redirect with the header() function:
header('Location: http://www.example.com/');
More Information for PHP redirects can be found here or on Google ;)
You could check this with ajax.
Here is a simple example:
<?php
if(isset($_GET["checkIfLoggedIn"]) && boolval($_GET["checkIfLoggedIn"]) === true) {
header("Content-Type: text/json");
die(json_encode(array("isLoggedIn" => $_COOKIE["isLoggedIn"])));
exit();
} else {
var_dump($_COOKIE);
}
?>
<html>
<head>
<script type="text/javascript" src="jquery-3.1.1.min.js"></script>
<script type="text/javascript" src="js.cookie.js"></script>
</head>
<body>
<script type="text/javascript">
function checkIfLoggedIn() {
console.log("checking...");
jQuery.post("?checkIfLoggedIn=1", function(data) {
if(data.isLoggedIn == true) {
alert("Logged im.");
} else {
alert("NOT logged in!");
}
});
}
</script>
Set logged in to true<br/>
Set logged in to false
</body>
</html>

Using Javascript to access PHP variables

How can I access PHP variables from Javascript where the PHP code exists in a separate file?
The code I have is:
<?php
$res = "OK";
?>
<html>
<head>
<script type="text/javascript">
function myFunc()
{
res = <?php echo json_encode($res); ?>;
console.log("res = " + res);
}
</script>
</head>
<body>
<button onclick="myFunc()">Click</button>
</body>
</html>
Now, if I were to move my php code to a separate file called a.php, how can I access $res? Assume I am calling a.php with a GET request (XMLHttpRequest object).
Try-
res = "<?php echo json_encode($res); ?>";

Categories

Resources