I am trying to call a javascript function from php. According to all of the examples I have been looking at the following should work but it doesn't. Why not?
<?php
echo "function test";
echo '<script type="text/javascript"> run(); </script>';
?>
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
</script>
</html>
Your html is invalid. You're missing some tags.
And you need to call the function after it has been declared, like this
<html>
<head>
<title></title>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "run();";
?>
</script>
</head>
<body>
</body>
</html>
In this case you can place the run before the method declaration, but as soon as you wrap the method call inside another script tag, the script tag has to be after the method declaration.
Try yourself http://jsfiddle.net/qdwXv/
the function must declare before use
it should be
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "function test";
echo run(); ;
?>
</script>
</html>
As others have suggested, the function needs to be declared first. But, if you need to echo out the JavaScript from PHP first, you can either store it in a PHP variable to echo out later, or have your code wait for the dom to finish loading first...
document.ready = function() {
run()
}
If you're using jQuery or another framework, they probalby have a better way of doing that... In jQuery:
$(function(){
run();
})
Related
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
I am getting the following error from the chrome developer tool
Uncaught ReferenceError: searchRequests is not defined
searchProcess.php:174 onclick.
When I click on hyperlink produced from engine.php, I don't get the alert from the searchRequests function. I'm not sure what the problem is, I appreciate any advice given. Here is my code:
searchProcess.php
<?php
include '../include/engine.php';
?>
<html>
<head>
<script type="text/javascript" src="../jQuery.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
var instrID;
var cat;
$(window).load(function(){
});
var newheight = $(window).height();
function searchRequests(instr)
{
alert("in searchResults");
instrID = instr;
alert(instrID);
}
});
</script>
</head>
<body>
<?php
drawSearchResults($var1, $var2, $var3, $var3, $var4);
?>
</body>
</html>
engine.php
<?php
function drawSearchResults($var1, $var2, $var3, $var4, $var5)
{
while($row = mysql_fetch_assoc($result))
{
echo ("<tr>");
echo ("<td id='InstrumentID'><a href='javascript:void(0);' onclick='searchRequests($row[InstrumentID])'>$row[InstrumentID]</a></td>");
echo ("</tr>");
}
?>
The problem is that the function searchRequests is not in scope outside of the $(document).ready(). Move it outside of $(document).ready().
In general you shouldn't embed your javascript in the html. Much nicer:
$('#InstrumentID a').click(someFunctionThatIsInScope);
And you can put that code in the $(document).ready() block. In addition the function you call will get an event object that you can use to get any values you might need from the markup.
Because it is private. You are hiding it from global scope since it is inside the ready function. Do not use inline event handlers, use on() to attach events!
I'm grabbing some information out of a database and passing it to some JavaScript using json_encode(). The line: var row_data = <?php echo $month_stats ?>; is dumping the object into the JS.
But now I want to abstract my JS into an external file, so suddenly I can't just echo the contents of the object into the JS since PHP won't have any presence there.
So I need to somehow (via AJAX?) send the PHP object $month_stats directly to the JS so that it can use the information independently of PHP, but I'm not sure how this is implemented. Any pointers?
<?php
include 'db.php';
$month_stats = generate_monthly_count_stats($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var row_data = <?php echo $month_stats ?>;
console.log(row_data);
</script>
</head>
<body>
</body>
</html>
You can simply echo the variable and access it in an external file:
<script type="text/javascript">var row_data = <?php echo $month_stats ?>;</script>
<script type="text/javascript" src="external.js"></script>
row_data is now a global variable, so you can access it in the external.js. However it is better to add it to a namespace if you have lots of other variables..
You can create some javascripn function in .js file
myFunction(obj) {
console.log(obj);
}
in your php file you can do that:
<script type="text/javascript">
myFunction(<?php echo $month_stats ?>);
</script>
When you put the JS into an external file, make it a function with one parameter.
In your .js file:
function logRowData(var1)
{
console.log(var1);
}
In your .php file:
<head>
<?php
include(filename.js);
?>
</head>
To log the stats, you can call in the php file.
<script type="text/javascript">
logRowData($month_stats)
</script>
More info on JS Functions
If you reference the variable row_data in your included Javascript file, it should work, as you are declaring that in the global scope. Here's one article for reference: http://snook.ca/archives/javascript/global_variable
I have a problem how to pass for example $example=1; variable to this jquery like a value in bracket where is 20, 40, 60.....:
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(20);
$("#pb2").progressBar(40);
$("#pb3").progressBar(60);
$("#pb4").progressBar(70);
$("#pb5").progressBar(100);
$("#pb6").progressBar(100);
});
</script>
The main problem is that I want to example string have value from database, so that's why I need to make it outside of script.
If this code is in your .php page...
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $pb1 ;?>);
$("#pb2").progressBar(<?php echo $pb2 ;?>);
$("#pb3").progressBar(<?php echo $pb3 ;?>);
$("#pb4").progressBar(<?php echo $pb4 ;?>);
$("#pb5").progressBar(<?php echo $pb5 ;?>);
$("#pb6").progressBar(<?php echo $pb6 ;?>);
});
</script>
Where $pb1,$pb2,$pb3,$pb4,$pb5,$pb6 are Integers ..
This is simple:
<?php
//Insert your code to generate the values to $example
$example = ...
?>
// and here is your JS with php code inside it
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $example; ?>);
$("#pb2").progressBar(<?php echo $example1; ?>);
$("#pb3").progressBar(<?php echo $example2; ?>);
$("#pb4").progressBar(<?php echo $example3; ?>);
$("#pb5").progressBar(<?php echo $example4; ?>);
$("#pb6").progressBar(<?php echo $example5; ?>);
});
</script>
I hope it helps! Good Luck!
If you meant to pass php variable to client to dynamically replace numbers in jquery you can use like code in below
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo example; ?>);
});
</script>
First off, having it in your database does not mean you cannot do so in the script. There are in fact several ways to do that. You could have your javascript file be php that generates javascript instead of html, or perhaps easier: you could use inline javscript. However, if you do want to keep the two separated it is still possible:
[..]
<script type='text/javascript'>var percentageDone = <?php echo intval($example) ?>;</script>
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(percentageDone);
});
</script>
[..]
Working on the same page as before,but now I'm using it as a playground for messing around with jQuery so I can learn it for my'boss.' Unfortunately, I can't get the javascript in this file to execute, let alone give me a warning. All of the PHP and HTML on the page work perfectly, it's just the script that's the issue. What am I doing wrong?
<?php
if( isset($_POST['mushu']) )
{
playAnimation();
clickInc();
}
function playAnimation()
{
echo "<img src='cocktail-kitten.jpg' id='blur'>";
}
function clickInc()
{
$count = glob("click*.txt");
$clicks = file($count[0]);
$clicks[0]+=1;
$fp = fopen($count[0], "w") or die("Can't open file");
fputs($fp, $clicks[0]);
fclose($fp);
echo $clicks[0];
}
?>
<html>
<head>
<title>Adobe Kitten</title>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>"
method="post">
<input type="submit"
value="Let's see what Mushu is up to."
name="mushu">
</form>
<script>
$(document).ready( function()
{
$('#blur').click( function()
{
$(this).blur( function()
{
alert('Handler for .blur() called.');
});
});
});
</script>
</body>
</html>
You're calling playAnimation() before your <html> tag, so your html is malformed. JQuery probably can't find the #blur element because it's not actually inside your web page, much less within the <body>.
Move the if( isset($_POST['mushu'])) ... block of code somewhere after the body tag.
Check FireBug's console, or FireFox' Error Console.
Verify that jquery.js is being included, and check your error console.
Otherwise, a few obvious errors which may or may not contribute to your javascript problems:
You're outputting HTML in playAnimation() before your opening HTML tag
Your form's action attribute is blank - you need <?= or <?php echo
Your script tags should read <script type="text/javascript">
Like Scott said you need to echo the div in the actual body of the page. Also, I think another problem you have is you're calling .blur which is the event when your mouse leaves the image. Since you have functions like animate I think you might actually be looking for .fade http://api.jquery.com/fadeOut/. Try something like:
<script>
$(document).ready( function()
{
$('#blur').click( function()
{
$(this).fadeOut('slow', function()
{
alert('All Done');
});
});
});
</script>