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!
Related
I'm learning the Ajax method with jQuery. I've a simple code here. It's to load data from a csv file by jQuery Ajax method, and put it into an array for further use. But it seems the array lost outside of the Ajax function even I do make the array global in the first place.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
var db=[];
$(document).ready(function(){
$.ajax({
url: 'loaddata.php',
success: function(data){
var arr = data.split('|');
for(var i=0; i<arr.length; i++){
var miniArr = arr[i].split(',');
db.push(miniArr);
}
printTest(); //work here
}
});
printTest(); //not working and collapse here
});
function printTest(){
document.getElementById('test').innerHTML += db;
}
</script>
</head>
<body>
<div id="test" />
</body>
</html> `
My php file should be fine,
<?php
$database = file('database');
foreach($database as $item){
if ($item===end($database))
echo $item;
else
echo $item.'|';
}
?>
Thanks in advance.
Your second printTest() is where the .ajax parameters go, so there's a syntax error there. The reason the first call works is because it's inside the success callback, and since AJAX is asynchronous this is called when the call has completed.
If you put the printTest() call after the AJAX call, it will be called immediately after the AJAX call has started, not waiting until it completes, due to async.
You can't call your second printTest() here.
And for the record, try to use JSON to retrieve your datas, it's way much easier.
Is it possible to change this to display an element loaded later on in the document:
function tracksinfox_{$page_trackid}()
{
document.getElementById('tracksinfoxshow_{$page_trackid}').innerHTML = 'get stuff here';
}
In the place of "get stuff here", I would like to display a div by id, but the div is created later in the page load using PHP.
with jQuery's on(), you can add event handlers to elements which are added later to the document. http://api.jquery.com/on/
you can make the function perform after document ready by document.onreadystatechange:
document.onreadystatechange=function() {
if(document.readyState == 'complete'){
tracksinfox_{$page_trackid}();
}
}
or just use window.onload event simply;
window.onload = tracksinfox_{$page_trackid};
but there's one more thing you have to know, if you like to perform two or more function after document ready, you can do it like this:
run_after_document_ready( tracksinfox_{$page_trackid} );
run_after_document_ready( somethingelse );
run_after_document_ready( somethingelse2 );
function run_after_document_ready( callback ) {
callback_saver = window.onload;
window.onload = function (){
if ( typeof callback_saver == "function" ){
callback_saver();
}
callback();
}
}
or just use the jQuery
$(document).ready(tracksinfox_{$page_trackid});
$(document).ready(somethiselse);
$(document).ready(somethiselse2);
NOTICE: window.onload has a little different with document.ready, for more information, you should to find the documents about window.onload, document.onreadystatechange and the jquery document ready.
How about using jQuery and doing something like the following. It establishes a callback method that will be called when a new element with id="info" is added to the DOM, then it adds a new DIV with id="info", which causes the callback function to be executed. The callback function unregisters itself (thus it will only ever be called once), then sets the update-me DIV's text based on the new DIV.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="update-me">I will be updated.</div>
<script language="javascript">
jQuery(function ($) {
$("body").on("DOMNodeInserted", "#info", function(e){
$("body").off("DOMNodeInserted", "#info");
$("#update-me").text( $(e.target).text() );
});
$("body").append("<div id='info'>I have changed.</div>");
});
</script>
</body>
</html>
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();
})
I have php file, in this file I have this code:
<script language="JavaScript" type="text/javascript" src="jquery.js"></script>
<script language="JavaScript">
$(document).ready( function () {
var myvar = <?php echo json_encode($myvar); ?> ;
});
</script>
<script language="JavaScript" type="text/javascript" src="costum.js"> </script>
and in costum.js file I have code:
$(document).ready( function () {
alert(myvar );
});
this not working, error consol returns "myvar is undefined"
if in php file I write this (that is, without "document.ready")
<script language="JavaScript">
var myvar = <?php echo json_encode($myvar); ?> ;
</script>
in costum.js file, code alredy is working. Please tell why this happened?
try with
<script>
var myvar;
$(document).ready( function () {
myvar = <?php echo json_encode($myvar); ?> ;
});
</script>
your variable has to be declared as global (or in other words, in the outer scope) to be viewed from both document.ready functions.
As a side note language attribute is not necessary. Even type is not necessary (if you're using html5 doctype)
Your myvar is in the local scope of the ready-function. Move the var declaration outside to make it global and available to the other script.
However, as you just assign to a variable, you won't need to wait for DOMready anyway. Just use
<script type="text/javascript">
var myvar = <?php echo json_encode($myvar); ?>;
</script>
BTW, the language attribute is deprecated.
local variable inside the function is only visible in the function scope.
when you declare variable in the global scope, then it is the global variable.
You could expose it to global scope by:
$(document).ready( function () {
var myvar = <?php echo json_encode($myvar); ?>;
window['myvar'] = myvar;
});
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>