Dynamically give access to JavaScript functions - php

The title may be a bit non-descriptive, so let me explain what I want to do.
I have a lot of JavaScript functions that I want to be able to "give access to" based on a user's permissions to do certain things on my system. As an example:
I have a JS function to add an employee:
function doNewEmployee() {
var x;
var objTemp=new Object();
var myElements = new Array ("username","password1", "password2", "emp_type",
"name", "surname", "personal_contact", "work_contact", "location_dd",
"home_address", "access_level", "id_num");
for (x=0;x<myElements.length;x++){
objTemp[''+myElements[x]+'']=document.getElementById(myElements[x]).value;
}
asyncProxy.addNewEmployee(objTemp);
}
This sends all the parameters through AJAX to my PHP
Now, what I want to be able to do is check whether the user has permissions to execute this function and only include it in the final JS file sent client-side if this is true.
Is this possible? I was thinking about just creating a load of if statements, echoing out the javascript functions in the index.php file, but this would entail having all my JS inline, which isn't what I want.
I guess at the end of the day I want a dynamically built JS file?
Any help would be greatly appreciated!

Related

Processing ID in the URL

I have gotta website powered by a set of jQueries; Dynamically loading the contents with a set of menu buttons.
Now, all I want to know is this:
Have you seen in blogger? The url is like
blogger.com/blogger.g?blogID=abcd#id
For the #id, if you put #overview it shows the stats. If you put #allposts it shows all the posts and similarly the content varies depending only on the #id in the url. I've seen many websites use this method to provide PermaLinks too.
How can I do it? for each menu button I provided an #id, which if passed in the url I need to switch to that particular menu.
Note : I use PHP, js, jQuery and HTML5 +/- Ajax
PS: Please, do not say you can use this and that! I'm a kinda middle of a knowledge i.e I'm not a pro. So please provide me with some algorithms or code.
Thanks in advance :)
window.location.hash will contain the hash value in the URL (#id, #overview, etc...). You can then use javascript that runs when your page loads to check the value of window.location.hash and based on what it contains, you can modify your page, using ajax calls if retrieving data from the server is necessary.
The hash value is not sent to the server so it must be client-side code that processes it.
As for specific code, you would use something like this;
$(document).ready(function() {
switch(window.location.hash) {
case "#id":
// code here
break;
case "#overview":
// code here
break;
default:
// code here
break;
}
});
What specific code goes in there obviously depends upon what you're trying to do. If you need to get data from your server, then you would issue ajax calls to retrieve that data.
This are called hash values which are not sent by the browser to the server, they can only be accessed by javascript.
They can be retrieved by
var hash_val = window.location.hash;
Javascript also provide event for hash change
window.onhashchange = function(){
}
And if you want it to modify content then
window.onload=function()
{
var hash_val = window.location.hash;
//do more ajax stuff here
}

Populate PHP variable with AJAX?

Im not sure if this is possible, but at the moment I have a form on my page where users can insert their interests, beneath that form are 3 PHP variables (Which dont currently show at first as there is no value assigned to them).
When a user enters an interest and clicks submit, my AJAX takes over, populates the table and then reloads the page so the Variable now shows as it has a value.
Is it possible to not have to refresh the page, so I can say "if success $var = 'value';"?
I hope this doesnt sound too confusing, thanks
Since you're already using AJAX, why don't you just do the logic using Javascript? If you're using jQuery, have a success callback function execute the code you want.
The problem with sending data from AJAX to PHP is that PHP is a server side language, while AJAX is a client side one. By the time your browser sees the page, the PHP has been entirely executed and returned to you as HTML / CSS / Javascript etc.
No, you can't. By the time the HTML has rendered/displayed in the browser, PHP will most likely have long since finished generating the HTML in the first place. You could round-trip the values through an AJAX handler and then populate the places in your page where the values are displayed, but when why bother round-tripping? Just have the AJAX call fill in the values right then and there.
It is absolutely possible, and quite easy to do. Just make another php script and call it from your form page's javascript (I'm going to assume you're using jQuery):
$('#mysubmit').click(function() {
$.getJSON(
'form_ajax.php', // This is the php file that will be called
{ formVar1: $('#form-var-1').val() }, // Add all your form data here
function(data) {
// This is the function that is called after the php script is
// done executing. The 'data' variable will contain the $data
// array you see in the following php file.
}
);
});
I prefer to use JSON, but other approaches are just as good. Check out the documentation for getJSON() and ajax(). Your php file would look something like this:
<?php
$data = array();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$data['formVar1'] = $_POST['formVar1'];
}
echo json_encode($data);
?>
Of course, yours would probably do a lot more with the form data. Also, theres plenty of other approaches so go explore for the one the best suits your needs.

how to pass variable from php template to javascript [duplicate]

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.

retrieving $_GET variable in jquery

I have a main page (topic.php) with GET information in the URL, like this:
http://studio.byuipt.net/topic.php?topic=Debugger&desc=Helps%20find%20and%20solve%20problems%20with%20others%27%20code.
I have a div, "currLeader" in topic.php into which I load another page, getCurrLeader.php. getCurrLeader.php is supposed to use the topic variable in the $_GET info of the url to do a mysql search and return the relevant info. The problem is that while, scripts on topic.php are able to successfully use extract($_GET), I am not able to retrieve any variables out of the getCurrLeader.php extract($_GET) statement. I thought both pages would be able to access the currently showing url. Is there another way I can get this information out of the current url?
(consequently, the "topic" info is actually present in an element with an id on the page, and I'm able to successfully retrieve it using jquery, but I can't figure out a way to then, within the same file, pass that value to my php script).
I'm not really sure I understand what you're asking. On first read I assumed you were trying to do this with jquery, but now I'm not so sure I'm on the same page at all. Here's an easy way to extract the parameters in javascript:
<script type="text/javascript">
var ourlocation = location.href;
var thisstuff = ourlocation.split("?");
var id = thisstuff[1];
var idary = id.split("&");
var param2 = idary[0];
var param3 = idary[1];
var param4 = idary[2];
</script>
Which probably has nothing to do with what you're trying to do.
On 2nd read it seems like you're trying to get the originating url in a php script, when another one loads first.
One way you could do that is use sessions. Either store the parameters you're trying to extract, and stuff them in a session to be retrieved by the other file, or you could actually just store the url itself, then pull it out and split it.
session_start();
$_SESSION['ourUrl'] = $_SERVER["REQUEST_URI"];
// do stuff on next page
unset($_SESSION['ourUrl']);
session_destroy();
If none of this makes sense feel free to explain further and we'll see if we can get you going. Hopefully this helps a little.

AJAX calling a PHP code and getting a response every few minutes

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.

Categories