Request value with JavaScript and show it on php file - javascript

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>

Related

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>

How to concatenate multiple php variables within Javascript

Hello I am trying to utilize geomapping within in my website and I'm having trouble dynamically pulling the address for a restaurant and putting it into my javascript. I am using the get method to pull the restaurant_id from the url and then use this to pull the restaurant's complete address. This is the line of code I am having trouble with (var destinationAddress):
$con=mysqli_connect("root","");
$rest_id2=$_GET['id'];
$rest_id=(int)$rest_id2;
$sql="SELECT * from restaurant WHERE restaurant_id='".$rest_id."'";
$result=mysqli_query($con,$sql);
$rows=mysqli_fetch_assoc($result);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
</script>
</head>
....
Any one know see what I am doing wrong here?
Make your life easier: build the destination address outside of the template:
$rows=mysqli_fetch_assoc($result);
if( $rows !== NULL )
{
$destinationAddress = "{$rows['address']}, {$rows['city']}, {$rows['state']}, {$rows['zip']}";
}
else
{
// no rows! (anomaly)
$destinationAddress = "no destination address available";
}
// due to the way you'll later inject the variable
// into JavaScript code double quotes must be escaped
$destinationAddress = str_replace( '"', '\"', $destinationAddress );
Then simply
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?=$destionationAddress?>";
} );
Try adding the commas and spaces.
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
becase u forgot to close the function }) , try
<script>
$(document).ready(function() {
//exit early if no geolocation
if(!navigator.geolocation) return;
var destinationAddress = "<?php echo $rows['address'].$rows['city'].$rows['state'].$rows['zip']; ?>";
})
</script>

How to return JS value using AJAX

I have a code like this
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_projectName.php',{id:value},function(data)
{
.....
.....
if(condition here){}
});
});
});
I need to check a condition according to the value returned from get_projectName.php. Let get_projectName.php have $abc = 1; and according to this value I need to use if condition.
Your jquery condition will be totally depend on the type of data returned from the php function. Let's check for the example:-
Example 1 :-
If your php code is :-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = 1; // as you said
}
echo $data;
?>
Then jquery will be:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script><!-- library needed-->
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){ // you need to check that it is working or not because i don't know from where it is coming
var value = $('#myHref').val(); // same as above check yourself.
$.get('get_sales_price.php','',function(data){
if(data ==1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Example 2:-
But if your php code is like below:-
<?php
if(isset($_GET['id'])){ // check id coming from `ajax` or not
$data = Array('a'=>1,'b'=>2);
}
echo json_encode($data);
?>
then jquery will be like below:-
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type = "text/javascript">
$(document).ready(function() {
$('#myHref').change(function(){
var value = $('#myHref').val();
$.get('get_sales_price.php','',function(data){
var newdata = $.parseJSON(data);//parse JSON
if(newdata.a ==1 && newdata.b !== 1){
alert('hello');
}else{
alert('hi');
}
});
});
});
</script>
Note:- these are simple examples, but conditions will vary in jquery, based on returned response from php. thanks.
Forgot the .done
$.get('get_projectName.php',
{id:value}
).done(function(data) {
console.log(data)
var data2 = JSON.parse(data);
if(data2.abc === 1)
{
//Do something
}else{
//Else Do something
}
});
You can write code as below -
//At javscript end
$.get( "get_projectName.php", function( data ) {
if(data == "1"){
// do your work
}
});
// At php end
<?php
$abc = 1;
echo $abc;
?>
Hope this will help you.
In main-php-file On change of value, Fetch the value pass it a php file sub-php-file via ajax
In sub-php-file, echo the ouput in json format
Retrieve the output and do the calculation
jQuery library, if never included
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
ajax
<script type="text/javascript">
$(document).ready(function(){
$('#myHref').on('change', function(){
var value = $('#myHref').val();
$.ajax({
type: "POST",
url: "get_projectName.php",
data: { id:value },
dataType: "json",
success: function(theResponse) {
var abc = theResponse['abc'];
if (abc == 1) {
//Do something
} else {
//Else Do something
}
}
});
});
});
</script>
get_projectName.php
<?php
$id = isset($_POST['id']) ? $_POST['id'] : '';
$ReturnArray['abc'] = 1;
echo json_encode( $ReturnArray );
?>

Running javascript inside php without echo

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.

Php calling javascript function

I can do that? Im trying to call a javascript function after conditional php "if"
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_get['id']){
echo "<script>functioncall({$_get['id']});</script>";
}
?>
Use $_GET instead of $_get in php condition, I have corrected some of the errors like script tag script type, and PHP $_GET
<script type="text/javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(isset($_GET['id'])){
echo "<script>functioncall('{$_GET['id']}');</script>";
}
?>
Or just using JS ?
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
And do like...
var id = getQueryVariable('id');
if(id) {
alert(id);
}
Credit : http://css-tricks.com/snippets/javascript/get-url-variables/
As Quentin said you are exposed to XSS attacks. Don't ever put anything into your page from GET variables (url variables) - 'id' in your case.
Anyways, if you want to call a function based on a php condition, you can do something like this:
<script type="text\javascript">
functioncall = (function(id){
alert(id);
});
</script>
<?php
if(condition-goes-here){
?>
<script type="text/javascript">
functioncall(<?php echo 'Put in your php data' ?>);
</script>
<?php } ?>
I haven't checked it, hope it should work. If your condition returns false, your function call will not be put into your page.
It's not a good practice though.

Categories

Resources