I'm very new to jQuery & web development in general. I'm attempting to use jQuery's ".getScript()" method to load a couple JavaScript scripts that are written in a particular PHP file, but I think I'm missing something.
(NOTE: I noticed several different questions that looked like they had the potential to help me, but none did. If there's one you know of, feel free to point me in that direction. Thanks.)
When I debug this in Firebug it hits the ".getScript()" call & then jumps on to the next line, seemingly without executing.
Here's how I'm trying to do it:
jQuery.getScript("relative/path/to/script/phpScript.php", function(){
alert("I'm HERE!");
setValues(); // JavaScript function that's written by phpScript.php
});
In this case, the JavaScript is being generated by the "phpScript.php" file and my "alert()" never gets run, but I'm not sure why. Any ideas?
I did notice that I'm getting some kind of parse error by following a suggestion in another question. I don't know how to resolve that. Here's the code for that:
jQuery(document).ajaxError(function(event, request, settings){
alert('error loading: ' + request.status + "\nevent: "+ event);
for (var key in request){
if (request.hasOwnProperty(key)) {
alert(key + " -> " + request[key]);
}
}
});
BTW, we're running jQuery with "jQuery.noConflict();" set, which is why I'm not using the shorthand "$()" notation.
Here is a snippet from the response body from the GET call in getScript():
<html><script type="text/javascript">
function setValues()
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
jQuery("#Form_DB").text(window.formDB);
jQuery('#pertaining_to').text(window.pertainNAME);
jQuery("#Pertain_To_ID").text(window.pertainID);
jQuery("#Form_ID").text(window.formID);
jQuery("#Field_ID").text(window.fieldName);
}
</script>
<head>
Thanks in advance,
-Mark
If you're loading JS scripts, try writing them as discrete functions into a .js file (e.g.: jsscript.js) and then using this HTML line:
<script type='text/javascript' src='jsscript.js'></script>
Then you can just call the functions themselves without using .getScript().
(Of course, you need to put the above line before the point where you call the scripts.)
That seems like a much cleaner way of doing it than what you're currently attempting.
EDIT: Given your present circumstances (i.e.: a PHP page that generates JS scripts and a PHP page that calls the scripts), maybe you can so something like this?
//PHP page that generates the scripts
function gen_script() {
//JS script generated into $script variable
return $script;
}
//PHP page that calls the scripts
include ('generate.php');
echo gen_script();
I thought you may just edit your phpScript.php file as
function setValues(){
jQuery("#formname").text(window.formNAME);
jQuery("#Form_Path").text(window.formPATH);
//...
}
That will be OK.
Related
I'm working on some code I've inherited and I'm not quite experienced enough to know if the way it currently works is as over-complex as it seems to be. I know that the project has had several developers working on it, including some inexperienced ones.
There is a script included in the header containing an IIFE which returns a function called bind_events, which takes an argument called settings
// scroll-events.js
var scroll_events = (function ($) {
return {
bind_events: function (settings) {
scroll_elements = settings.scroll_elements;
click_elements = settings.click_elements;
}
};
})();
In footer.php, there is an echo statement containing a jQuery document ready function which calls the function returned by the IIFE defined in scroll-events.js, interpolating PHP variables as parameter values.
echo "
jQuery(document).ready(function() {
scroll_events.bind_events({
\"universal\":".$universal.",
\"page\":\"".$page
})
});
"
I'm working in WordPress, and have the ability to easily localize PHP variables so JS scripts have access to them.
I'd like to know if the current way of doing things is as convoluted as it seems, and how the same result could be achieved in a more easy-to-follow-and-debug way?
I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.
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.
Had a nice PHP/HTML/JS prototype working on my personal Linode, then tried to throw it into a work machine.
The page adds a script tag dynamically with some JavaScript. It's a bunch of Google charts that update based on different timeslices. That code looks something like this:
// jQuery $.post to send the beginning and end timestamps
$.post("channel_functions.php", data_to_post, function(data){
// the data that's returned is the javascript I want to load
var script = document.createElement('script');
var head= document.getElementsByTagName('head')[0];
var script= document.createElement('script');
var text = document.createTextNode(data);
script.type= 'text/javascript';
script.id = 'chart_data';
script.appendChild(text);
// Adding script tag to page
head.appendChild(script);
// Call the function I know were present in the script tag
loadTheCharts();
});
function loadTheCharts() {
// These are the functions that were loaded dynamically
// By this point the script tag is supposed be loaded, added and eval'd
function1();
function2();
}
Function1() and function2() don't exist until they get added to the dom, but I don't call loadTheCharts() until after the $.post has run so this doesn't seem to be a problem.
I'm one of those dirty PHP coders you mother warned you about, so I'm not well versed in JavaScript beyond what I've read in the typical go-to O'Reilly books. But this code worked fine on my personal dev server, so I'm wondering why it wouldn't work on this new machine.
The only difference in setup, from what I can tell, is that the new machine is running on port 8080, so it's 192.168.blah.blah:8080/index.php instead of nicedomain.com/index.php.
I see the code was indeed added to the dom when I use webmaster tools to "view generated source" but in Firebug I get an error like "function2() is undefined" even though my understanding was that all script tags are eval'ed when added to .
My question: Given what I've laid out, and that the machine is running on :8080, is there a reason anyone can think of as to why a dynamically loaded function like function2() would be defined on the Linode and not on the machine running Apache on 8080?
jQuery supports javascript responses:
$.post("channel_functions.php", data_to_post,
function (data, textStatus, xhr) {loadTheCharts()},
'script');
However, a dataType of "script" will turn a cross-domain POST into a GET, as per the documentation.
The main problem with eval is the eval-ed code inherits the scope the eval is in. Instead, you can use jQuery.globalEval. Try something like:
$.post("channel_functions.php", data_to_post,
function (data, textStatus, xhr) {
/* data might have errors, which will cause an exception.
We'll let the default exception handler catch & log it.
*/
$.globalEval(data);
loadTheCharts();
});
Why don't you just eval the responseText? I don't see the need to create a new script node.
I have made a method which will delete a file.
first i echo the url to this file.
like this
echo "<a href='$fulr'>$filename</a>";
now basicaly i want to call the function deletefile($file);
how can i do it like this
echo "<a onclick='$this->deletefile($filename)' href='$fulr'>$filename</a>";
is that even posible?
Or how can i implement something similiar inside the php code?
You seem to have the wrong idea about browser/server communication. You need to either do:
<?php
...
printf("<form name=\"delfilefrm\" action=\"delfile.php\" method=\"POST\">
<input type=\"hidden\" name=\"delfile\" value=\"%s\" />
<input type=\"submit\" value=\"Delete %s\" />
</form>", $filename, $filename);
...
?>
In the server, so that the link goes to a script on the server, or use JavaScript. I would recommend using jQuery's post() function or a similar AJAX function:
$.post("delfile.php", { file: \"$filename\" } );
Remember: security, security, security ... then graceful degradation
And thanks waiwai933, David Dorward for allowing me to "see the wood for the trees" on a fundamental point quickly forgotten.
In this instance, the PHP runs on the webserver and sends some output to the browser.
The browser then processes that output as JavaScript.
There is no way to directly access the PHP. You have to send an HTTP request back to the server.
This could be a simple link (but don't do that for a delete file operation, GET operations should be safe (or else a bot will walk over your site and delete everything), a form, or if you really want to involve JavaScript - XHR (or some other object that can be used to perform Ajax). Libraries such as YUI or jQuery can help you with the heavy lifting here.
Either way (form or Ajax), you'll probably end up putting the data about what file you want to delete in the POST data. Your PHP script will read this (from $_POST and call the function you want).
… and if you do go down the Ajax route, don't forget to build on things that work.
You can't call PHP code from your Javascript.
What you CAN do is (assuming this is happening on a web server) place a GET/POST to a PHP script, passing in any necessary parameters, to execute the right PHP method.
From within PHP, it's a bit easier. If you're spitting out HTML, you can add a script node to invoke a Javascript function (or just run some Javascript).
You can't do it in that way because javascript cannot execute php code and you cannot delete a file with javascript so i think that you must do something like this:
if(isset($_GET['delete'])) unlink($_GET['delete']);
....
echo "<a href='".__FILE__."?delete=$fulr'>$filename</a>";
You can do this:
php: lets call it deletefile.php
<?
$file = $_POST['filename'];
deletefile($file);
?>
jQuery:
$('a').click(function(){
$.ajax({
method: 'POST',
url: 'deletefile.php',
data: "filename=" + $(this).text(),
success: function(data) {
alert('File deleted.');
}
});
return false;
});
html:
<a href="#" >filename<a/> <!-- filename is the name of your file... -->
You can't call PHP code from your Javascript.
but u can use xajax for doing it
or check this post.
this will be better solution using ajax
If you want to call PHP functions from Javascript then this is about as close as you can get: http://www.phplivex.com/
I'ved used this lib many times and I really like it.