MD.MD
MD.MD

Reputation: 718

how to take value from drop down list by ajax and send it to php?

I have a drop down list of some categories names, I want to take the name of the selected category by using ajax and send them to the same php page that the ajax script is inside it, here is my new code:

create action code:

public function actionCreate()
    {
        $model=new News;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

                if(isset($_POST['category']))
                       $category = $_POST['category'];
                   else
                       $category = NULL;

        if(isset($_POST['News']))
        {
            $model->attributes=$_POST['News'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model, 'category'=>$category
        ));
    }

form code:

<div class="row">
        <?php echo CHtml::label('Choose category to add from',''); ?>
                <?php $data = array('celebrities'=>'Celebrities', 'events'=>'Events', 'videos'=>'Videos', 'editorials'=>'Editorials'); ?>
        <?php echo CHtml::dropDownList('category', '', $data); ?>
    </div>
        <script type="text/javascript">

            $("#category").change(function(){
                var category = $(this).val();

            $.ajax({
                url:'/tonyward/index.php/news/create',
                data:{category:category},
                type:'POST',
                dataType:'html',
                success:function(data) {
                    console.log(data.category)
                },
                cache:false
            });
        });
        </script>

        <div class="row">
        <?php echo $form->labelEx($model,'idItem'); ?>
                <?php $data = array('celebrities'=>$category); ?>
        <?php echo CHtml::dropDownList('subcategory', '', $data); ?>
                <?php echo $form->error($model,'idItem'); ?>
    </div>

now how should the data of the second drop down list will changed ?

old code :

<div class="row">
            <?php echo CHtml::label('Choose category to add from',''); ?>
                    <?php $data = array('celebrities'=>'Celebrities', 'events'=>'Events', 'videos'=>'Videos', 'editorials'=>'Editorials'); ?>
            <?php echo CHtml::dropDownList('category', '', $data); ?>
        </div>

    <script type="text/javascript">

        $("#category").change(function(){

            $("#category").change(function(){

                var category = $(this).val();

                $.ajax({
                    url:window.location.href,
                    type:'GET',
                    data:{category:category},
                    dataType:'json',
                    cache:false,
                    success:function(data){

                    },
                });
            });
    </script>

    <?php 
        if(isset($_GET['category'])){

            $category = $_GET['category'];

            echo "<script>alert('done');</script>";
        }
    ?>

Upvotes: 0

Views: 1359

Answers (3)

MD.MD
MD.MD

Reputation: 718

how did I solved my problem?

  1. I have created a function named selectedCategory().
  2. selectedCategory() is renderPartial the html code of the drop down list, that are written in _categoryItems.php.
  3. I called an ajax function on the change of the first drop down category ('#category').
  4. the ajax function will be posted to selectedCategory(), and finally it will load html data (on success) in a specific div.

here is the codes:

form and ajax function code:

<div class="row">
        <?php echo CHtml::label('Choose category to add from',''); ?>
                <?php $data = array('Celebrities'=>'Celebrities', 'Events'=>'Events', 'Videos'=>'Videos', 'Editorials'=>'Editorials'); ?>
        <?php echo CHtml::dropDownList('category', '', $data, array(
                    'empty'=>'select category'
                )); ?>
    </div>
        <script type="text/javascript">

            $(function() {

                document.getElementById('itemslabel').style.display='none';
            });

            $("#category").change(function(){

                document.getElementById('itemslabel').style.display='block';
                var category = $(this).val();

                if(category === ''){

                    document.getElementById('items').style.display='none';
                }

                else{

                    $.ajax({
                        url:'/tonyward/index.php/news/selectedCategory',
                        data:{category:category},
                        async:true,
                        type:'POST',
                        dataType:'html',
                        success:function(data) {

                            document.getElementById('items').style.display='block';
                            $('#categoryItems').html(data);
                        },
                        cache:false
                    });
                }
        });
        </script>

        <div class="row" id="items">
        <?php echo $form->labelEx($model,'idItem', array('id'=>'itemslabel')); ?>
                <div id="categoryItems"></div>
                <?php echo $form->error($model,'idItem'); ?>
    </div>

action selectedCategory code:

public function actionSelectedCategory(){

            if(Yii::app()->request->isAjaxRequest){

                $category = $_POST['category'];

                $this->renderPartial('_categoryItems', array(
                   'category'=>$category 
                ));
            }
        }

_categoryItems code:

<?php $data = CHtml::listData($category::model()->findAll(), 'id', 'thumbtitle'); ?>
<?php echo CHtml::dropDownList('subcategory', '', $data); ?>

Note: I displayed and hid some elements by my js code.

Upvotes: 0

PeterKA
PeterKA

Reputation: 24638

Do you know that your page AJAX call returns the WHOLE PAGE plus <script>alert('done');</script>? Which is really NOT json as specified by the dataType option. Therefore, I expect that there will be a parse error and there's no .error handler to fire. And if the call was to be successful, you do not render what's is returned ... therefore you wont see the alert.

Suggestions

  1. Change your PHP script so that when category is set only the code within the if block is returned
  2. Instead of <script>alert('done');</script> just use done ==> `echo "done"
  3. In the success handler include alert( data )
  4. Change dataType to text
  5. Include an error handler just in case.
  6. When asking a question based on client-side code it's usually helpful to include the HTML (rendered by your browser) of the relevant part(s) instead of server-side code. I cannot tell what category in the PHP code is: id or name ... and many others may have the same issue and would avoid the question.

Upvotes: 1

charlietfl
charlietfl

Reputation: 171669

A select tag has no href so this.href isn't going to produce a valid URL for your AJAX.

Upvotes: 1

Related Questions