Passing a friend GET ID to another page - php

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.

Related

Initiating a form to change MySQL data by a HTML link?

Curiosity killed the cat...
Here's a good one that I need some help with, long story short I am trying to update information on MySQL databases, I understand how to do this with a form on the website and a bit of PHP coding. However, what I am trying to do is create a link on my webpage, just a standard html link, which - once clicked will do the same thing as a form almost (without all the information) which would change a piece of info in the database. Example:
Click "here" to change set number from 0 to 1
Once the user clicks "here" the number in the database changes from 0 to 1.
I would use Ajax. Even though you need to use another PHP file, that won't refresh the HTML page.
1) The link should be something like:
Click here to set number from 0 to 1
2) The Javascript/JQuery code:
function changeValue(value) {
$.ajax({
type: "GET",
url: 'changeIt.php?value='+value,
success : function() {
//does nothing
}
});
}
3) And finally, the code in changeIt.php file should be something like:
$value = $_GET['value'];
//Use MySQL to change the value in the Database

Set a session variable when a link is clicked

I want to set a session variable to 0 when any of a certain set of links are clicked. To do this I have put the following in my javascript file:
$(window).load(function () {
$("#hdr li a").click(function () {
$.ajax({
type: "POST",
url: "clear.php",
data: "width=0"
});
});
});
(Ignore data: "width=0"... I don't use this data in clear.php. I put it there because I thought maybe I had to specify a data field.)
and in the file 'clear.php' I simply have:
<?php session_start();
$_SESSION['name'] = 0;
?>
So, the idea is that when any of the links in #hdr li are clicked, the user should be taken to the page that the link points to, via clear.php, which sets the session variable to 0.
This works in some browsers (Firefox and Chrome) but not in others (e.g., Safari).
Is this the standard/correct way to implement what I want? Also, how does the browser know where to go after visiting clear.php? Somehow it works, but my first thought was that I should pass the final destination URL into clear.php, and then use "header" to move from clear.php to the final destination.
Is Ajax required? If your re-directing the user to another page & you simply want to pass some data to that page then it may be simpler to include that data in your URL.
Link
Now your php would be simple:
$_SESSION['name'] = $_GET['new_session_variable'];
Now you've removed your dependency on JavaScript, does that make sense? :)
I feel it might be worth mentioning that your approach would be appropriate in certain situations, for example: if you wanted the user to be able to mark one of the links on the page as a favourite. Rather than redirecting them to the same page and reloading the majority of the pages content you might:
<a class="favourite" data-linkid="link123" href="mylink.php">My Link</a>
// Ensure your page has finished loading aka: 'ready' (almost always)
$(document).ready(function() {
// Listen for the click event
$('.favourite').on('click', favoriteLink);
// On the click - post the update via ajax and update your interface
function favoriteLink(event) {
event.preventDefault();
// Lets get the link id from our data attribute
var favourite_link = $(this).data('linkid');
// Post that information via ajax
$.post('ajax_handler.html', { link : favourite_link }, function(data) {
// And finally do something with the result!
$('.result').html(data);
});
}
My guess is this has something to do with the asynchronicity of AJAX, some browsers are properly firing the AJAX before the new link is loaded. Others might be canceling the AJAX request because the page is changing. Try preventing the default action of the anchor, and then use window.location to redirect them after the ajax call has returned.
$("#hdr li a").click(function (e) {
var href = $(this).attr('href');
e.preventDefault()
$.post("clear.php", function () {
window.location = href;
});
});
The visitor do not get to clear.php page since you are performing an ajax call.
Instead, what happens is that your browser sends a request underneath via javascript using XMLHTTPRequest object which do not break your browser behavior and as such load the page the a href points to.
As said : the ajax call is usless. You'd better include clear.php on top of your pages and test if whether or not you should set your session var, based on get param for exemple.
If you do want to keep the ajax call before the browser gets to a new page, you may attach an event handler on first common parent of your "resetting" links (event delegation) and test if you should send an ajax request to notify clear.php
I had this problem. I wanted to pass a different sql string to select different rows from a table depending on the link the user clicked on but i did not want to display the sql in a GET.
My solution was to set different session variables for each link and pass the NAME of the session variable from the link. I had several links but I have just included 2 here for the example. My code for the links was:-
<?php $_SESSION["extend_stats_sql_01"] = "";
echo ' View';}?> <br>
and
<?php $_SESSION["extend_stats_sql_02"] = " Where booking_status = 'Cancelled'";
echo ' View';}?> <br>
My code to retrieve the values on my next page to display the list with the correct sql depending on the link was:-
$stats_sql = "SELECT id, name, activity, email, diving_date, arrival_date, checkin_date, create_date, seller FROM guests ";
$sort = $_GET['sort'];
$sent= $_GET['sent'];
$result = $_SESSION["$sent"];
$stats_sql.= "$result";
$stats_sql.= " ORDER BY $sort";
obviously you need to start a session at the beginning of each page :-
session_start();
and when you have finished :-
// remove all session variables
session_unset();
// destroy the session
session_destroy();

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.

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