call values in select box without using zend form - php

I am new to zend framework. I want to call option values in select box dynamically in view file without using zend form. Please help
MY OLD CODE
$txtCategory = new Zend_Form_Element_Select('category');
$txtCategory->setLabel('Category')
->setRequired(true);
$table = new Application_Model_DbTable_Category();
foreach ($table->getcategory() as $c) {
$txtCategory->addMultiOption($c->ExpenseCategoryID, $c->Category);
}
My categories are in select box.

You can simply echo the element on your view if you don't want to use zend_form
In controller
$table = new Application_Model_DbTable_Category();
$this->view->categories = $table->getcategory();
$this->view->selected = "X"; // currently selected value
In view
<form>
<select name="select2" size="3" multiple="multiple" tabindex="1">
<?php $selected = $this->selected;
foreach($this->categories as $c) {
echo "<option value=\"" . $c->ExpenseCategoryID . "\"" . ($c->ExpenseCategoryID == $selected ? " selected=\"selected\">" : ">") . $c->Category . "</option>";
}?>
</select>
//rest of the element
</form>

You're going to need to learn how to use AJAX and javascript to talk to your PHP server. It's going to be a bit harder than using the Zend form like you are now.
Some links with tutorials:
Tutorialspoint on PHP and AJAX
Tutorials point AJAX series

Related

Passing data from an echo dropdown list using javascript

I have this dropdown list that is written using echo
But the select is not as expected
This is my select tag
$output.=" <select name='selectnewauthor' id='selectnewauthor' class='form-control input-lg selectnewauthor'>
<option disabled selected value>Select Author</option> ";
// Getting data from database
$getresourcetype = "Book";
$selectqry = "SELECT author_fullname FROM tbl_author_add WHERE resource_type = ? ORDER BY author_fullname";
$stmt_author = $mysqlconnection->prepare($selectqry);
$stmt_author->bind_param("s",$getresourcetype);
$stmt_author->execute();
$stmt_author->store_result();
$stmt_author->bind_result($author_fullname);
// Writing options
while($stmt_author->fetch()) {
$author_fullname = $author_fullname;
$output .= "<option value='{$author_fullname}'>{$author_fullname}</option>";
}
$output.="</select>
It sounds as though your #selectnewauthor element is dynamically-generated. As such, you need to attach the listener to an element available on page load, and make use of event delegation.
Essentially, instead of $("#selectnewauthor").on('change', function() ...
You're looking for $("document").on("change", "#selectnewauthor", function() ....

html multiple select chosen js submit form

I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.
You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}
Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");

Have data in mySQL database be reflective of what's displayed in a drop down menu.

Thanking you for taking the time to look at this question.
The premise of the situation is that I have a "website" written in PHP and HTML that displays items from my database named "Spreadsheet." There are six columns, and over 4000+ rows of data. The columns are "accountID", "accountName", "website", "rating", "imageURL", "comments." The column "rating" in the website is a drop down list.
Currently, everything works well, but I have do questions:
How do I, with PHP, have data submitted to the database upon clicking on an option (such as "Very Bad") in the drop down list? At the moment, it requires the user to click a "submit" button, which refreshes the page entirely, losing their position. Is it possible to have it submit silently (without refreshing)
Second question has to do with the drop-down list again. How do you have the drop-down list display what's in the database? For example, if rating is "Very Bad" in the database, the drop-down list reflects that, and not what the first element is.
Below is my code.
". $row['website']."<br />
<Form Name =\"rating\" Method =\"POST\" ACTION =\"\" />
<input type = \"hidden\" name=accountID value=" . $row['accountID'] . ">
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\">Above Average</option>
</select>
<INPUT TYPE =\"Submit\" Name =\"formSubmit\" VALUE =\"Submit\">
if (isset($_POST['formSubmit'])){
$rating = $_POST['rating'];
$accountID = $_POST['accountID'];
var_dump($rating);
var_dump($accountID);
if(!mysql_query("UPDATE Spreadsheet SET rating='$rating' WHERE accountID='$accountID'")) {echo 1;}
}
mysql_close();
?>
Thanks so much! This question has been bothering me for a bit. I have tried many Google attempts, but I could not find an answer as specific as I am asking. Thank you so much.
Answer to #1:
You can use Javascript/AJAX to accomplish submitting the form without actually pressing submit. There are various javascript libraries that can help you accomplish this a lot easier than bare bones Javascript, namely jQuery ( http://jquery.com/ ). It's not a very complicated task but you will need to learn some basic Javascript and how to use jQuery. The essential flow of things would be when the form changes, submit an AJAX request to submit the form. You will need a second script to take the incoming AJAX request and do the save. Try search engines for some basic jQuery tutorials, and once you have a basic grip, something like "ajax submit on form change jquery" will get you started.
Answer to #2:
Something like this (please see my notes...)
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '">' . $row['option_name'] . '</option>';
}
echo '</select>';
If you would like the select preselected, that's pretty easy too! Taking from the last example:
$pre_selected = "Very Bad";
echo '<select name="rating" id="rating">';
$q = mysql_query("SELECT `option_name` FROM `options`");
while($row = mysql_fetch_assoc($q)) {
echo '<option value="' . $row['option_name'] . '"';
if($row['option_name'] == $pre_selected) {
echo ' selected="selected"';
}
echo '>' . $row['option_name'] . '</option>';
}
echo '</select>';
But this is the part I'd like to point a few things out:
Don't use the old mySQL library like you are using and my examples are using. Please, use PDO, or at least mySQLi. The functions you are using are deprecated, and may not be available in PHP for much longer.
Please, escape your data properly. Search for "SQL Injection" and you will find a massive amount of information about how your code is very insecure (your UPDATE, specifically) because you did not escape the values.
Just a heads up, when/if you use jQuery, you're going to need to use id="foo" in addition to name="foo".
For the first question you can look at ajax onchange event. Basically when you change select value you fill call function that can call php file to insert data in db.
For the second question you check the DB for selected value and if it matches option value or text you set it to selected
<select name=\"rating\">
<option value=\"\"></option>
<option value=\"Very Bad\">Very Bad</option>
<option value=\"Bad\">Bad</option>
<option value=\"Average\">Average</option>
<option value=\"Above Average\"
<?php if($someValueFromDb=='Above Average'){
echo 'selected=selected';}?>
>Above Average</option>
</select>

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

In joomla, how do I use a form to return dynamic content in an article via ajax

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...

Categories