jQuery eval of ajax inline script not throwing errors - php

Debugging Ajax code with Firebug
This question is quite similar, though old and without real answers.
I'm currently putting together an app that has scripts that get loaded in with an ajax request.
An example:
var main = _main.get();
main.load( someurl );
Where someurl is a page that contains an inline script element:
<script type="text/javascript">
$(document).ready( function(){
var activities = new activities();
activities.init();
});
</script>
jQuery will do a line by line eval of js that lives in inline script tags. The problem is, I get no errors or any information whatsoever in firebug when something goes awry.
Does anyone have a good solution for this? Or a better practice for loading pages which contain javascript functionality?
Edit: A little progress... so at the top of the page that is being loaded in via ajax, I have another script that was being included like this:
<script type="text/javascript" src="javascript/pages/activities.js"></script>
When I moved the inline $(document).ready() code in the page to the end of this included file, instead, syntax errors were now properly getting thrown.
As an aside, I threw a console.log() into the inline script tag, and it was being logged just fine. I also tried removing the $(document).ready() altogether, and also switching it out for a $(window).load() event. No difference. May have something to do with the inline scripts dependency on the included activities.js, I guess.
:: shakes head :: javascript can be a nightmare.

I suggest using http://api.jquery.com/jQuery.getScript/ for lazy loading Javascript or for getting html content http://api.jquery.com/load/
respectively:
$.getScript('path/to/file.js');
.. and
$('#content-wrap').load('path/to/html/file.html');
Both of theses methods are wraps around http://api.jquery.com/jQuery.ajax/ and have optional callback function parameters.

Related

Script-Tags generated by Javascript do not work?

I'm creating a webpage using php, mysql, html5&css3 and javascript (ajax).
To improve the performance, i decided to use AJAX to get only the content div (<div id="content">) that actually changes, i dont want to reload the whole code all the time. That works as follows: after having received the new content from a php-file, javascript does the following:
document.getElementById("content").innerHTML = new_content;
After that, the new_content is well displayed...
Now the Problem:
In the new_content, i have some javascript, too, e.g.:
<script type="text/javascript" lang="JAVASCRIPT">
alert('Hello!');
...
</script>
Unfortunately, when inserting it in the div, it isn't executed at all...when calling the php-file "naturally", the javascript code does what i want it to do, so there's no error in it.
Thanks in advance
EDIT: Problem is solved, i included jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
and used $("#content").html(new_content); in javascript as mentioned below.
Use jQuery's $.html. It will automatically execute scripts for you.
$("#content").html(new_content);
Indeed, by default script execution is disabled when just replacing HTML - makes sense if you look at it. You should really consider using a library like jQuery or Mootools to abstract issues like this away.
If you look at Mootools' Request.HTML implementation you'll see it has its evalScripts option defaulting to true, which later on during the call results in this bit of code being executed:
response.html = text.stripScripts(function(script){
response.javascript = script;
});
...
if (options.evalScripts) Browser.exec(response.javascript);
However this probably won't work on its own without Mootools' other bits of browser-abstracting code in place, so yes I'd definitely recommend including a library on your project.

Is there a way to get Joomla module position and functions with jquery .ready function?

I am trying to pass a
{loadposition grabber}
custom module position and module to delay it's operation after the document has loaded. I have loaded my jquery.js file and added this script.
<script type="text/javascript">
$(document).ready(function(){
$.get('{loadposition grabber}',
function(output) {
$('#grabberDiv').html(output).fadeIn(500);
});
});
</script>
With a...
<div id="grabberDiv">Testing grabberDiv</div>
In my body. What I am trying to figure out is if this is a problem in my code here or if it is simply impossible to do without altering my module.
Joomla!'s {loadposition aModulePosition} is meant for use in the body of an article and is replaced during page rendering by the CMS, ie. prior to the page being sent back to the browser.
So the browser (& therefore jQuery/Javascript) never sees an element called {loadposition grabber}.
It might be better to set the default CSS for the grabberDiv to display:none and then update your script to work with the correct element ID.

issue calling JavaScript function from PHP

basically I am trying to call a javascript function from my PHP and I am using code I know works in other situations however here is it not and I am at a loss as to why?
It may be something stupid as I have been staring at this screen for a long time :)
here is where I call the function:
if(isset($test_details['done_test'])){
echo "getting here";
echo "<SCRIPT LANGUAGE='javascript'>user_error();</SCRIPT>";
}
I successfully get 'getting here' printed however it does not call the JS function.
javascript function:
function user_error(){
document.write("working");
//alert("User has already taken this test. Your are being redirected...");
//setTimeout("window.location='home_student.php'",3000);
}
The commented it what I do eventually want it to do.
Could anyone please shed some light.
Many thanks,
#Crimson - Here is what I tried after your advice...still no luck.
javascript now:
$(document).ready(function () {
var done = "<?= $test_details['done_test'] ?>";
if(typeof done != 'undefined'){
$('WORKING').appendTo('#bodyArea'); // just to test
}
});
By echoing <script>...</script> with PHP, you are not going to get the browser run the JS function!
PHP only outputs the HTML file that you want to send to the browser. The browser then parses this HTML and does a multitude of things before the page is displayed to the user.
Next, the user interacts with the displayed page (or some other browser related event like 'onload' happens) and the attached JS gets called.
So, if there is some JS that you want to run at a certain time, say immediately after the browser has finished loading the page, you need to create JS in the HTML file such that there is a JS function which gets called at the page load event like this:
<body onload="/*do something here*/"> ... </body>
It is better to use JQuery or some other JS frmework to accomplish something like this though.
Are you sure the function is already defined? Perhaps you declared your function after making the function call.
Additionally, although it's not really going to matter here, the proper way to have a javascript script tag is.
<script type="text/javascript"></script>
i.e. not language="javascript"
Replace the line you call the JS function with this:
echo '<script type="text/javascript">window.onload = user_error </script>' ;
It should solve the problem. Because at the time you are calling user_error(), the function may not have been initialized by the browser. So you'll get an error since the function could not be found.
If the function is placed in an external .js file, it's very likely that you get this error, since the external file usually takes a while to be loaded. If the function deceleration is in the same file but after where you are calling it, same thing happens.

jquery effects are NOT working

I have some experience in PHP but not in JQuery that much.
My admin.php page has a div which has id named "table1" where content gets loaded via ajax:
document.getElementById("table1").innerHTML=xmlhttp.responseText;
xmlhttp gets data from sorgula1.php page which has some JQuery effects like highlighting table rows. When I'm trying to run the sorgula1.php alone, the highlighting works but when it is loaded via ajax to admin.php, highlighting and other JQuery effects are not working. I've tried everything to make it work but, I always failed.
For those of you who will ask me to remove the $(document).ready(function() statement, I'm informing you that it doesn't work.
Here is the sorgula.php code: sorgula1.php
please be specific about the answers guys.Thanx for all answers.
Maybe when you use innerHTML property, the javascript doesn't work. I think you can solve this problem by using jQuery load() function.
The problem is most likely that the elements loaded via ajax do not have the effects applied to them - have you tried calling the $("#myTable").tablesorter(); javascript (again) after the ajax response has been received and injected into the DOM?
Edit sorry it should probably be this code that you call:
$("tr").not(':first').hover(
function () {
$(this).css("background","yellow");
},
function () {
$(this).css("background","");
}
);
or use .live()
Try to rewrite your events to Live(). I would say that it doesn't work, because elements are loaded after the jQuery functions are registered. So try
$("tr").not(':first').live('hover',function(){ // CODE });

Why doesn't my <script> tag work from php file? (jQuery involved here too)

Here is what I am trying to accomplish. I have a form that uses jQuery to make an AJAX call to a PHP file. The PHP file interacts with a database, and then creates the page content to return as the AJAX response; i.e. this page content is written to a new window in the success function for the $.ajax call. As part of the page content returned by the PHP file, I have a straightforward HTML script tag that has a JavaScript file. Specifically:
<script type="text/javascript" src="pageControl.js"></script>
This is not echoed in the php (although I have tried that), it is just html. The pageControl.js is in the same directory as my php file that generates the content.
No matter what I try, I can't seem to get the pageControl.js file included or working in the resulting new window created in response to success in the AJAX call. I end up with errors like "Object expected" or variable not defined, leading me to believe the file is not getting included. If I copy the JavaScript directly into the PHPfile, rather than using the script tag with src, I can get it working.
Is there something I am missing here about scope resolution between calling file, php, and the jQuery AJAX? I am going to want to include javascript files this way in the future and would like to understand what I am doing wrong.
Hello again:
I have worked away at this issue, and still no luck. I am going to try and clarify what I am doing, and maybe that will bring something to mind. I am including some code as requested to help clarify things a bit.
Here is the sequence:
User selects some options, and clicks submit button on form.
The form button click is handled by jQuery code that looks like this:
$(document).ready(function() {
$("#runReport").click(function() {
var report = $("#report").val();
var program = $("#program").val();
var session = $("#session").val();
var students = $("#students").val();
var dataString = 'report=' +report+
'&program=' +program+
'&session=' +session+
'&students=' +students;
$.ajax({
type: "POST",
url: "process_report_request.php",
cache: false,
data: dataString,
success: function(pageContent) {
if (pageContent) {
$("#result_msg").addClass("successMsg")
.text("Report created.");
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
// open a new report window
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// add the report data itself returned from the AJAX call
reportWindow.document.write(pageContent);
reportWindow.document.close();
}
else {
$("#result_msg").addClass("failedMsg")
.text("Report creation failed.");
}
}
}); // end ajax call
// return false from click function to prevent normal submit handling
return false;
}); // end click call
}); // end ready call
This code performs an AJAX call to a PHP file (process_report_request.php) that creates the page content for the new window. This content is taken from a database and HTML. In the PHP file I want to include another javascript file in the head with javascript used in the new window. I am trying to include it as follows
<script src="/folder1/folder2/folder3/pageControl.js" type="text/javascript"></script>
Changed path folder names to protect the innocent :)
The pageControl.js file is actually in the same folder as the jQuery code file and the php file, but I am trying the full path just to be safe. I am also able to access the js file using the URL in the browser, and I can successfully include it in a static html test page using the script src tag.
After the javascript file is included in the php file, I have a call to one of its functions as follows (echo from php):
echo '<script type="text/javascript" language="javascript">writePageControls();</script>';
So, once the php file sends all the page content back to the AJAX call, then the new window is opened, and the returned content is written to it by the jQuery code above.
The writePageControls line is where I get the error "Error: Object expected" when I run the page. However, since the JavaScript works fine in both the static HTML page and when included "inline" in the PHP file, it is leading me to think this is a path issue of some kind.
Again, no matter what I try, my calls to the functions in the pageControls.js file do not work. If I put the contents of the pageControl.js file in the php file between script tags and change nothing else, it works as expected.
Based on what some of you have already said, I am wondering if the path resolution to the newly opened window is not correct. But I don't understand why because I am using the full path. Also to confuse matters even more, my linked stylesheet works just fine from the PHP file.
Apologies for how long this is, but if anyone has the time to look at this further, I would greatly appreciate it. I am stumped. I am a novice when it comes to a lot of this, so if there is just a better way to do this and avoid this problem, I am all ears (or eyes I suppose...)
I have also had problems with a similar issue to this, and this was a real headache. The following approach may not be elegant, but it worked for me.
Make sure that your php file, just outputs what you want in your
body
Add jquery to the window head dynamically
Add any external script files to the window head dynamically
use jQuery html on the window's document to call html() with your loaded content on the body, so that scripts are evaluated.
For example, in your ajax success:
success: function(pageContent) {
var windowFeatures = "width=800,menubar=yes,scrollbars=1,resizable=1,status=yes";
var reportWindow = window.open("", "newReportWindow", windowFeatures);
// boilerplate
var boilerplate = "<html><head></head><body></body></html>";
reportWindow.document.write(boilerplate);
var head = reportWindow.document.getElementsByTagName("head")[0];
var jquery = reportWindow.document.createElement("script");
jquery.type = "text/javascript";
jquery.src = "http://code.jquery.com/jquery-1.7.min.js";
head.appendChild(jquery);
var js = reportWindow.document.createElement("script");
js.type = "text/javascript";
js.src = "/folder1/folder2/folder3/pageControl.js";
js.onload= function() {
reportWindow.$("body").html(pageContent);
};
head.appendChild(js);
reportWindow.document.close();
}
Good luck!
It probably isn't looking where you think it is looking to grab your javascript file.
Try a server-relative format like this:
<script src="/some/path/to/pageControl.js"></script>
If that still isn't working, verify that you can type the url to your script file into your browser and get it to download.
Make sure that you have that within either <head> or <body> of the HTML page. Also, I'd double check the path to the .js file. You could do that by pasting "pageControl.js" at the root of your web address.
Things to look for:
Use Firebug (NET tab) to check if the js file is loaded with status 200. Also check in the Console tab for any javascript errors.
Are you using HTML5 offline. If you do, maybe it serves a cached version that doesn't include your <script> tag.
View the page source and make sure it includes the script tag.
Change the source attribute to absolute path: <script src="http://www.example.com/js/pageControl.js" type="text/javascript"></script>
Visit http://www.example.com/js/pageControl.js and make sure it shows correctly.
Try to place the <script> right after the <head> so that it loads first.
This is all I could think of.
You can dynamically load script by creating the element and then append it to head or other element:
reportWindow.document.write(pageContent);
var script = document.createElement('script');
script.src = 'pageControl.js';
script.type = 'text/javascript';
reportWindow.document.getElementsByTagName('head')[0].appendChild(script);
reportWindow.document.close();
Have you tried using the jquery $("#target_div").load(...)
This also executes JS inside the output...
Read this doc to find out how to use it :
http://api.jquery.com/load/
To me it sounds like you're expecting an unloaded script to work.
Try taking a look here: http://ensure.codeplex.com/SourceControl/changeset/view/9070#201379
This is a bit of javascript that ensures that the script is loaded properly before access is attempted. You can use this either as lazy loading (loading javascript files only when required), or, as I interpret your problem, loading a script based on the result of ajax calls.
What's probably happening is, you're echoing a string via an ajax callback, not inserting an element. External scripts require a second GET call to load their contents, which isn't happening - only the first call happened. So, when the first call includes the inline code, the DOM doesn't have to make an additional GET request to fetch the contents. If the DOM doesn't see the script, the DOM won't execute it, which means it's just some random tag.
There's a very fast way to find out. In Chrome (or Firefox with the Firebug plugin installed), check the console > scripts dropdown to see all the loaded scripts. If it's not listed, it's not loaded and the script tag you see in the markup is otherwise inert.
Since it's probably just a string as far as PHP cares, you could create it as PHP DOM object and insert it properly (although this could be laborious). Instead, maybe place it at the very end of the page, just before the closing body tags. (This is the preferred position for js anyway - dead last, after all the other elements on the page have loaded and are available to the DOM.)
HTH :)

Categories