PHP POST for HTML Select using another POST - javascript

This ain't something not working but just I'm confusing about how to do it, I want to fetch the values from my DB based on users' preferences that been chosen earlier.
These are the steps will be taken for my process:
User will select from images (will add HTML images then will whip it upon another selection)
Will continue till reaching last stage
Last stage will have 3 Select (dropdown menus) and 2 of them will change the content according to what user's chooses (like country and state dd)
My PHP:
else if ($_POST["data_key"]=="last")
{
$final_arr;
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$myquery="SELECT DISTINCT Layout.* FROM Layout,Products,Occasion, Cover, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.cover=$fetcher_cover;";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="size";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="size")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$myquery="SELECT DISTINCT Size.stitle FROM Layout,Products,Occasion, Size, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.size=Size.id";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}
else if ($_POST["data_key"]=="finishing")
{
$final_arr;
$fetcher = $_POST["selected_id"];
$fetcher_theme = $_POST["themeid"];
$fetcher_category= $_POST["themecategory"];
$fetcher_product= $_POST["themeproduct"];
$fetcher_cover = $_POST["ctitle"];
$fetcher_size = $_POST["stitle"];
$fetcher_finishing = $_POST["ftitle"];
$myquery="SELECT DISTINCT Finishing.ftitle FROM Layout,Products,Occasion, Size, Cover, finishing, Theme
WHERE Layout.product=$fetcher_product
AND Layout.occasion=$fetcher_category
AND Layout.theme=$fetcher_theme
AND Layout.size=$fetcher_size
AND Layout.cover=$fetcher_cover
AND Layout.finishing=$fetcher_finishing";
$results=$DB->fetchAll($myquery);
foreach ($results as $row) {
$row["current"]="finishing";
unset($row["pixfizzId"]);
$final_arr[]=$row;
}
echo json_encode($final_arr);
}}
My Engine JS (what I assign):
myItem.setId(jsonData[i].id);
myItem.setImg(jsonData[i].image);
myItem.setTitle(jsonData[i].title);
My Selects in JS (printing HTML):
myString +="<a>Sizes: </a><br><select id='sizesSelect' style=' width:200px'></select><br><br>";
myString +="<a>Cover: </a><br><select id='coverSelect' style=' width:200px'><br></select><br><br>";
myString +="<a>Finishing: </a><br><select id='finishingSelect' style=' width:200px'></select><br><br><br>";
Appending to Select in JS:
myString +="<script>$('#sizesSelect').append('<option val="+i+">"+this.getSize()+"</option>')</script>";
Now I need to know how can I post again to my PHP server to fetch the the values to other selects (refer for the img).
Select Size -> Update Covers -> Select Covers -> Update Finishing -> Select Finishing

Instead of using SQL to store and present previous user choices, you could keep the previous choices as $_POST data by re-adding the choises to the HTML Form as hidden input fields. Example: <input type="hidden" text="foo" name="<?=htmlspecialchars($_POST['foo'])?>">

Related

Hover Event in Javascript/PHP/Codeigniter

To give some Background information: I've got a php-function "showSystems" which extracts data from our CMDB and shows it in a Dropdown generated by the Codeigniter form helper "form_dropdown". So the dropdown contains the names of all our servers and when clicking on one, some other unrelevant functions show different kinds of information about that particular system.
What I want to achieve now is, when hovering over a system listed in the dropdown, that the description of that system is shown in a label under the list. When nothing is hovered, the label is hidden.
Something like:
Dropdown:
Server1
Server2 <-- hover over this
Server3
Label --> shows Description of Server2
How can I handle the mosehover-event in this generated dropdown using php/javascript?
Edit: So I give some more background-information, as it seems to have something to do with my technical setup.
The function, which produces the dropdown with the received data is written in a model of Codeigniter:
<?php
echo '<select class="minipanel" id="selectminipanel" size="25" style="width: 100%" onchange="window.location = \''.site_url(CONTROLLER.'/showItem').'/\' + this.value;">';
foreach($tmp as $key => $value):
if ($active == $key){
echo '<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" value="'.$key.'" server-description="'.$value[1].'" selected>'.$value[0].'</option>';
} else {
echo '<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" value="'.$key.'" server-description="'.$value[1].'">'.$value[0].'</option>';
}
endforeach;
echo '</select>';
?>
The modul is loaded in a template via a view(which loads the model). The label is defined right after the codeigniter call:
<?php $this->load->view("V".$this->name."/vMinipanel"); ?>
<label id="description"></label>
The script is also written in this template's head section:
<script language="JavaScript">
function displayDescription($ele) {
var server_data = ele.server-description;
document.getElementById('description').innerHTML = server_data;
}
function hideLabel() {
document.getElementById('description').innerHTML ='';
}
</script>
So, why are the functions displayDescription and hideLabel not called?
Please check and run below code:
server 1<br>
server 2<br>
server 3
If you are using bootstrap
server 1
server 2
server 3
just these lines of codes will work fine for you .
trigger an event on mouse over, and use the element's data-description to show the details:
<option onmouseover="displayDescription(this)" onmouseout="hideLabel()" data-server-description="your_description" id='1'>
Server1
</option>
<script>
function displayDescription(ele)
{
// You can use the data-server-description attribute to catch the description
var server_data = ele.data-server-description;
// you can also use the ID to fetch the description if not embadded in as an html attribute
var server_id = ele.id;
document.getElementById('your_label_id').innerHTML = server_data;
}
function hideLabel()
{
document.getElementById('your_label_id').innerHTML ='';
}
</script>

PHPExcel to bold text in between HTML markups <B> and <strong>

HI folks ive been trying to figure out a problem that's been haunting me for some time now and original started this thread thread PHPExcel - How to replace text using preg_replace. I was going about this all the wrong way and Mark gave me some tips on where to start. I gave up this project as I was very clueless of how to even start a script for this.
What I am currently attempting is to bold text that are within HTML marker <B> and <Strong>. After spending some time studying Jquery and some javascript to help me with this. I am understanding that ill nee to write a script to find text with HTML markups <b></b> and <strong></strong>,and tell the javascript to bold that text using the following method:
$objRichText = new PHPExcel_RichText();
$objRichText->createText('This text is ');
$objBoldTextRun = $objRichText->createTextRun('bold');
$objBoldTextRun->getFont()->setBold(true);
$objPHPExcel->getActiveSheet()->getCell('B1')->setValue($objRichText);
I would imagine that with Jquery I would use something like the event .find but not quite sure what the best way to approach something like this. This is honestly way beyond my level of comprehension but willing to give it a shot with some help.
Update updated code:
<?php
/** Error reporting */
/** PHPExcel */
require_once '../js/PHPExcel/Classes/PHPExcel.php';
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$rows=2;
$sheet=$objPHPExcel->getActiveSheet();
$wizard = new PHPExcel_Helper_HTML();
//Font Setting for the Support group title.
$Support_team = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 22,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Font settings for the header cells only.
$headers = array('font'=> array('bold'=> true,'color' => array('rgb' => '4D4D4D'),'size' => 12,'name' => 'Arial'),'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER),);
//Border settings
$borders = array('borders' => array('inside'=> array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171')),'outline' => array('style' => PHPExcel_Style_Border::BORDER_THIN,'color' => array('argb' => '717171'))));
// SQl database connections
$db = mysql_connect("localhost", "IMC_Admin", "IMCisgreat2014");
mysql_select_db("imc_directory_tool",$db);
$sql="select client,team_name,support_team_prime,prime_comments,support_team_backup,backup_comments,escalation1,escalation1_comments,escalation2,escalation2_comments,escalation3,escalation3_comments,escalation4,escalation4_comments,note from tbl_address ORDER BY team_name";
$result=mysql_query($sql);
$numrows=mysql_num_rows($result);
if ($numrows>0)
{
while($data=mysql_fetch_array($result))
{
//Cell Wraptext
$sheet->getStyle('C'.($rows+1).':D'.($rows+1))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+3).':D'.($rows+3))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+4).':D'.($rows+4))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+6).':D'.($rows+6))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+7).':D'.($rows+7))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+8).':D'.($rows+8))->getAlignment()->setWrapText(true);
$sheet->getStyle('C'.($rows+9).':D'.($rows+9))->getAlignment()->setWrapText(true);
$sheet->getStyle('B'.($rows+11).':D'.($rows+11))->getAlignment()->setWrapText(true);
$richTextClient = $wizard->toRichTextObject($data['client']);
$richTextteam_name = $wizard->toRichTextObject($data['team_name']);
$richTextsupport_team_prime = $wizard->toRichTextObject($data['support_team_prime']);
$richTextprime_comments = $wizard->toRichTextObject($data['prime_comments']);
$richTextsupport_team_backup = $wizard->toRichTextObject($data['support_team_backup']);
$richTextbackup_comments = $wizard->toRichTextObject($data['backup_comments']);
$richTextescalation1 = $wizard->toRichTextObject($data['escalation1']);
$richTextescalation1_comments = $wizard->toRichTextObject($data['escalation1_comments']);
$richTextescalation2 = $wizard->toRichTextObject($data['escalation2']);
$richTextescalation2_comments = $wizard->toRichTextObject($data['escalation2_comments']);
$richTextescalation3 = $wizard->toRichTextObject($data['escalation3']);
$richTextescalation3_comments = $wizard->toRichTextObject($data['escalation3_comments']);
$richTextescalation4 = $wizard->toRichTextObject($data['escalation4']);
$richTextescalation4_comments = $wizard->toRichTextObject($data['escalation4_comments']);
$richTextNote = $wizard->toRichTextObject($data['note']);
//This section is the actual data imported from the SQL database *don't touch*
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('C'.($rows+1),$richTextClient) //this will give cell C2.
->setCellValue('B'.$rows,$richTextteam_name) // this will give cell B2
->setCellValue('C'.($rows+3),$richTextsupport_team_prime) //this will give C5
->setCellValue('D'.($rows+3),$richTextprime_comments) // This will give D5
->setCellValue('C'.($rows+4),$richTextsupport_team_backup) //This will give C6
->setCellValue('D'.($rows+4),$richTextbackup_comments) //This will give D6
->setCellValue('C'.($rows+6),$richTextescalation1)//THis will give you C8
->setCellValue('D'.($rows+6),$richTextescalation1_comments)//This will give you D8
->setCellValue('C'.($rows+7),$richTextescalation2)//This will give you C9
->setCellValue('D'.($rows+7),$richTextescalation2_comments)//This will give you D9
->setCellValue('C'.($rows+8),$richTextescalation3)//This will give you C10
->setCellValue('D'.($rows+8),$richTextescalation3_comments)//This will give you D10
->setCellValue('C'.($rows+9),$richTextescalation4)//This will give you C11
->setCellValue('D'.($rows+9),$richTextescalation4_comments)//This will give you D11
->setCellValue('B'.($rows+11),$richTextNote); //This will give you B13
//Cell Merging
$sheet
->mergeCells('B'.$rows.':D'.$rows)
->mergeCells('B'.($rows+2).':D'.($rows+2))
->mergeCells('B'.($rows+5).':D'.($rows+5))
->mergeCells('B'.($rows+10).':D'.($rows+10))
->mergeCells('C'.($rows+1).':D'.($rows+1))
->mergeCells('B'.($rows+11).':D'.($rows+11));
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('B'.($rows+1), 'Client:')
->setCellValue('B'.($rows+2), 'Support group contacts')
->setCellValue('B'.($rows+3), 'Prime:')
->setCellValue('B'.($rows+4), 'Backup:')
->setCellValue('B'.($rows+5), 'Escalations')
->setCellValue('B'.($rows+6), 'Escalation 1:')
->setCellValue('B'.($rows+7), 'Escalation 2:')
->setCellValue('B'.($rows+8), 'Escalation 3:')
->setCellValue('B'.($rows+9), 'Escalation 4:')
->setCellValue('B'.($rows+10), 'Notes');
//Format the hardcoded text
$sheet->getStyle('B'.$rows)->applyFromArray($Support_team);
$sheet->getStyle('B'.($rows+2))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+5))->applyFromArray($headers);
$sheet->getStyle('B'.($rows+10))->applyFromArray($headers);
//Row height adjustments
$sheet->getRowDimension($rows+3)->setRowHeight(60);
$sheet->getRowDimension($rows+4)->setRowHeight(60);
$sheet->getRowDimension($rows+6)->setRowHeight(60);
$sheet->getRowDimension($rows+7)->setRowHeight(60);
$sheet->getRowDimension($rows+8)->setRowHeight(60);
$sheet->getRowDimension($rows+9)->setRowHeight(60);
$sheet->getRowDimension($rows+11)->setRowHeight(100);
//Background color on cells
$sheet->getStyle('B'.$rows.':D'.$rows)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+2).':D'.($rows+2))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+5).':D'.($rows+5))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+10).':D'.($rows+10))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FF9BC2E6');
$sheet->getStyle('B'.($rows+1))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+3))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+4))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+6))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+7))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+8))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
$sheet->getStyle('B'.($rows+9))->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setARGB('FFE6F1FA');
//Border range
$sheet->getStyle('B'.$rows.':D'.($rows+11))->applyFromArray($borders);
$rows+=14;
}
}
//This is the hard coded *non dynamic* cell formatting
$sheet->getColumnDimension('A')->setWidth(5);
$sheet->getColumnDimension('B')->setWidth(15);
$sheet->getColumnDimension('C')->setWidth(50);
$sheet->getColumnDimension('D')->setWidth(50);
$sheet->getSheetView()->setZoomScale(90);
$sheet->getStyle('A:D') ->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);
// Rename sheet
$sheet->setTitle('Directory Tool Full dump');
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);
// Redirect output to a client’s web browser (Excel2007)
$today=date("F.d.Y");
$filename = "Directory_Export-$today.xlsx";
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=$filename");
header("Cache-Control: max-age=0");
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
?>
If you're using the latest develop branch from the PHPExcel github repo, there is actually an html to rich text helper class:
The file 42richText.php in the Examples folder demonstrates its use:
$html1='<font color="#0000ff">
<h1 align="center">My very first example of rich text<br />generated from html markup</h1>
<p>
<font size="14" COLOR="rgb(0,255,128)">
<b>This block</b> contains an <i>italicized</i> word;
while this block uses an <u>underline</u>.
</font>
</p>
<p align="right"><font size="9" color="red">
I want to eat <ins><del>healthy food</del><strong>pizza</strong></ins>.
</font>
';
$html2='<p>
<font color="#ff0000">
100°C is a hot temperature
</font>
<br>
<font color="#0080ff">
10°F is cold
</font>
</p>';
$html3='2<sup>3</sup> equals 8';
$html4='H<sub>2</sub>SO<sub>4</sub> is the chemical formula for Sulphuric acid';
$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->toRichTextObject($html1);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', $richText);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(48);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A1')
->getAlignment()
->setWrapText(true);
$richText = $wizard->toRichTextObject($html2);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A2', $richText);
$objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(-1);
$objPHPExcel->getActiveSheet()->getStyle('A2')
->getAlignment()
->setWrapText(true);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A3', $wizard->toRichTextObject($html3));
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A4', $wizard->toRichTextObject($html4));

radio button list with text option cakephp

I am new to CakePHP. I need to make a form with radio buttons and the last one is "other" where the user can type in an answer in a text box.
Is there any way FormHelper can do this that's built in?
One way I was going to do was create a radio list and a text field. When "other" is selected Javascript will show the text field. For this I don't understand how to use any other variables besides the fields in the database. How does one create a variable from a model that can be accessed from a view and the value returned for processing?
For the model I have:
class User extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'title';
var $sourceOther = ' ';
var $passwordRepeat = ' ';
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = sha1(
$this->data[$this->alias]['password']);
}
// $this->data[$this->alias]['created']= CakeTime::gmt();
// $this->data[$this->alias]['updated']= CakeTime::gmt();
$this->data[$this->alias]['username']= $this->data[$this->alias]['email'];
return true;
In the view I have
echo $this->Form->input('mobilePhone',array(
'label'=>'Mobile or fixed phone with no spaces'));
echo $this->Form->input('alternatePhone');
echo $this->Form->input('leadSource', array(
'options'=>array('Google'=>'Google','OnlineAd'=>'Online Ad',
'Printed Media'=>'Printed Media','LetterDrop'=>'Letter Drop',
'Other'=>'Other (specify text)'),
'empty'=>'(choose one)'));
echo $this->Form->input($this->sourceOther);
...but it doesn't like sourceOther, the variable in the model. How do I get data from the view (the text box) into the user model so beforeSave can do something with it?
Thanks.
Thanks.
Sorted it out after reading "Cake PHP Application Development". It works for Cake 2.x and 1.2 (as used in the book).
In your view put:
echo $this->Form->input('sourceOther');
Then in the model you can access your variable with:
$this->data['User']['sourceOther'];
For example, use it to save "other" text field in beforesave:
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = sha1(
$this->data[$this->alias]['password']);
}
$this->data[$this->alias]['username'] = $this->data[$this->alias]['email'];
$this->data[$this->alias]['activation'] = md5(uniqid(rand(), true));
if ($this->data[$this->alias]['leadSource'] == 'Other') {
$this->data[$this->alias]['leadSource'] =
$this->data['User']['sourceOther'];
}
return true;
}

How To Fade Out Function With No Unique ID/Class

I don't normally post my server side code but I guess I can post abit to solve this issue,I have a staff page that loops through in a database as I am going to use the database to do other things like deleting/demoting the staff if they did anything wrong and to make the site neater. (don't like demoting staff but in a case I need to)
Anyway I am looping it through with a box what I want now is when one of the boxes are clicked I want it to go to a php page (via a ajax request to delete the user from the database) then hide or fade way by using the hide or fade function.
But the only issue is how can I do this when it's looping through? because the div does not have it's own class or id and I don't think jquery can connect to a database to get a unique id (since it's client side)
Here's some of my code to help
while($staff_info = mysqli_fetch_array($select_staff)) {
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Hoping to get some help and this I search Google but can't find nothing I might be doing it wrong for this type of system
Thanks!
You can give each box a unique id like this with your code:
while($staff_info = mysqli_fetch_array($select_staff)) {
$id = $staff_info['id']; // assuming you have an id field in your DB
$account_name = $staff_info['account_name'];
$position = $staff_info['position'];
$description = $staff_info['description'];
echo "
<div id='staff_boxes_$id'> <text style='float:right;'> <a href='#' class='delete_button'> X </a> </text>";
echo"
<h2>$account_name</h2>
$position
<p>$description</p>
</div> ";
}
Alternatively, you can give all the divs the same class (e.g. <div class="staff_box"> ... </div> then use jQuery like this:
$('.staff_box').each(function(index) {
var box = $(this);
box.children('.delete_button').click(function(event) {
event.stopPropagation();
box.hide();
})
});

Zend forms working with ajax/javascript onchange event

I am writing a code to use onchange in my application this is my code so far
.Phtml
<script type="text/javascript">
function submit()
{
$id = intval($_GET['id']);
$satellite = intval($_GET['satellite_id']);
if ($id == 0)
{
echo "Please select a Region";
}
else
{
$query = "select * from satellites where region_id = '".$id."'";
$query = mysql_query($query);
echo "<select name='satellite_id'><option value=''>-- select one --</option>";
while ($row = mysql_fetch_assoc($query))
{
echo "<option value='".$row['satellite_id']."'".($row['satellite_id']==$satellite?" selected":"").">".$row['satellite_name']."</option>";
}
echo "</select>";
//DisplayFormRow ("Satellite", FormDropDownBox ("satellite_id", $SatelliteARY, $Result['satellite_id']));
}
}
</script
//zend code Form
$region_name = new Zend_Form_Element_Select('region_name');
$region_name->setAttribs(array('style' => 'width: 150px;'));
$region_name ->setLabel('Region')
->onchange('this.form.submit();') //tried this code ->onchange('javascript:submit();')
->addMultiOption('--Select One--', '--Select One--');
$mdlRegions = new Model_Regions();
$regions = $mdlRegions->getRegions();
foreach ($regions as $region)
{
$region_name->addMultiOption($region->region_id, $region->region_name, $region->region_short_name);
}
//model
<?php
class Model_Regions extends Zend_Db_Table_Abstract
{
protected $_name = 'regions';
//protected $_name = 'smmedetails';
public function getregion($region_id)
{
$region_id = (int)$region_id;
$row = $this->fetchRow('region_id = ' . $region_id);
if (!$row) {
throw new Exception("Could not find row $region_id");
}
return $row->toArray();
}
public function smmedetails2region($region_name)
{
$data = array(
'region_name'=> $region_name
);
return $this->insert($data);
}
public function getRegions()
{
$select = $this->select();
return $this->fetchAll($select);
}
}
//controller
public function registerAction()
{
$this->view->headScript()->appendFile('/js/ui/jquery.ui.autocomplete.js');
$form = new Form_SmmeDetails();
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$companyname = $form->getValue('companyname');
$companytradingname = $form->getValue('companytradingname');
$region_name = $form->getValue('region_name');
$satellite_name = $form->getValue('satellite_name');
$city = $form->getValue('city');
$companyaddress = $form->getValue('companyaddress');
$addresscode = $form->getValue('addresscode');
$companypostaladdress = $form->getValue('companypostaladdress');
$postalcode = $form->getValue('postalcode');
$companyphonenumber = $form->getValue('companyphonenumber');
$companyfaxnumber = $form->getValue('companyfaxnumber');
$companycellnumber = $form->getValue('companycellnumber');
$businessemailaddress = $form->getValue('businessemailaddress');
$businesswebsite = $form->getValue('businesswebsite');
$smmedetails = new Application_Model_DbTable_SmmeDetails();
$smmeid = $smmedetails ->smmedetailsSmmeDetails($companyname, $companytradingname, $region_name, $satellite_name, $city, $companyaddress, $addresscode, $companypostaladdress, $postalcode, $companyphonenumber, $companyfaxnumber,
$companycellnumber, $businessemailaddress, $businesswebsite);
// $region = new Application_Model_DbTable_Region();
//$region ->smmedetails2region($formData, $smmedetails->smmeid);
$this->_redirect('/admin/smme/register2/smmeid/'.$smmeid);
} else {
$form->populate($formData);
}
}
}
The code is suppose to view a hidden input select, called satellite when you select a feild option from regions, the satellite should view certain options based on the region selected. In short the region selected should correspond with what the user selected. eg Province is Gauteng, so cites would be, Johannseburg,Pretoria etc. Take note the region and satellite options are called from the database table according to they names and id. The code above keeps giving me and error Message: Method onchange does not exist. Was told not to use onchange method should I be using ajax and can I use javascript and sqlquery in the view or should I call it as an action? If so how? Here is a slight picture example.
Please be of help
Thanks in advance
I'd make a few suggestions to what you have there.
Firstly, for simplicity, I'd not use the onChange function, because I don't see it in the API, plus JavaScript or jQuery written in that way can become difficult to maintain and write properly. It is a lot simpler to instead include an external JavaScript file. By doing this, you can also test and debug the JavaScript separately, as well as reuse it.
Have a look at the excellent document for onChange, and getJson. I've used these and others and they're quite straight-forward. For testing, I recommend QUnit for starters. It makes testing a breeze.
Secondly, if you're using the Zend libraries for Model_Regions and $region_name, then I'd suggest using them instead of the direct mysql calls as well. This will allow you to build a good library which you can continue to expand as needed, plus it makes composing SQL quicker and safer.
For the controller, I'd suggest a RestController with a Restful Route. Here's an excellent tutorial.
I hope this helps you out with the problem. If you need anything more, let me know.
Thanks for emailing me about this.
The way I go about this is as follows:
Firstly I set up the form, and then an action in a controller.
Lets say getmajorgroupAction()
which in that action I would then disable layout, and just get the relevent results based on the id.
Then in the view file, loop through the
so the output from that call would be
<option value="1">1</option>
<option value="2">2</option>
etc
Personally I use jquery now, whereas the post you referenced when you emailed me, I was using another method.
trying to use something like this
jQuery(document).ready(function() {
jQuery("#division").change(function () {var division = jQuery("#division").val();
jQuery("#major_group").load("/module/getmajorgroup/", {division_id: division} );});
});
Hope that makes sense.
Thanks that was useful but i found a way to do it using this formula below, but everytime I click on the first select the while still in the session the second select appears all the time, eg if a person choose the wrong selection and re tried it brings up another field instead of fixing the field. I think its in a countinous loop . heres my script
<script type="text/javascript">
$(document).ready(function() {
$("#region_name").on('change', function () {
ajaxAddField();
}
);
}
);
// Retrieve new element's html from controller
function ajaxAddField()
{
$.ajax(
{
type: "POST",
url: '<?php echo $this->baseURL()?>/admin/ajax/get-cities/city/' + encodeURIComponent($('#region_name').val()),
success: function(newElement) {
// Insert new element before the Add button
//$(this).prev().remove().end().before('#city-label');
$("#city-label").before(newElement);
}
}
);
}
</script>

Categories