Dynamic javascript redirection - php

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);

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.

PHP redirect to pdf then navigate to another page?

I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?

Passing URL from php to javascript

I am reading a rss feed with php and creating html DOM from the same. Now I have a bunch of <li>'s with news feed. when a user clicks on a particular <li> I want to post certain data to another php file which performs some other function.
How I want the data is tricky. I have a URL for all the feed elements. When a user clicks on a particular feed, I need to retrieve the URL associated with that particular feed.
I want to run a $.click() function in which I am going to $.post to the next php script.
How do I get that URL without storing it in the HTML itself. I do not want to store the URL in the html document for security puposes.
I am new with PHP.
You will need to assign unique id (uid) to each list element that corresponds to the url. A good way of handling this would be a database. You send the list item's identifier, look up in the database the associated url, perform some magic, and send the response back to the client. You can use jQuery's data method that leverages the html5 data attribute to store the information. Here is the basic pseudocode.
html
<li class="feed" data-uid="12345">Go</li>
javascript
$('li.feed').click( function() {
$.post({ id: $(this).data('uid') }, function(data) {
//do something with data
});
});
php
$uid = $_POST['uid'];
//db lookup of url
//do something with url
//return data to page
you could encrypt the url being sent from the server and then decrypt when it's sent back from the client. Just use a simple salt encryption method. I assume you're going to use ajax or the like to post back from the client to the server in which case, this methodology would work for you.
alternatively, you could create an array and store the urls in a collection with an associative key that you send to the client, then look up the url on the server side by that key. You could also implement a database solution to do this same thing where the key is the ID in the db.
U have to encode the variable url...
PHP
var url = ...;
JavaScript
$(function (){ var d1 = <?php echo json_encode(array($url)); ?>;});

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.

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.

Categories