I'm building a plugin for Joomla that ajaxifies the front-end. I've been using a script from balupton's balupton's history js page, and it works fine, except any javascript using the .ready() function will not execute, as the DOM has already been loaded.
What I would like to do is somehow search the scripts being requested, and then strip out the functions that use ready(), and then execute them.
In the script, we already grab all the scripts referenced in each html file, and we have access to the text inside each js file:
// Add the scripts
$scripts.each(function(){
var $script = $(this), scriptText = $script.text(), scriptNode = document.createElement('script');
scriptNode.appendChild(document.createTextNode(scriptText));
contentNode.appendChild(scriptNode);
});
I am considering doing a simple string replace, but then again, I'm not sure if there's a better way of going about doing this, as it will of course require regex due to the possibilities of varying callback functions.
Thanks in advance.
I don't think that changing the JS is the correct way. Have you tried simply firing the ready function manually?
jQuery.ready();
Related
I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?
I have a jquery1.js file that conflicts with another jquery2.js file intermittently. I would like to load the second jquery file only if the first is not present, because the modules that need these display intermittently throughout the site. So is it possible to search for at least the string or inner html in javascript and make a decision on that finding?
i.e. (in pseudocode)
if (jquery1 exists){do nothing}
else{document.write('<script>/jquery2.js</script>')}
or something along these lines.
Have you considered using a script loader like YepNope to manage this sort of dependancy?
yepnope({
test: window.jQuery,
nope: 'jquery2.js',
complete: function () {
// Initialise any dependant scripts
}
});
Assuming jquery1.js has jQuery namespaced as jQuery (the default), you can do the following:
<script>!window.jQuery && document.write(unescape('%3Cscript src="/jquery2.js"%3E%3C/script%3E'))</script>
I belive $().jquery will return the version you are using so you can try if($().jquery === undefined)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Server side browser that can execute JavaScript
Execute javascript in PHP
How can I parse HTML that includes JavaScript code, preferably with PHP script if possible.
As an example:
link
should be replaced by the appropriate value the JavaScript function returns, e.g.
link
A more complex example would be a saved facebook html page which is littered with loads of javascript code.
Summarized:
Return a DOM for a page with html+javascript
You could just give this link an ID. Not that this solution is javascript, jQuery.
So give the link an Id, or class.
$('.link').each(function() {
var functionName = 'link';
var start = $(this).attr('href');
remove = start.replace('javascript:', ''),
get = remove.replace(new RegExp('^'+functionName+'\(((.+\,?)+)\)\;?', 'g'), function(a, b, c) {
return c.replace(/[()']/g,'')
}), args = get.split(",");
//read settings
var firstArgument = args[0];
$(this).attr('href', firstArgument)
});
Please note this is just an example.
Usage:
<a class="link" href="javascript:link('http://facebook.com')">Hi</a>
That would make the actual link http://facebook.com.
Adding new arguments this way is difficult though and its not really professional.
But this should do what you want, I just didn't know what your link function actually doesnt so I didnt add the argument with the boolean. Of course this could get far more complex and you could write a function that could do this too but I just wrote this for your really quick.
Check out the example.
You can't. When clicked, javascript: URIs just call the function and let it do whatever it wants (which MIGHT include navigating somewhere); they don't expect or use a return value. In many use cases, the function may not cause any navigation at all.
DomDocument can be used to parse HTML in PHP including JS: http://php.net/manual/en/class.domdocument.php
You can "render" the JS with the HTML by merely echoing out the output of a cURL or wget (or whatever you use) without escaping the HTML characters. For external JS you are going to need to build a crawler which will crawl the DomDocument script tags and fetch the appropiate URL and load it into a position that is accessible unless you use it directly from their servers but I don't think they will be too happy about that.
Edit: My new answer after some comments is: no
For example:
$(document).ready(function(){
$('.selector').click(function(){
<?php
// php code goes here
?>
});
});
Will this cause issues or slow down the page? Is this bad practice? Is there anything important that I should know related to this?
Thanks!
If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.
If you are trying to generate final javascript or jquery code using PHP then this is okay.
It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:
<script>
var stuff = <?php print $stuff; ?>;
var blah = "<?php print $blah; ?>";
// Do things in JS with stuff and blah here, no more PHP mixed in
</script>
PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.
If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.
Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out. Other than that, have fun.
PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:
User requests page.
Apache (or equivalent) notices this
is a php file. It then renders all
the php that are between php tags.
Apache sends the page to the user.
User's browser sees the JavaScript
and executes it.
Just be sure the PHP is outputting valid JavaScript.
you have a better choice to use ajax that runs the php script when you are handling a click event
$(document).ready(function(){
$('.selector').click(function(){
$.ajax({url:"phpfile.php",type:"POST",
data:"datastring="+value+"&datastring2="othervalue,
,success:function(data){
//get the result from the php file after it's executed on server
}
});
});
});
No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.
I was wondering how i could achieve using <?php?> in javascript for url's? There's a certain route you have to go, Anyone know?
the normal way for example:
$fetchContent = $('#div').load('website/members #content');
What i'm trying to do:
$fetchContent = $('#grav').load('<?php?> #poppu');
Yep, thats wrong as hell lol, but i'm sure someone knows
I would also like to know how to tie php with javascript, but thats probably a whole new topic
You said it right :)
Yep, thats wrong as hell lol, but i'm
sure someone knows
Anyway, from your php script, output the url as a javascript code anywhere in the script before the javascript used for ajax call, e.g.
<?php
echo '<script language="javascript"> var g_ajax_url = "'. $the_url . '";</script>';
?>
and in your javascript, use it this way
$fetchContent = $('#grav').load(g_ajax_url + ' #poppu');
What it simply does is define g_ajax_url as a global variable with the proper php value, and you can use that variable in your js as you use other variables.
To tie php with js directly, try looking into xmlrpc topic.
If javascript is in .php file you can use <?php echo $url ?> and if the file is .js you can't use <?php ?>
It is not clear to me what you are trying to achieve. I assume you are using the jQuery load() function, if yes, you should state so.
You can't load php during javascript execution because the php has already been processes and rendered as HTML and sent back to the client. As PHP is processes on the server it is logical that you cannot run it on the client side.
You could of course send an AJAX request to the server that runs a certain php page and you will be able to use the response as you please.
you can't necessarily "tie" them together because they operate in two different spectrums of processing, php being processed on the server, and javascript being processed in the browser.
You can however render javascript within a php file.
if your javascript is included within a <script> tag within your php page your example should work should actually work. The php would render the urls into the script before it is sent to the browser.
if you are wanting to load external javascript files with php inlcuded urls, you will need to set the proper headers and include the php file just as you would a normal .js file.
good article on this topic HERE
You cannot execute <?php ?> inside JavaScript, but inside PHP you can declare a global variable as:
var x = '<?php echo x;?>';
or, if it's an array, store it as JSON:
var x = <?php json_encode(x); ?>
then access the JavaScript variables inside the external JavaScript.