I am passing a variable via the URL as var=5 to urlrun.php (like urlrun.php?var=5). There is a JavaScript function called testrun in urlrun.php.
Is there a way to call that JavaScript function depending on the value of that variable (var) passed through the URL?
For example, if($_GET['var']==5), I need to call that JavaScript function.
Put this somewhere:
<?php if($_GET['var'] == 5) { ?>
<script type="text/javascript">
testrun();
</script>
<?php } ?>
Related
how to set ajax result to global variable PHP
This is index.php Code
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function()
{
function getSession()
{
$.post("getSession.php", { },
function(result){
$("#div1").text(result);
}
);
}
setInterval(getSession, 1000); // 1000 = 1 second
getSession();
}
);
</script>
<body>
<div id="div1"></div>
</body>
</html>
And this is getSession.php Code
<?php
session_start();
$_SESSION["time"] = date("Y-m-d H:i:s");
echo $_SESSION["time"];
?>
how to set <div id="div1"></div> to global variable php like
$answer = <div id="div1"></div>
Or how to set ajax result to global variable PHP
This is not possible. You can't assign javascript results to server side code.
You can make assignments on the server when the ajax request executes on the server though.
A straight JavaScript variable to PHP variable assignment is not possible
Global variables need to be set when the preprocessor (PHP) parses the PHP file. You can send variables and values to PHP script, but only after the main page has been parsed and the script has been executed.
You can have an AJAX call made to a PHP script, and have the script return a variable/value pair as JSON data and have that data managed.
Example: page1.php loads up with your JavaScript. AJAX request sent to page2.php; page2.php processes the request, then spits out an answer as JSON data. JSON data is parsed by page1.php and data is pushed in the div1 <div>.
Lets say
var wanted = whatever....;
windows.wanted = wanted ;
try it
I am using Codeigniter and want to separate the JavaScript from the view files, but many of the JavaScript functions need data from controller (it depended on values from controllers)
ex:
controller :
function show_post() {
$data['data'] = $this -> get_data(); //some data
$data['random_key'] = $this -> generate_random(); //returns a random value
$this -> load -> view('posts', $data);
}
and in view I have a js function:
<script>
function get_random() {
return "<?= $random_key; ?>";
}
</script>
How can I save this javascript snippets to some other file say posts.js? If I did something like this then I cannot use php variables inside the script.
What is the best way to achieve this in terms of Performance and Maintenance?
Some other ways I do not want to follow :
Save the JS file as a PHP file and then pass the values to that file
Declare all those variable in the view file globally
you could pass the value as parameter to your js function, like
post.js
function get_random( param ) {
//use param here
}
//OR
function get_random( ) {
//get arguments like
var firstArg = arguments[0];
}
view.php
//include post.js file
//call the js function passing php variable as parameter, like
get_random("<?php echo $random_key; ?>");
did you mean something like this
One way to do it by using hidden fields, in your case store them in hidden field like:
<input type="hidden" value="<?php echo $random_key;?>" id="randomkey">
and access them in js by using ID like:
$("#randomkey").val();
In this way you can use controller paramter in your js.
Help it will help you!
the simplest method is that , define php variables as js variable in your view file
<script type="text/javascript">
var random_key = <?= $random_key; ?>;
</script>
then you can use that variable in your example.js file
Is there anyway I can use a php variable in the JQuery script?
Example:
PHP variable: $sr2
Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')
How can I make it so the variable is valid in that JQuery part?
Thanks
PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.
<script type="text/javascript">
var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>
or retrieve the value via an AJAX call, which means you're basically creating a webservice.
What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.
<script type="text/javascript">
<?php
$phpVar = "foo";
echo "var phpVariable = '{$phpVar}';";
?>
</script>
Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -
<script type="text/javascript">
var phpVariable = 'foo';
</script>
Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -
$("div."+phpVariable);
That will retrieve us any <div> element with a foo class -
<div class="foo"></div>
Assuming your jQuery is in the same file:
... $('#a2_bottom_<?php echo $sr2 ?>') ...
You could output it as part of the page in a script tag... i.e.
<script type="text/javascript">
<?php
echo "var sr2 = \"" . $sr2 . "\"";
?>
</script>
Then your jQuery line would be able to access it:
$('#a2_bottom_' + sr2)
I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.
I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>