Passing variable to external PHP file - php

I'm having a (probably super simple) issue. The code below is supposed to _POST (using AJAX) a variable called 'id' to an external file called getYourData.php.
I think the issue is below. The 'data' section doen't seem to be functioning - I've even tried putting [data: '2'] to simply put '2' in the SELECT statement. But that doesn't even work.
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: 'id',
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
Here's the rest of code (snippet - jquery has been imported)
<!-- First Box: click on link shows up second box -->
<div id="selectOne" style="float: left; margin-right: 10px; border: #666 thin solid; padding: 10px;">
One<br />
Two<br />
Three
</div>
<!-- Second Box: initially hidden with CSS "display: none;" -->
<div id="selectTwo" style="float: left; margin-right: 10px; display: none; border: #666 thin solid; padding: 10px;"></div>
<!-- The JavaScript (jQuery) -->
<script type="text/javascript">
//Do something when the DOM is ready:
$(document).ready(function() {
//When a link in div with id "selectOne" is clicked, do something:
$('#selectOne a').click(function() {
//Fade in second box:
$('#selectTwo').fadeIn(500);
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: '2',
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
//Depending on the id of the link, do something:
if (id == 'one') {
//Insert html into the second box which was faded in before:
$('#selectTwo').html('One<br />is<br />selected')
} else if (id == 'two') {
$('#selectTwo').html('Two<br />is<br />selected')
} else if (id == 'three') {
$('#selectTwo').html('Three<br />is<br />selected')
}
});
});
</script>
getYourData.php - creates a custom SELECT statement based on the 'id' passed from primary page. For some reason, this isn't working. Only works when I intentionally set a dud variable ($id2)
<?php
$username="primary";
$password="testpass";
$database="testdb";
mysql_connect(localhost,$username,$password) or die ('Unable to connect...');
mysql_select_db($database) or die('Error: '.mysql_error ());
//Intentionally creating a dud variable will create a good SELECT statement and work
$id2 = "3";
$id = $_POST['id'];
$query = mysql_query('SELECT * FROM members WHERE member_id='.$id);
$result = mysql_fetch_assoc($query);
//Now echo the results - they will be in the callback variable:
echo $result['firstname'].', '.$result['lastname'];
mysql_close();
?>

data in your AJAX function needs to be of the form 'id=xxx'. I see you have it in the variable id. Try data: 'id=' + id. Confusing I know.
The explanation here is that POST data should be of the form a=b,c=d,... et cetera. That way PHP will pick it up as a key/value pair in the $_POST dictionary. Now you have a variable id which you would like to send (value), and you also want this to be the name of the (key). Hence you would need to do data: 'id=' + id. If id=2, then that will evaluate to data: 'id=2', which is correct.
Ultimately, as #Stephen noted, it is better to use an Object for the data field, as it is arguably more elegant. data: {'id': id} should work as well, and you can add more variables in the future.

Have you tried data: {id: 2 } - object, not an array.

I believe the data in your ajax call is wrong. The php references $_POST['id'] in your call but the var ID is not sent.
from : http://api.jquery.com/jQuery.ajax/
dataObject, String
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting
(described below).
Should be more like this:
data: "id=2",

Related

How to insert row using AJAX

I am creating a page for blog posts and I am having some trouble with getting my 'Like' (Heart) function to work using AJAX.
It needs to submit when the heart is clicked which should submit a new row into my PHP database without page refresh, but the form submission is not working/posting.
This is my first time submitting form using AJAX so sorry if I'm being a noob.
My PHP table has 5 columns - id, content, userID, username & date.
$(document).ready(function() {
$("#heart").click(function() {
if ($("#heart").hasClass("liked")) {
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
$("#heart").removeClass("liked");
} else {
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
$("#heart").addClass("liked");
$("form#myform").submit(function(event) {
event.preventDefault();
var title = $("#title").val();
var user = $("#user").val();
var userID = $("#userID").val();
var dte = $("#dte").val();
$.ajax({
type: "POST",
url: "../PHP/user_functions.php",
data: "title=" + content + "&user=" + user + "&dte=" + dte + "&userID=" + userID,
success: function(){alert('success');}
});
});
}
});
});
.fa-heart-o {
font-size:24px;
color:black;
cursor: pointer;
}
.fa-heart {
font-size:24px;
color: red;
cursor: pointer;
}
.ggg{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<form id="myform" action="../PHP/user_functions.php" method="post">
<span class="" id="heart"><i class="fa fa-heart-o" aria-hidden="true"></i></span>
<input type="hidden" id="title" value="How To Guide Title Example" name="content">
<input type="hidden" id="user" value="TestBot" name="username">
<input type="hidden" id="userID" value="<?php echo $userID ?>" name="sessionID">
<input type="hidden" id="dte" value="<?php echo date('Y/m/d H:i:s'); ?>" name="date">
<input class="ggg" type="submit" id="submitButton" name="submitButton" value="Submit">
</form>
and my PHP page..
<?php
if (isset($_POST['submitButton'])) {
$username = $_POST['username'];
$userID = $_POST['userID'];
$date = $_POST['date'];
$content = $_POST['content'];
$sql = 'INSERT INTO `likes-blog` (username, userID, date, content) VALUES (:username, :userID, :date, :content)';
$stmt = $dbh->prepare($sql);
$stmt->execute(['username' => $username, 'userID' => $userID, 'date' => $date, 'content' => $content]);
?>
<?php
}
?>
In your backend/PHP file, treat it as if the POST data is always getting passed into it.
Think about this: You're only going to run the code that's controlling the data to be sent to your database when $_POST['submitButton'] is passed to the page. When you're sending your data to your PHP file, it does nothing because you're telling it to only run that code if $_POST['submitButton'] is set (has a value).
Secondly, I want to mention that in your ajax, it's much easier to structure the POST data like this, and also cleaning up the success function to look a little better; you can also pass through a response like I've shown here, that the PHP file will send back in case of an error or you can have your PHP file send back a custom string with a success message:
$.ajax({
type: "POST",
url: "../PHP/user_functions.php",
data: {
title: content,
user: user,
dte: dte,
userID: userID
},
success: function(response) {
alert(response);
}
})
I would also definitely look into MySQLi prepared statements and looking at how to better protect against SQL injection.
Take a look at these PHP functions and how to use them, I've written up a very basic example of something you could use, but you can also change it to fit your needs, just make sure you use the functions properly:
// Data:
$dataOne = 5; // <-- integer
$dataTwo = "Hello, world" // <-- string
// in the ...bind_param() function, where "is" is located, in order, you'd use i for integer and s for string, there are others but these are the basic ones, you can find more documentation online for this.
// For example if you passed through the $dataTwo variable and then the $dataOne variable, it would be "si" because the variable with string content gets passed first and the variable with an integer passed second.
// For the ? marks in the $sql string, those directly relate to how many values you're going to pass through. In the computer, ? will be translated to each value passed through in the ...bind_param() function, in order, and insert them into the selected table/columns, in order. Basically, the code below will insert $dataOne into the "column1Name" column and will insert $dataTwo into the "column2Name" column in the "tableName" table.
$sql = "INSERT INTO "tableName" ("column1Name", "column2Name") VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
or die("Could not initiate a connection.");
mysqli_stmt_prepare($stmt, $sql)
or die("Could not prepare SQL statement.");
mysqli_stmt_bind_param($stmt, "is", $dataOne, $dataTwo)
or die("Could not bind SQL parameters.");
mysqli_stmt_execute($stmt)
or die("Could not execute SQL sequence.");
mysqli_stmt_close($stmt)
or die("Could not close SQL connection.");
Seems complicated and there is more to learn, but instead of being like everyone else on here that just expects you to figure it out yourself, I figured I'd give you an example. I'd also recommend learning how to wash your POST data once your AJAX sends it to your PHP file. You can also use the above method for securely deleting and updating rows/columns/values in your database. (If you're not actually inserting data, for example if you're using a delete statement, you can simply not use the ...bind_param() function since it would serve no purpose there.
Also, I believe part of your issue is that you're also submitting the form itself and I don't think even executing the Ajax code. Part of the reason why ajax is useful is because it allows you to submit POST and GET data to an external handler file (your PHP/backend code/file) without having to have the page reload, which has many other benefits, there are only some cases where you'd actually HAVE to submit the form like would be done by default without ajax. Technically, you don't even need to use a form if you're using ajax, in most cases. (but not all). For example you could get rid of the tags altogether, and just have your inputs stay as normal; you can use JS to grab the values. Set your submit button to type="button" (if it's set to submit, the page will reload, which kind of defeats the purpose; type="button" will not reload the page).
So, here's a rough example of what I'm talking about:
HTML:
<input type="text" id="firstName" name="firstName" placeholder="What's your first name?"/>
<input type="text" id="lastName" name="lastName" placeholder="What's your last name?"/>
<button type="button" id="submit">Submit</button>
And your JavaScript w/ ajax:
$("#submit").on("click", () => {
// Get the current value of the input textbox:
let first = document.querySelector("#firstName").value;
let last = document.querySelector("#lastName").value;
if (firstName !== null) {
// Send data to PHP file:
// Keep in mind when only sending single data values, you can do it like shown here:
$.ajax({
type: "POST",
url: "path to php file here",
data: {
firstName: first,
lastName: last
}
success: function(response) {
// The following is an example of something you can use to error handle. Have the PHP file handle all the errors and simply make the PHP code respond with 1/true if the code was executed correctly, or if there was an issue, have it respond with false/0:
if (response == 1) {
alert("You've successfully submitted the form.");
} else if (response == 0) {
alert("Sorry, there was an error submitting the form.");
}
}
})
}
})
PHP example:
<?php
require("path_to_database_connect_file"); // I never recommend creating a connection inside another file, so do something like this instead. Have a separate PHP file where its sole purpose is creating and starting a connection with your database. I used the connection variable as $conn, it seems in your original question you were using $dbh. The variable name doesn't really matter I just prefer $conn.
$data = array_filter($_POST);
$first = $data['firstName'];
$last = $data['lastName'];
$sql = "INSERT INTO names (firstName, lastName) VALUES (?, ?);";
$stmt = mysqli_stmt_init($conn)
or exit(false);
mysqli_stmt_prepare($stmt, $sql)
or exit(false);
mysqli_stmt_bind_param($stmt, "ss", $first, $last)
or exit(false); // Both $first and $last have type "string", so the passthrough right after $stmt in this function is "ss" for string-string. If $last was an integer, it would be "si" for string-integer, in that order. Though, if you don't mind everything in your database being string types, which is usually fine for basic stuff, you can still just use "s" for everything. So if you're passing 5 variables into 5 different table columns, you could just do "sssss" there.
mysqli_stmt_execute($stmt)
or exit(false);
mysqli_stmt_close($stmt)
or exit(false);
echo true; // If any of the above code fails, it will return false back to ajax in the response callback and exit the script, ajax will see the returned value of "response" as "0" and you will receive the alert message of "Sorry, there was an error submitting the form.". If everything works smoothly with no errors, this script will echo or "return" true back to ajax, and ajax will read "true" as "1", therefore in the success method as shown above, you should get the alert message: "You've successfully submitted the form."
Try this
<script>
$(document).ready(function() {
$("#heart").click(function() {
if ($("#heart").hasClass("liked")) {
$("#heart").html('<i class="fa fa-heart-o" aria-hidden="true"></i>');
$("#heart").removeClass("liked");
} else {
$("#heart").html('<i class="fa fa-heart" aria-hidden="true"></i>');
$("#heart").addClass("liked");
let title = $("#title").val();
let user = $("#user").val();
let userID = $("#userID").val();
let dte = $("#dte").val();
//Ajax
$.ajax({
url: "../backend.php", //This your backend file PHP
data: {
"title": title,
"user" : user,
"userID" : userID,
"dte" : dte
},
dataType: "JSON",
type: "POST",
beforeSend: function() {
//Function for sweetalert like loading or any
},
success: function(data) {
//if succes
console.log(data);
},
complete: function() {
//Function while ajax complete
},
error: function(data) {
//if error
console.log("ERROR");
console.log(data);
}
});
}
});
});
</script>

jquery - ajax - problem with update columns one by ones

i want to update each columns acording by id, when i click on an image, without refresh all the page. my codes just update last ids column when i click each on images.
index.php:
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid=1");
while($rw=mysqli_fetch_assoc($rzp)){$id=$rw['id'];
echo $id;?><img id="up" src="pc3/up.png" alt=""><br>
<?php }?>
<script>
$(document).ready(function() {
var id = <?php echo $id;?>;
$(document).on("click","#up",function() {
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id},
async :false
}).done(function(msg2) {
alert(msg2);
});
});
});
</script>
y2.php:
$id=$_POST['id'];
mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
thanks
There are a couple things immediately wrong here:
You are re-using id values in your HTML, which is invalid.
Your var id = ... JavaScript code always has the last value from your data, and you're explicitly using that every time instead of any value from your HTML element.
Let's simplify. First, echo your HTML elements to include (1) a class to use for triggering the click handler and (2) the ID that the click handler needs:
<?php
while($rw=mysqli_fetch_assoc($rzp)){
$id=$rw['id'];
echo $id;
?>
<img class="up" src="pc3/up.png" alt="" data-id="<?php echo $id; ?>"><br>
<?php } ?>
(Note: There's probably a much cleaner way to do that. I'm attempting to maintain the coding style you currently have, but you should definitely look into cleaner approaches of writing code overall.)
Now you have a bunch of images with (1) a class called "up" and (2) a data- attribute with the ID you need upon clicking. Your click handler can now use that information:
$(document).on("click", ".up", function() { // use the class as the selector
var id = $(this).data('id'); // get the data-id value from this specific element
$.ajax({
method: "POST",
url: "y2.php",
data: {id: id}
}).done(function(msg2) {
alert(msg2);
});
});
(Note: I also removed async: false because one should never use async: false. If there's some reason you think you need to use it, that's a different problem entirely and one that should be addressed as well.)

Getting jQuery variable to PHP in the same file without refreshing the page

Thanks for reading. I have tried the answers in other similar questions but none have worked so far. I'm trying to UPDATE values inside a Table that is inside a form, so in the first part of the file is the isset "saveImport" which is the name of the a tag that I'm using to send the id thru the URL:
if (isset($_POST['saveImport'])) {
$id = $_POST['id'];
}
a tag:
<a name="saveImport" href="./?id=<?= $row['id']; ?>" class="saveImport btn btn-success col-xs">Save</a>
I do get the ID value in the URL but since is been updated in the same file I'm assuming it refreshes the page before the variable gets post thru AJAX:
<script type="text/javascript">
$(document).ready(function() {
$('.saveImport').click(function() {
var imp_id = id.id;
var imp_href = $(id).attr('href');
alert(imp_href);
$.ajax({
url: "./",
data: {id : imp_id},
type: "POST",
success: function(data){
alert(id);//send this ID to the PHP variable without
//refreshing the file
}
});
});
});
I'm getting the class .saveImport because it's inside a Table which is displaying values from a Database so it's inside a while loop and if I use an ID it will cause conflict as the ID will repeat itself.
I already created the PHP function to UPDATE the Values which executes if the ISSET is true, so my real problem will be to execute the ISSET and inside grab the ID that was posted with AJAX so I can use the ID in the UPDATE function. Right now, if I click on the a tag, it sends the ID thru URL, the page refreshes but the value of the ID is not getting in the $id = $_POST['id];
I appreciate your time.
This should work.
Change the ajax url to your php file name (mine was t.php).
Replace 99 with your data from php. (id is used. href is not used)
<?php
if (isset($_POST['saveImport'])) {
print_r( $_POST );
exit;
}
?>
<a name="saveImport" id='99' href="./?id=99" class="saveImport btn btn-success col-xs"'>Save</a>
<script type="text/javascript">
$('.saveImport').click(function(event) {
var imp_id = this.id;
$.ajax({
url: "t.php",
data: {id : imp_id, saveImport: 1},
type: "POST",
success: function(data){
alert( data );//send this ID to the PHP variable without
//refreshing the file
}
});
event.preventDefault();
});
</script>
.preventDefault() will prevent the link from loading the target page... And then, ajax will proceed.
$('.saveImport').click(function(event) {
event.preventDefault();

Send different error messages from PHP back to Ajax/Jquery script and populate HTML DIV...?

I am attempting to send different error messages back to an HTML DIV depending on the PHP outcome. I have searched through here and other place but have been unable to locate an answer that seems to work for my situation... hopefully someone else can help me with this.
My HTML page includes a form that a user is asked to enter a reservation ID # (unique), once the user does this and presses "Search Reservation" a Jquery script is called to send the ID to a PHP script via AJAX. The Data is returned and then is populated into a form using a jquery plugin called, "populate".
Here is the script:
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
$('#reservation-id').val(resCheck); //add res ID back into text box
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
},
error: function(){
$("#res-message").html('<a>There was an error with your request</a>');
}
});
});
});
</script>
This was called from the following form (which also includes the DIV in which I would like to populate my error messages, res-message):
<form name="form_reservation" id="form-reservation">
<div style="padding:10px 20px 10px 10px;">
<label for="reservation-id">Reservation ID</label>
<input name="reservation_id" id="reservation-id" class="reservationid" style="width:120px !important"/>
<div class="res_message" id="res-message"> </div>
<input type="submit" class="button" value="Search Reservation" style="width:150px !important; margin:10px 0px 0px 5px;"/>
<input type="button" class="button" value="Clear" style="width:150px !important; margin:10px 0px 0px 5px;" onclick="resetForms('reservation')" />
</div>
</form>
The form that is populated should not be important for this question. Finally the PHP looks like such:
<?php
include('config-searchres.php');
$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
//$sql = mysql_query("SELECT * FROM ap_form_8 WHERE element_12 = '$term'"); //real selector will look for unique number that has not been added to table yet
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
echo json_encode($row);
}
else //Reservation already passed (old reservation)
{
echo $error = "Passed";
//echo 'passed';
}
}
else //Reservation already cancelled
{
echo 'cancelled';
}
}
else //Reservation not found
{
echo 'not found';
}
mysql_close();
?>
I know next to nothing about PHP, but I do know that this script seems to work for populating my tables... just not displaying errors for other situations. 3 different errors, 'passed', 'cancelled', and 'not found' need to be passed back during their respective situations. Anyone have an idea?
The quick and dirty solution is to test the returned result to see if it is a string or an array. On your javascript:
(...)
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
if (typeof(jsonData)=='object'&&(jsonData instanceof Array)) {
// jsonData is an array, populate success div
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
} else {
// jsonData is a simple string, so PHP returned an error. populate error div
$("#res-message").html('<a>There was an error with your request</a>');
}
(...)
Naturally, when handling the error, you can switch on jsonData contents to provide a specific error message if needed.
It seems the issue is that the different error messages from the PHP code are not send as JSON string. So when using 'jsonData = $.parseJSON(data);' it gives and exception.
May be you can try using the below code.
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
resetForms('reservation'); //clear forms
$('#reservation-id').val(resCheck); //add res ID back into text box
try
{
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'],reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
}
catch
{
$("#res-message").html('<a>There was an error with your request</a>');
$('#json-reservation').populate({status:data});
}
}
});
});
});
</script>
I have not tested this code but atleast the logic should work.

PHP: Navigating through data

I have a PHP site I'm working on, and need to allow the user to select data and have different data appear on the next DIV (see attached image). Essentially I'd like a DIV (overflow:auto, so it scrolls) to populate using the SQL SELECT statement, and allow a user to click on a list item. That item creates a new SELECT statement for the div to the right, if that makes sense. Any input on the best way to go about this? New to PHP, not HTML/CSS though.
Zach
I think the best way to achieve this is with jQuery (a JavaScript-Library). I is quite easy to use, and if you got the trick, you can do amazing things with it.
For PHP/MySQL, you could use jQuerys Ajax functionalities (see http://api.jquery.com/jQuery.ajax/). Use the callback to display the loaded data (see below).
Here is a very simple example on how to show another div (in which could be more links to select) with dynamic content. If you combine this with Ajax, you should get what you need.
Include jQuery in within head tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
Code for the body:
<!-- First Box: click on link shows up second box -->
<div id="selectOne" style="float: left; margin-right: 10px; border: #666 thin solid; padding: 10px;">
One<br />
Two<br />
Three
</div>
<!-- Second Box: initially hidden with CSS "display: none;" -->
<div id="selectTwo" style="float: left; margin-right: 10px; display: none; border: #666 thin solid; padding: 10px;"></div>
<!-- The JavaScript (jQuery) -->
<script type="text/javascript">
//Do something when the DOM is ready:
$(document).ready(function() {
//When a link in div with id "selectOne" is clicked, do something:
$('#selectOne a').click(function() {
//Fade in second box:
$('#selectTwo').fadeIn(500);
//Get id from clicked link:
var id = $(this).attr('id');
//Depending on the id of the link, do something:
if (id == 'one') {
//Insert html into the second box which was faded in before:
$('#selectTwo').html('One<br />is<br />selected')
} else if (id == 'two') {
$('#selectTwo').html('Two<br />is<br />selected')
} else if (id == 'three') {
$('#selectTwo').html('Three<br />is<br />selected')
}
});
});
</script>
So if you would use jQuerys Ajax-Functionality, you could use something like that (not tested!):
$('#selectOne a').click(function() {
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getYourData.php',
data: 'thisIsSentToPHPFile='+id,
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#selectTwo').html(msg)
$('#selectTwo').fadeIn(500);
}
});
});
The getYourData.php could be:
$id = $_POST['id'];
$query = mysql_query('SELECT * FROM table WHERE id='.$id);
$result = mysql_fetch_assoc($query);
//Now echo the results - they will be in the callback variable:
echo $result['tablefield1'].', '.$result['tablefield2'];
Give it some tries, tweak it a little bit and you should get it working.
The most straightforward way to do this is probably to make the right portion an iframe.
Then each item in the middle list could be a link like so:
Company 2
In displaySubItems.php you would then use the $_GET['company'] value in your select statement to populate the table.
Alternatively you could make use of AJAX methods to populate the table on the right though I'm personally not that familiar with AJAX so I can't tell you more about that. Also I suspect iframes are more widely supported.
EDIT: changed some parts based on one of your comments

Categories