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?
Related
Good evening ..
I have a form where you assign work to a worker, however, if that work is already assigned then user has a choice of either reassigning it or returning to previous page.
so I'm trying to write the syntax for a confirm alert that redirects user to one page or another depending on his choice ,
I placed it within the head section and it goes something like this:
function show_confirm() {
var con = confirm("Already assigned.. would you like to reassign?");
if (con ==true) {
window.location = "reassign.php"
} else {
window.location = "index.php"
}
}
The question is : how do you call this function depending on an if statement? I have seen some examples on the internet where people place the function (rather than just call it ) directly inside the if statement, but wouldn't that be mixing different kinds of script?
So .. how do you call the function from within this if statement?
I tried this but it didnt work:
$flat=$_POST['flat'];
$check= mysql_query("SELECT * FROM assignment WHERE flat = '$flat'");
$num= mysql_num_rows($check);
if ($num!=0) { show_confirm();
} else { //irrellivant code
Since this is a JavaScript function, you just place the function itself inside the header, and then in PHP, you output the call to the function in your if like this:
if ($num!=0) {
echo '<script type="text/javascript">show_confirm();</script>';
} else {
//irrelevant code
}
PHP is a server-side scripting language, while JavaScript is client-side. You can't call the JavaScript function directly from the server-side like you were trying to do. You can however output javascript to the page via PHP as I have done in my example.
Yes, you are trying to mix php (server side) and javascript (client side) in one process which won't work.
When you submit the form to check if they are already assigned you then need to redirect them to a confirm page, from there you would have yes/no buttons linking to the reassign and go back pages.
The best solution would actually be to handle this with AJAX but given the nature question I think its best to stick with non-ajax workflow.
Let me know if that makes sense, if not I will add some more detail
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.
I have just started into OO PHP and have created my first class. As it is, it works, but I want to tidy things up a bit.
Right now elements in the class call an ajax function that is declared in the head of the document.
I don't want the class to be dependent on a proper head, so to keep it self contained, I moved the script functions into the class file. I could not find information on whether this is a no-no, so if it is, I want to know "Why is putting javascript/ajax in a PHP class bad form?" If, however, it is an acceptable practice, I have a trickier question.
The AJAX calls a PHP page who's results will then fill in more of the class object on the page. But, I figure the class would be better if it didn't rely on external php files either. So, I moved the files into functions on the class file. Here's the tricky bit.
How do I get the AJAX to get the results from a function located on the same file as the AJAX call instead of an external page?
Here is my AJAX code so far. var url currently is the path to one of two possible PHP pages instead of the desired internal php functions. var dest is where in the class object the results end up.
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq(url,dest) {
http.open('get',url);
http.onreadystatechange = function () {
if (http.readyState == 4) {
if (http.status == 200) {
var responce = http.responseText;
document.getElementById(dest).innerHTML = responce;
}
}
};
http.send(null);
}
What you're asking for sounds like xml-rpc or json-rcp. It lets you dynamically execute server-side code and get the results.
Example javascript rpc library: http://barracudaserver.com/doc/WebServices/JRpcDoc.html
However, I think that simply passing parameters is what you want. The simplest way is to pass get parameters in the url
http://www.site.com/ajax.php?cmd=find_user&user_id=12
then in php check for those parameters in the global $_GET variable
if(isset($_GET["cmd"]) && $_GET["cmd"] == "find_user"){
$user_id = $_GET["user_id"];
//some server-side stuff
echo results;
}
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a page where I want to display some points on map. I have small templates (like Smarty, but lighter) and there in template I have variable $points, that consists of coordinates of points I need. I need to pass them to javascript (because only javascript can render that map with points).
I have 3 variants of doing it. Can you tell, what is best?
1th way: (Template inserting javascript-tags with global variable)
tpl.php file:
<script>
MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
.js file
function renderMap(){
var points = MAP_POINTS; // using global. Is it really bad? or who cares? =))
}
2nd way: (Passing variable through the HTML element)
tpl.php.file
<input type="hidden"
value="<?php echo json_encode($this->points); ?>"
id="map_points_container">
.js file
function renderMap(){
// without globals, but needed to be parsed on local side
var points = $.parseJSON ( $( "#map_points_container" ).val() );
}
3rd way: (AJAX-way)
I don't pass $this->points from template file at all. I have another .php file that handles all my AJAX requests:
Ajaxing.php
function get_map_points($params){
// some operations
return json_encode ($map_points);
}
And than on local side I'll have something like this:
.js file
$.post ( 'ajaxing.php', params,
function(points){
renderMap(points);
}, 'json');
The third way is usual, but if I already pass some values from template to local page, then I can pass and map points too. In fact, I don't need to make another request for only this map points (that's why I don't like third way)
But may be you can advise me another way? a better way?
The way I choosed:
1th way with little remarks. All my 'map-rendering' code is in another file and it's like:
$(function(){
MAP_APP = {};
MAP_APP.some_prop = null; // some properties
MAP_APP.some_method = function(){}; // some methods
});
So in template file I only have to extend my MAP_APP object:
<script>
MAP_APP.points = <?php echo json_encode($this->points); ?>;
</script>
Yes, global variable. But it's like namespace of whole application.
Thanks to everybody.
The first way is definitely the least complicated and fastest.
The second one adds an additional processing step (the parseJSON()) that isn't necessary.
The third way is good if you're dealing with lots of data that is optional (i.e. is needed only if the user requests it, and it isn't 100% sure whether that will happen) or dynamic. It creates a new request though, and is not going to be immediately available.
If you don't want to use globals, you could e.g. wrap your JavaScript functions into an object, and populate an object property from PHP:
<script>
MyObject.MAP_POINTS = <?php echo json_encode($this->points); ?>;
</script>
There is another funky way of passing variables in a js external file :)
Your PHP file:
<script type='text/javascript' src='script.js?id=0&some=<?php echo $whatever?>'></script>
and inside your script.js you can retrieve those values:
var scripts = document.getElementsByTagName('scripts');
// get your current script;
for (var i=0,l=scripts.length;i<l;i++){
if(scripts[i].src.indexOf('script.js') !== -1) { // or your script name
var query = scripts[i].src.substr(scripts[i].src.indexOf('?')+1);
// now you can split the query and access the values you want
....
}
}
The first one is most efficient and fastest. The second one is funky. The third one is also fine.
The first because it does not require any other requests. The second one is a bit odd, I would not use that kind of constructs, but that does not mean you can't. The third one is also fine, but you should think about if AJAX is the way to go. If you application requires multiple requests for points for different locations, then it might be the most efficient way to go.
I would go with your second method since you don't want to use AJAX for it (and it seems odd to use AJAX for something you already have in the current page). You want to limit the number of global variables in your JavaScript because everything in your JavaScript will create an instance of each global variable and thus decrease your performance.
I forgot the name of the person, but the man who was heading on optimization at Yahoo! and then went to work for Google gave a lecture about JavaScript optimization, and this was one of his points.
EDIT: Found the link: http://sites.google.com/site/io/even-faster-web-sites
Speed wise 1st way is the best way.
But the best way is to create an XML output from PHP and loading that xml into Javascript via Ajax. The best example of this is article given on google maps documentation - http://code.google.com/apis/maps/articles/phpsqlajax_v3.html
Another way:
In script_that_defines_renderMap.js:
function renderMap(points) {
// take "points" as an argument
}
And then:
<script src="script_that_defines_renderMap.js"/>
<script>
var mapPoints = <?php echo json_encode($this->points); ?>;
renderMap(mapPoints);
</script>
No global variable, no problem.
I'm trying to create a very simple message board (author, text, and date written) that will auto-update every few moments to see if a new message has arrived, and if it has, auto load the latest message(s).
I'm proficient in PHP, but my knowledge in AJAX is lacking.
The way I see it, I would have to create a PHP file called get_messages.php that would connect to a database and get through a $_GET variable return all posts beyond date X, and then I would somehow through jquery call this PHP file every few minutes with $_GET=current time?
Does this sound correct?
How would I got about requesting and returning the data to the web page asynchronously?
You're pretty close, you'll need a PHP script that can query the database for your results. Next, you'll want to transfigure those results into an array, and json_encode() them:
$results = getMyResults();
/* Assume this produce the following Array:
Array(
"id" => "128","authorid" => "12","posttime" => "12:53pm",
"comment" => "I completely agree! Stackoverflow FTW!"
);
*/
print json_encode($results);
/* We'll end up with the following JSON:
{
{"id":"128"},{"authorid":"12"},{"posttime":"12:53pm"},
{"comment":"I completely agree! Stackoverflow FTW!"}
}
*/
Once these results are in JSON format, you can better handle them with javascript. Using jQuery's ajax functionality, we can do the following:
setInterval("update()", 10000); /* Call server every 10 seconds */
function update() {
$.get("serverScript.php", {}, function (response) {
/* 'response' is our JSON */
alert(response.comment);
}, "json");
}
Now that you've got your data within javascript ('response'), you are free to use the information from the server.
Ignore the ASP.NET stuff, this link is a good start:
http://www.aspcode.net/Timed-Ajax-calls-with-JQuery-and-ASPNET.aspx
What you're going to use is a javascript function called setTimeout, which asynchronously calls a javascript function on an interval. From there, jQuery has a fancy function called "load" that will load the results of an AJAX call into a DIV or whatever element you're looking for. There are also numerous other ways to get jQuery to do alter the DOM the way you'd like.
There are a hundred ways to do this, but I'd say avoid writing plain Javascript to save yourself the headache of cross-browser functionality when you can.
I suggest you go for the Simple AJAX Code-Kit (SACK) available on Google code.
I've been using it since before it was on Google code. It's very light and straightforward. It's one js file that you have to include. I've seen it being used in online browser games as well.
http://code.google.com/p/tw-sack/
Example for loading page contents from get_messages.php in a div (if you don't care about the page contents from get_messages.php, and simply want to call the php file, simple remove the ajax.element line):
<script type="text/javascript" src="tw-sack.js"></script>
<script>
var ajax = new sack();
ajax.method = "GET"; // Can also be set to POST
ajax.element = 'my_messages'; // Remove to make a simple "ping" type of request
ajax.requestFile = "get_messages.php";
ajax.setVar("user_name","bobby");
ajax.setVar("other_variables","hello world");
ajax.setVar("time",dateObject.getTime());
ajax.onCompleted = whenCompleted;
ajax.runAJAX();
function whenCompleted(){
alert('completed');
}
</script>
<div id="my_messages">Loading...</div>
You don't need to specify an "ajax.element" if you want to do a simple "ping" type of request and ignore the output of the php file. All you have to do to implement your requirements now is to use a "setTimeout" making the ajax calls.
There are also many other options like:
//ajax.onLoading = whenLoading;
//ajax.onLoaded = whenLoaded;
//ajax.onInteractive = whenInteractive;
No need to learn or include huge frameworks. And you'll get started in no time with tw-sack.