We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Dynamic Option Ajax Phalcon

sorry for my bad english before.

I have problem when display dynamic value on multiple select using Ajax. Actually on view retrieve the data from controller, but list item on multiple select not change as the data from controller

Controller createAction()

public function createAction(){
    $form = new liistTopicForm(null);
    if ($this->request->isPost()) {
        $post = $_POST;
        $_POST['speciality[]'] = isset($_POST['speciality']) ? $_POST['speciality'] : null;
        $_POST['topic[]'] = isset($_POST['topic']) ? $_POST['topic'] : null;
        $_POST['type[]'] = isset($_POST['type']) ? $_POST['type'] : null;
        unset($_POST['type']);

        if (false == $form->isValid(\array_merge($_POST, $_FILES))) {
            $this->flash->error($form->getSummary());
        } else {
            $ins = new liistTopic();
            $ins->assign($_POST);

            Utility::getAdditionalProperty($_POST, $ins);

            if (true == $this->request->hasFiles()) {
                Utility::getFile($_FILES, $ins);
            }

            if (!$ins->createUsingTransaction()) {
                $this->flash->error($ins->getMessages());
            }

            $this->setTypeMsg($post,$ins);
            $this->flashSession->success('Created');
            $this->response->redirect('cats/'.$this->router->getControllerName());
            $this->view->disable();

            return;
        }
    }
    $this->view->form = $form;
}

Controller catListAction():

public function catListAction()
    {
        $this->view->disable();

        $this->jsonMessages = Schedule::getList($_POST['start']);

        return $this->jsonMessages;
    }

liistTopicForm() :

public function initialize($entity = null, $options = null)
{
    [
        'required' => $required,
        'numeric' => $numeric,
        'url' => $url,
        'file' => $file,
        'empty_file' => $empty_file,
        'date' => $date,
    ] = Form::Validators();

    $file = (isset($options['edit']) && $options['edit']) ? $empty_file : $file;

    //** name **//
    $this->add(Form::Text('name', [], [$required]));
    $this->add(Form::Text('start', [], [$required, $date]));
    $this->add(Form::Text('end', [], [$required, $date]));
    $this->add(Form::Select('tyoe[]', [ 'multiple' => true, 'label' => 'type', 'placeholder' => 'Type', 'id' => 'type' ], [$required], [
        "1" => "Type 1",
        "2" => "Type 2",
        "3" => "Type 3"
    ]));
    $list = Schedule::getList();
    $list[0] = 'All Topic';
    $this->add(Form::Select('topic[]', [ 'multiple' => true, 'label' => 'topic', 'placeholder' => 'Topic', 'id' => 'topic' ], [], $list));
    $list_p = Specs::getList();
    $list_p[0] = 'All Specs';
    $this->add(Form::Select('speciality[]', [ 'multiple' => true, 'label' => 'speciality', 'placeholder' => 'Select speciality', 'id' => 'speciality' ], [], $list_p));
    $this->add(Form::Image('attachment', [], [$file]));
    $this->add(Form::Hidden('_crop', ['value' => '{}'], []));
}

View create.volt:

<div class="card">
  {{ content() }}
  <div class="card-body">
    {{ form('method': 'post', 'autocomplete': 'off', 'enctype': 'multipart/form-data') }}
    {% for element in form %}
      {% if is_a(element, 'Phalcon\Forms\Element\Hidden') %}
        {{ element }}
      {% else %}
        {{ form.render(element.getName()) }}
      {% endif %}
    {% endfor %}
    <div class="form-group">
      <div class="row">
        <label class="col-sm-2"></label>
        <div class="col-sm-10">
          {{ submit_button("Save", "class": "btn btn-fill btn-primary") }}
        </div>
      </div>
    </div>
    </form>
  </div>
</div>

<script type="text/javascript">
  var date = new Date();
    date.setDate(date.getDate() + 1);
$(function() {

  $('#topic').parent().parent().hide();
  $('#speciality').parent().parent().hide();

  icons = {
    time: 'fa fa-clock-o',
    date: 'fa fa-calendar',
    up: 'fa fa-chevron-up',
    down: 'fa fa-chevron-down',
    today: 'fa fa-screenshot',
    clear: 'fa fa-trash',
    close: 'fa fa-remove',
    previous: 'fa fa-chevron-left',
    next: 'fa fa-chevron-right',
  };

  $("#start").datetimepicker({
    minDate: date,
    format: 'YYYY-MM-DD',
    icons,
  });
  $("#end").datetimepicker({
    minDate: date,
    format: 'YYYY-MM-DD',
    icons,
  });

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

    var value_start = $('#start').val();
    var value_end = $('#end').val();

      $("#type option:selected").each(function () {
          var value_type = $(this).val();
          var data_selected = $('#type').val();

          if(value_type == 2)
          {
            $('#topic').parent().parent().show();

            $.ajax({
                url:"cats/catList",
                dataType:'text',
                data : {type: value_type, start: value_start, end: value_end},
                type:"POST",
                success: function(result){
                    var obj = JSON.parse(result);
                    var html = "";
                    $.each(obj, function(datas,value){
                      // datas = id, value = name
                      html += "<option value='"+datas+"'>"+value+"</option>";
                    });

                    $('#topic').html(html);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                  alert(xhr.status + "\n" + ajaxOptions + "\n" + thrownError);
                }
            })
          }
          else if(value_type == 3)
          {
            $('#premium').parent().parent().show();
          }
          else
          {
            $('#topic').parent().parent().hide();
            $('#premium').parent().parent().hide();
          }

          if(data_selected.indexOf("2") == -1)
          {
            $('#topic').parent().parent().hide();
          }
          else if(data_selected.indexOf("3") == -1)
          {
            $('#premium').parent().parent().hide();
          }
      });

      $("#type ")
  }).trigger("change");
});
</script>

ControllerBase:

public function afterExecuteRoute()
{
    if($this->request->isAjax() == true) {
        $data = $this->dispatcher->getReturnedValue();
        $this->response->setJsonContent($data);
        return $this->response->send();
    }

    $this->view->setViewsDir($this->view->getViewsDir().'cats/');
}

actually ajax retrieve data from catListAction and success, but the list item option on topic not change. Is there something wrong in my script? NOTE : the result should be (just Topic 3) but in fact showed on Schedule::getList() result



8.4k
edited May '20

i'm not sure if i understand you issue

is the response you get from your ajax request is not what you wanted ?

if so can you tell us what does Schedule::getList() do ?

and can you tell us about your enviroment phalcon version, php version, operation system

edited May '20

getList() does is :

  • show all data from now and future, if not sending $POST['start']
  • show all data by date chosen, if sending $POST['start']

All data existing :

  1. Topic 1 (18 May 2020)
  2. Topic 2 (18 May 2020)
  3. Topic 3 (17 May 2020)

data showed what i wanted (using parameter $POST['start'] which is 17 May 2020):

  • show all data 17 May 2020

ajax result is (i try to var dump result and var obj) :

  • Topic 3 (17 May 2020)

but in fact the page load data from $list in listTopicForm, which mean is (i had make sure this when i try to inject some data to know what data is loaded):

  • Topic 1 (18 May 2020)
  • Topic 2 (18 May 2020)
  • Topic 3 (17 May 2020)

my question is :

  • why page not load data as ajax result? even though the data result and var obj just showed Topic 3

i hope you understand what i mean. Thanks before for your attention @talal424 and i hope you not confuse because of my English LOL



8.4k
edited May '20

so your issue is that the ajax request to catListAction() is not returning what you expect from it

in this case i'll need to see Schedule::getList()'s code

either way we need to see the output so after this line

$this->jsonMessages = Schedule::getList($_POST['start']);

dump $this->jsonMessages and $_POST['start']

and post it here with Schedule::getList()'s code

a piece of a advice using $_POST directly without any filtering is likely prone to malicious attacks so if you are using this code in production

i highly recommend filtering user input and never trust it at any circumstance using Phalcon\Request

check the documentation phalcon 3 and for phalcon 4

so your issue is that the ajax request to catListAction() is not returning what you expect from it

no, ajax request have return what i expect. But why on topic field always display result from $list = Schedule::getList(); from listTopicForm.php.

a piece of a advice using $_POST directly without any filtering is likely prone to malicious attacks so if you are using this code in production

i highly recommend filtering user input and never trust it at any circumstance using Phalcon\Request

thanks for the advice

actually i have solved this issue yesterday using selectizeJs, but i wonder why topic field can not show what i want just using ajax. Maybe you know why?



8.4k

i'm glad you solved your issue

your issue is most likely in javascript and not php by assuming you didn't change your php code

i need to see the actual data coming from the ajax request to pin point your issue