Pass id from the edit form in Javascript - javascript

I am trying to pass data from a form and table to edit a form, using JavaScript. The problem is that it doesn't update the form and table when I try to edit it. Can someone at least help me by giving me an example of what the code should be?
function SYS_add_product_form(){
var pullout_id=$('#tbl_pending_pullout_id').val();
$('#dialog1').remove();
$('body').append("<div id='dialog1'></div>"); /*Creates a virtual DOM <div id='dialog1'></div>*/
SYS_dialog3('#dialog1','495','950px','Create Pullout Request',function(){ });
$.post(URL+"index.php/pullout_request/loadPullOutRequestForm",{pullout_id:''}).done(function(data){
$("#dialog1").html(data).dialog("open");
});
}
function pullout_edit(x){
var pullout_id=$('#tbl_pending_pullout_id'+x).val();
SYS_dialog3('#dialog1','495','950px','Edit Pullout Request',function(){ });
$.post(URL+"index.php/pullout_request/loadPullOutRequestForm",{pullout_id:'edit'}).done(function(data){
$("#dialog1").html(data).dialog("open");
});
When adding there is no problem. But, I think maybe the problem is my elseif statement.
$pullout_id=$_POST['pullout_id'];
if ($pullout_id=='') {
$pullout_id=$this->mainmodel->getMaxId("across_pullout","pullout_id")+1;
$this->db->query("insert into across_pullout values('$pullout_id','$pullout_num','$date_requested','$user_accountid','','','','','','','0','$description','$counter','$year','1');");
for($x=0;$x<count($pid);$x++){
$pid1=$pid[$x];
$qty1=$qty[$x];
if($qty1==0){ $msg="All Quantities should be greater than zero"; }
$this->db->query("insert into across_pullout_items values('','$pullout_id','$pid1','$qty1','1');");
}
}else if($pullout_id=='edit') {
$sql .= "UPDATE `across_pullout` SET date_requested='$date_requested', `description`='$description' where pullout_num='$pullout_num' and remark='1';";
$sql .= "UPDATE across_pullout_items set pullout_qty='$pullout_qty' where remark='1';";
}

First of all, the way you use $this->db->query may cause query injection.
So I suggest you to use as follows.
$sql = "UPDATE `across_pullout` SET date_requested=?, `description`=? where pullout_num=? and remark='1'"
$this->db->query($sql, array($date_requested, $description, $pullout_num));
And $this->db->query() does not accept multiple queries.
So you need to call $this->db->query() twice to execute 2 queries.

Related

W3.js html table filter - onkeyup timeout

I am new to Javascript and need help with following problem:
Currently I have php page, where I generate html table from .xml file. Its working with this PHP function:
function xmlToHtmlTable($p_oXmlRoot) {
$bIsHeaderProceessed = false;
$sTHead = '';
$sTBody = '';
foreach ($p_oXmlRoot as $oNode) {
$sTBody .= '<tr class=item>';
foreach ($oNode as $sName => $oValue){
if (!$bIsHeaderProceessed) {
$sTHead .= "<th>{$sName}</th>";
}
$sValue = (string)$oValue;
$sTBody .= "<td>{$sValue}</td>";
}
$bIsHeaderProceessed = true;
$sTBody .= '</tr>';
}
$sHTML = "<table id=demo border=1>
<thead><tr>{$sTHead}</tr></thead>
<tbody>{$sTBody}</tbody>
</table>";
return $sHTML;
The table generated is pretty long and I need filtering option for it. I found simple solution that meets my requirements using w3.js filter table function. I have one input field that does the filtering:
<input onkeyup="w3.filterHTML('#demo', '.item', this.value)" placeholder="Filter">
Everything is working good but very slow, the table is +2000 lines long and the search is processing every single character typed and refreshing the results. What I need is to execute typed word/number/... after lets say 2 sec.
I have found similar questions here, but I cannot make it work with w3.js (maybe doing something wrong, as I said I am just beginning with JS).
In angularjs there is a concept called ng-minlength="2".. which means that search will be performed only after search string is 2 characters at least. So I made that in javascript. Instead of calling w3 js filter function directly, call only once the search string length is more than 2. Hope this helps..
<p>
<!--<input oninput="w3.filterHTML('#id01', '.item', this.value)" placeholder="Search for names..">-->
<input oninput="searchFilter(this.value)" placeholder="Search for names..">
</p>
<script>
function searchFilter(v) {
var n = v.length;
if(n>2) {
w3.filterHTML('#id01', '.item', v);
}
else {
w3.filterHTML('#id01', '.item', '');
}
}
</script>

PHP POST for HTML Select using another POST

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'])?>">

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