I have a modal window that uploads files to server. Works great. Upon completion of the upload I am refreshing a div on the parent page. Almost works. What I need in order for it to work is to be able to grab $_GET['edit']. Hopefully my layout of the code will help show my issue.
Modal Window: upload complete
$('#albumFinished').click(function() {
$('#sortableImages').load('../includes/sortImages.php');
});
sortImages.php
$galleryID = $_SESSION['newGalleryId'];
$getGalleryID = $_GET['edit'];
echo "<ul>";
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $getGalleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='recordsArray_{$row['id']}' >";
echo '<img src="'. $sortPath .'"/>';
echo "</li>";
}
echo "</ul>";
Everything is functioning properly except I am unable to grab the $_GET variable. How do I go about grabbing this variable? Also if my explanation is not clear, I will try to clarify further.
I'm sorry maybe I'm not understanding but your not actually sending any data to the sort images.php to get with $_get your simply doing a load which is identical to just typing that url in your browser
try using $.post or $.get or $.ajax to send your get info over similar to this
$.get("../includes/sortImages.php", { edit: "what your editing"},
function(data){
return your data here
});
The load function include an extra param called data. This param is the one you have to use to pass parameters to the server via GETmethod. For example:
$('#albumFinished').click(function() {
$('#sortableImages').load('../includes/sortImages.php',
{newGalleryId: 'specify_an_id', edit: 'some_value'});
});
The third line pass the specified parameters and values to the server. Where you will be able to grab them
Related
I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery
Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4
I want to output the results of an ajax form that resides in a module into the article that is currently on display. Below is a screenshot of what I'd like to accomplish. I'd like to modify the mysql query that is in the article via the form input from the module(in sidebarA) via ajax.
Here is some truncated form code from the module via jumi:
<form action="http://fsdsonline.com/menumanager/index.php/menustab/all-meals/77-component-menus/124-alcohol-n" method="post">
<option value="AND plate = '1'">Plate FSDS only</option>
<option value="AND plate = '1'">Prep FSDS only</option>
<option value="">Plate and Prep FSDS</option>
</select><br /><select style="font-size: 12px;" name="menu">
<option value="">All Meals</option>
<input style="font-size: 12px;" onclick="location=document.menuselector.menu.options[document.menuselector.menu.selectedIndex].value;" type="button" value="Show" /></form>
<div class="success" style="display: none;">View your menu</div>
And here is the php code that is in the article via jumi.
mysql_connect($hostname,$username, $password) OR DIE ('Unable to
connect to database! Please try again later.');
mysql_select_db($dbname);
$plateprep = $_POST['plateprep'];
$meal = $_POST['meal'];
$pub = $_POST['pub'];
$avocado = $_POST['avocado'];
$alcohol = $_POST['alcohol'];
$result = mysql_query("SELECT catnum, ctgry, Shrt_Desc, `desc`, ROUND(`Energ_Kcal`*`yield`*`qty` ) AS `cal` FROM allinnot a
LEFT JOIN allinfsds b
ON a.`NDB_No2` = b.id1
LEFT JOIN fdcat h ON b.product_type = h.unik
LEFT JOIN allinnot2 g ON a.`NDB_No2` = g.NDB_No
LEFT JOIN allincomp j ON a.`NDB_No2` = j.fsds_num
WHERE `own_id` = $user->id $plateprep $pub $meal $avocado $alcohol
ORDER BY `catnum`, `order`");
$cat = null;
$first = true;
while ($row = mysql_fetch_array($result)) {
if ($row['catnum'] != $cat) {
if (!$first) {
echo '</table>'; // close the table if we're NOT the first row being output.
}
$first = false; // no longer the first table, so disable this check.
echo '<p style="line-height: 12pt; font-size: 12pt;"><strong>' . $row['ctgry'] . '</strong></p>';
echo '<table>'; // start new table
$cat = $row['catnum'];
}
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . " " . $row['cal'] . " cal</td></tr>";
}
?>
</table>
</body>
</html>
I think that I've coded my query correctly, and the form looks nice, but how do I connect the two via ajax??
Thanks!!
I'm afraid that I'm not familiar with jumi.
Normally to do an ajax request your javascript file will make an ajax request to a specific php file. You will need to trigger this in your form somehow if you are going to use ajax. The php file should echo the information that you want, back to the file that made the ajax request.
In this case, I think that the ajax request will have to go to the page that you have jumi embedded in, but I'm not sure.
If you are going to use ajax then I recommend using jquery to do it. It makes life a lot easier. Here is an example of a simple ajax request made using jquery.
$.ajax({
type: "POST",
url: "joomla_page.php",
data: { 'menu': menu },
success: function(){
informationfromphp= data.menu; //This is $menu echod from php
$('#menuid').html('<span class="food_results">Success!</span>');
}
})
In your php code, capture the ajax message with something like this
if (isset($_GET['menu'])) {
//do something ;
}
Then do something in the php (such as make a call to the DB). Afterwards you can return the information from the php to the ajax file using an echo.
echo $menu;
Please note that this is not a working example, it is just a rough idea to get your started. You will find plenty of other examples on stackoverflow.
Using jumi with joomla will give you path problems :
In your php code, ( server side ), you will have for all include and require to :
_use absolute path , using $_SERVER['DOCUMENT_ROOT'] .
_Or redefine the path for jumi tu use your includes ( not tested, seems to me macGiver fixing, as using jumi anyway...).
Actualy, there is another problem , client side, caused by joomla choices :
The html BASE is defined by joomla on every pages, by default, and the base is the human readable url ... so for your url in the html and javascript, be aware of relative uri ...
You will be ok with absolute uri.
So, in your case, with ajax , client side, you have to precise the target with an absolute url , and in your php, to give absolute path for all ressources used that are in other files.
Managed to make work a jquery autocompletion on joomla over jumi with that.
Note that joomla uses mootools, and that you can only include jquery late on the page ( all you do in jumi will be in the body) . And sometimes, jquery and mootols don't go well together : similar use of the $ . Sometimes you'll have to use the jquery.noConflict.
I will advice to use only one kind of javascript framework , but, sometimes, you have to manage with old choices...
I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
$(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.
i am calling a javascript for image gallery and php on a single page.
let me show you some code to make things clear:
PHP
echo "<form method = post action = 'user_submit.php'>";
// get possible answers using question ID
$query = "SELECT aid, atitle FROM answers WHERE qid = '$qid' ORDER BY aid ASC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_object($result)) {
echo "<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>";
echo "<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th".$row->aid.".jpg' /> </a>";
echo "<input type = hidden name = aid id = rd".$row->aid." value = ".$row->aid.">".$row->atitle."</input>";
echo "</div>";
}
echo "<input type = hidden name = qid value = '".$qid."'>";
echo "<br/>";
echo "<input type = submit name = submit value = 'Vote!'>";
}
echo '</form>';
}
the above code fetches object ids and places jpeg images accordingly (thumbnails).
now when i click on these thumbnails the javascript opens an overlay to display the large version. i want to pass the value of $row->aid to javascript.
then from the javascript i want to fill out a form and pass the $row->aid and the form to user_submit.php to add it to the DB.
i am new to php. please help me out.
You can write a variable, object or array literal declaration to your javascipt file or to a <script> element in a HTML file, as kiamlaluno correctly said. but i would suggest, (1) use the var keyword and (2) consider using a separate namespace.
If you have several things to tell the JS, it's handy to put them in a PHP hash and json_encode() and then write the encoded string to your output. This takes care of the namespace and correct escaping of the data. For example:
<?php
$jsdata = array(
'this' => "It\"s gone.\nWhat?",
'that' => array(1,3,2),
'another' => 0x2f );
$jsdata = json_encode($jsdata);
?>
<html>
<head></head>
<body>
<script type="text/javascript">
var thedata = <?php echo "$jsdata;" ?>
window.console.log(thedata);
</script>
</body>
</html>
Try that and look at the javascript console to see if it works.
EDIT: Another reason I like this approach is because you can use PHP's array handling conveniences to construct an arbitrarily complex $jsdata while not worrying about escaping issues and only consuming one global JS object name.
First of all, you don't need to echo everything. Something like this is just as valid:
while ($row = mysql_fetch_object($result)) { ?>
<div id=captionbox style='width: 110px;float:left;color:#FFF;text-align:center;'>
<a href='#' class='thumb' ><img class='thumb-img' src='images/roadies/th<?=$row->aid?>jpg' /> </a>
<?php ...
In this case, uses php's echo shortcut tag to echo the value of the contents. It is equivalent to <?php echo $some_variable ?> .
Second, I don't actually see any JavaScript code in your question. But to accomplish what it sounds like you want to do, you can make an HTML form with a SINGLE hidden input whose value is set by selecting one of your images, and then have that form submit to user_submit.php.
The value-setting can happen in a number of ways, which is really up to you. But suppose you wanted it to happen when the user clicked an image. Then you could set the onClick event inside the img tag, like onclick="hidden_input.value='<?=$row->aid?>'"
There are many ways to pass data to JavaScript; the easier is the following:
<script>
aid = <?php print $row->aid; ?>
// The rest of the script
</script>
I only wrote the necessary code, without even write all the attributes for the tag SCRIPT.