retrieving $_GET variable in jquery - php

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.

Related

Passing a friend GET ID to another page

I have asked this question before but I couldn't understand the answer maybe because it didn't work for me.
I have a developed a chat application. Once a user submits using keyup, it works well i.e inserted into database and also selected just fine and the message is even displayed. The page being refreshed by javascript is load.php which has php code doing the selection like this;
SELECT * FROM chat WHERE sender_id=$_SESSION['id']
This is working just fine. But when I change it to
SELECT * FROM chat WHERE sender_id=$_SESSION['id'] AND receipent_id=$_GET['id']
it is not working simply because the $_GET['id'] of a selected member in the home page is not being passed to the load.php which is being refreshed by javascript every .....milliseconds so that online messages of the session id and the selected member should show in the message display.
I refresh the load.php using this code on the home page;
function refresh(){
setTimeout (function(){
$('#message').load('load.php');
refresh();
}, 2000);
}
working just fine.
Now this load.php must select for me messages only for the member selected in the home page. So how can I have this members' id passed on to this load.php on selecting from database?
Will be so grateful for your help programmers.
If you want to pass $_GET['id'] value try to add in your function this value
function refresh(){ setTimeout (function(){
$('#message').load('load.php?id=<?php echo $_GET['id']; ?>');
refresh(); }, 2000);
}
Then load.php will have get value
You need to add get variable in your code:
function refresh(id){ //receive id
setTimeout (function(){
$('#message').load('load.php?id='+id); //add id variable to the url
refresh();
}, 2000);
}
Well, you need to pass the GET value on the query string. Currently you're requesting this:
load('load.php')
If you want an id value, add one:
load('load.php?id=' + someValue)
If you need to get that value from the current query string in JavaScript, there are a number of ways to do that. Though, when you initially load the page, if the value is available then it would be trivial to output it to the page from PHP code in the first place. Something like this:
var someValue = <?php echo $someValue; ?>;
Keep in mind a few things here:
If the value is a string then you need to specify quotes in the JavaScript, not in the PHP.
Don't blindly echo user-submitted values to the page, that's a security vulnerability.
Users can change this value in your load.() call. So your approach may make it trivial for users to "impersonate" other users in your application. Make sure you always validate authorization server-side.
Your example SQL queries look like glaring SQL injection vulnerabilities. You're probably going to want to read up on validating user input and using prepared statements.

Dynamically give access to JavaScript functions

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!

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
}

Dynamic javascript redirection

I need to redirect users to a unique url when they visit a specific link which corresponds to a certain/row/column in the mysql database.
Here is what I mean:
The mysql database has a table table123 with a row id 123 and inside a column name "column123".
This row and column correspond to the webpage1.html
Normal javascript redirection is like this:
<script>location.replace('http://website.com/webpage2.html');</script>
What I need to do is extract the value from column123 of the webpage1.html and add it to the redirection url, so it would redirect specifically with that value.
For example:
<script>location.replace('http://website.com/webpage2.html/go/dbtable123row123column123value');</script>
This redirection script will be placed on top of the php page that will call the other php pages, so it has to be dynamic every time, thus the redirection script has to use dynamic placeholder, not static value, except the domain name.
Thanks
If the table really is mysql table and the javascript has no way to access that information, follow other suggestions and deal with it on the server-side. If somehow, the table data are printed on the html document where you want the redirect to take place then you can consider the following. (Though, it would really make more sense to manage this server-side).
Assuming you have given unique id to your column and assuming that the table is on the web page that you have your location.replace call on.
location.replace("http://website.com/webpage2.html/go/" + $('#column123').text())
Without jQuery, you could use
document.getElementById('#column123').innerHTML (or text?)
If it is not practical to assign an id to the column, you can possibly use some jQuery selector magic with :eq
location.replace("http://website.com/webpage2.html/go/" + $('#dbtable123 > tr:eq(1) > td:eq(3)').text())
(none tested)
Assuming you can't redirect in PHP for whatever reason, here's what I'd do. Grab the proper web page from your database using AJAX. I'd suggest using a library such as jQuery to help you do that. If you use jQuery it'll look something like this:
$(function() {
$.get(
'/script/that/queries/db.php',
'your=query_string&goes=here',
function(data) {
if(data.url.length > 0) {
location.href = data.url;
}
},
'json'
);
});
You didn't specify when you want this redirect to fire, so I just put it in the standard body onload. Anyway, after you write that $.get() function call, then in your /script/that/queries/db.php, you'll want to perform your database query based on the get variable(s), and print a JSON encoded array with the valid page you want to redirect to:
$json = array('url' => '/webpage2.html');
print json_encode($json);
Of course I've just written some pseudo code, but hopefully it'll help get the idea across. You'll want to make sure you validate/sanitize all info being querying the database, etc.
Do it simply.Make dynamic url with php script.
header('Location: http://website.com/'.$table123row123column123);

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.

Categories