Interacting with Zend forms using AJAX and JavaScript's onchange event

I'm currently working on a code that utilizes the onchange event in my application. Here's the code snippet I have 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);
                }

        }
        }

I am trying to implement a functionality where a hidden input select called "satellite" is displayed when a region option is selected. The satellite options should vary based on the region selected. For example, if the user selects "Gauteng" as the region, the available cities could be "Johannesburg" and "Pretoria". The region and satellite options are fetched from a database table using their respective names and IDs. However, I keep encountering an error: "Method onchange does not exist." I was advised not to use the onchange method. Should I consider using AJAX instead? Can I use JavaScript and SQL queries in the view, or should I handle them as actions? Any guidance on this issue would be greatly appreciated.

Thank you for your assistance.

Answer №1

Here are a few recommendations for your current setup.

Instead of using the onChange function in JavaScript or jQuery directly within the HTML, consider including an external JavaScript file. This approach will make your code simpler to maintain and debug, as well as allowing for easier reuse in the future. Check out the documentation for onChange and getJson for more information on how to implement these functions effectively. When it comes to testing, consider using QUnit for a streamlined testing process.

Additionally, if you are utilizing Zend libraries for handling database queries, such as Model_Regions and $region_name, it is advisable to make use of these libraries instead of direct mysql calls. This will allow you to build a robust library that can be easily expanded upon in the future, while also ensuring that your SQL queries are composed more efficiently and securely.

For the controller, consider implementing a RestController with a Restful Route. You can refer to this tutorial for more detailed guidance on setting up RESTful services with Zend Framework.

I hope these suggestions prove helpful in resolving the issues you are facing. Feel free to reach out if you require any further assistance.

Answer №2

Thank you for reaching out with your inquiry. Here is my approach to the task:

Firstly, I create the form and then establish an action within a controller. Let's call it getmajorgroupAction(). Within that action, I disable the layout and retrieve the necessary results based on the provided ID. Subsequently, in the view file, I iterate through the results.

The resulting output from the call would look like this:

<option value="1">1</option>
<option value="2">2</option>

and so on.

Currently, I prefer using jquery for this task. In the previous post you mentioned in your email, I was utilizing a different method. Here is an example of how I implement it:

jQuery(document).ready(function() {
jQuery("#division").change(function () {
var division = jQuery("#division").val();
jQuery("#major_group").load("/module/getmajorgroup/", {division_id: division} );});
});

I hope this explanation clarifies things for you.

Answer №3

Appreciate the guidance, I managed to solve the issue by utilizing the formula provided below. However, I am encountering a recurring problem where the second select option consistently appears whenever I click on the first select. For instance, if a user selects the wrong option and tries again, instead of correcting the initial selection, a new field is generated. It seems to be stuck in a continuous loop. Here is the script I am currently using:

<script type="text/javascript">
$(document).ready(function() {
        $("#region_name").on('change', function () {
                ajaxAddField();
            }
        );
        }
    );

    // Fetch new element's HTML from the 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>   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I use more than one AudioContext at a time?

In my project, I am developing a React App using MeteorJS that utilizes the Web Audio API. This app consists of multiple pages, each of which utilizes web audio functionality. The issue I am facing is that I have hit the limit of 6 audio contexts allowed i ...

Unable to retrieve the parent element of an event target in AngularJS when using Internet Explorer 11

function determineClosestAncestor(startElement, callback) { const parent = startElement.parentElement; if (!parent) return undefined; return callback(parent) ? parent : determineClosestAncestor(parent, callback); }; $document.on('click', e ...

I noticed that when I use jQuery to add a class to an <li> element, the class is added successfully but then quickly removed. I'm wondering if this could be a conflict with

$(document).ready(function() { var $listItems = $('ul li'); listItems.click(function() { $listItems.removeClass('selected'); $(this).addClass('selected'); }); }); .selected{ background color: "green"; } / ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

Connecting radio buttons to data in Vue using render/createElement

How do you connect the value of a selected radio button to a specific variable in the data object within a Vue application when using the render/createElement function? ...

Implementing Bootstrap tooltips in content that can be scrolled

I need help with positioning two containers, which you can view in this FIDDLE. Both containers may contain a lot of content, so I have applied overflow: auto to both of them. This is the HTML structure: <div id="maincontainer"> <d ...

Exploring the concepts of arc functions in discord/js programming

Example: Having trouble understanding how to create an arc in JavaScript based on a percentage input? Here's a simple explanation: feed it a percentage and it will create an arc that represents that percentage of a circle. I've managed to get t ...

angular primeng table has a checkbox to select all checkboxes

Is there a way to check all checkboxes in a table when the checkbox in the table header is clicked? I am currently utilizing angular 12 and primeNG table for this functionality. <p-table styleClass="text-sm" [value]="value" [loading] ...

Unlocking request header field access-control-allow-origin on VueJS

When attempting to send a POST request to the Slack API using raw JSON, I encountered the following error: Access to XMLHttpRequest at '' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field acces ...

Displaying the chosen option from the V-menu in a different section of the application. Utilizing Vuetify

I'm working with a v-menu that has multiple options. I want to be able to display the selected option in another section of my application within the same component. Even though I attempted to use v-model for this purpose, it doesn't seem to work ...

Looping through properties of objects with the help of angularJS ng-repeat is known as using objects['propertyname&#

What is the best way to iterate over an object with property names like this? $scope.myobjects = [ { 'property1': { id: 0, name: 'someone' } }, { 'property2': { id: 1, name: ' ...

What could be causing my node.js postgres function to return undefined even though I verified the value is displayed in the console?

Currently, I am in the process of developing a node.js application with a PostgreSQL backend. I have implemented a pool of connections and made an INSERT query to the database where I anticipate the last inserted ID to be returned. However, while the query ...

Updating ASP Update panel causes unexpected issues with jQuery star rating system

After incorporating an updatePanel into my ListView, I encountered a problem with my rating system. Upon initial page load, everything appears fine using the krajee-star rating library: https://i.sstatic.net/JmWI5.jpg However, during a partial-postback, ...

Is there a way to extract a username from LDAP?

Can you help me understand how to dynamically retrieve a username from LDAP? In the code snippet below, I have hardcoded the username as 'smith2': $_SERVER["REMOTE_USER"] = 'smith2'; $param = $_SERVER["REMOTE_USER"] By using this appr ...

Using Javascript and Node.js to send a JSON request

While browsing through this particular question, I came across a method in node.js to distinguish between html requests and json requests: app.get('/route', function (req, res) { if (req.is('json')) res.json(data); else if (req ...

Tips for avoiding the automatic transition to the next slide in SwiperJS

How can I prevent the next button click in swiper based on my custom logic? I am using the swiperjs library within a Vue project and I need to stop users from swiping or clicking the next button to move to the next slide depending on certain conditions de ...

Refresh a specific div element within an HTML file when the AJAX call is successful

After uploading the image, I want it to be displayed right away. To achieve this, I am looking to refresh the div with id="imagecontainer" within the success function of my ajax call. However, I would prefer not to rely on ("$id").load("href") as it does ...

Incorporate a JavaScript variable within the src attribute of a script tag

Embedding Google's script allows for displaying a trends Map on our website. <script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&a ...