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.
Related
I want the value I get in $re variale to use in a Javascript function variable var $r:
<?php
include('functions.php');
if(!isLogIn()){<br>
$_SESSION['msg']="You must log in first";
header('location:login.php');
}
$orderid=$_GET['id'];
$Maxid=mysqli_query($db,"sql query here");
$result=mysqli_fetch_assoc($MAxid);
$re=$result['printst'];
<script type="text/javascript">
function print(){
var $r=<?php $re;?>;
if($r==1){
window.print();}
else{
return false}
you can use echo function to inject php result into javascript as follow:
include('functions.php');
if(!isLogIn()){
$_SESSION['msg']="You must log in first";
header('location:login.php');
}
$orderid=$_GET['id'];
$Maxid=mysqli_query($db,"sql query here");
$result=mysqli_fetch_assoc($MAxid);
$re=$result['printst'];
//assuming this is the javascript part
function print(){
var $r=<?php echo $re;?>;
if($r==1){
window.print();}
else{
return false}
You need to pass that variable to your JS file like this
<script>
var $r= '<?php echo $re; ?>';
</script>
// your js file use that variable
function print(){
if($r==1){
window.print();}
else{
return false}
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>
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>
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 );
?>
Framework: CodeIgniter 2.0
I am trying access session data setup in model from view.
This is the code I am testing in view:
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
var num_records = '$this->session->userdata("number_Of_Records_session")';
alert(num_records);
if(elem.value.length > 0){
alert(helperMsg);
elem.focus();
return false;
}else{
window.location="/path/";
}
return true;
}
</script>
When I use PHP code I could retrieve the value from session and display it.
<?php
$numberOfRecords_session =
$this->session->userdata('number_Of_Records_session');
echo "Num records:".$numberOfRecords_session;
?>
But in javascript this line
var num_records = '$this->session->userdata("number_Of_Records_session")';
print this message in alert box:
$this->session->userdata("number_Of_Records_session")
Any advice to retrieve value in javascript and show it alert box is appreciate.
You cannot access your session (stored on server) from JavaScript (executed on client)
So you have to declare a JavaScript variable and define it with PHP
Like this you're defining a string:
...
<script>
var sessionValue = "<?php echo $this->session->userdata('number_Of_Records_session');?>";
</script>
...
If you're sure that there is always a number you could remove the " above, which are defining the variable as string.
If you're not sure about the datatype of the sessionValue you should use parseInt(string,radix):
...
<script>
var sessionValue = parseInt("<?php echo $this->session->userdata('number_Of_Records_session');?>");
if(sessionValue == "NaN") sessionValue = 0;
</script>
...