n4gash
n4gash

Reputation: 13

JQuery can't access new element after Ajax function

I have a form with several select inputs which are reloaded by Ajax when I changed a Date field. I want to keep the current selections when ajax reloads the select elements, but when I try to get them once the ajax function has reloaded the select elements I only get "Undefined".

The select objects are reloaded correctly using Ajax functions, but the problem is that I'cant keep the current selections.

I've defined the jQuery change event's handler of "#myDate" field on $(document).on.

$(document).on('change', '#myDate', function(e){ 
    callAjaxSelectClient( $("#idCity").val(), $('#idClientOpt option:selected').val());
    callAjaxSelectLuggage( $("#idCity").val(), $('#luggageOpt option:selected').val());     
});

I show you the ajax call (one example, all calls are similar). I send two parameters, idCity which it's a fix value, and the current selection of idClientOpt to keep it selected when the ajax call rewrites it.

function callAjaxSelectClient( idCity, idClientOpt )    {

            var params = {
                    "idCity" : idCity,
                    "idClientOpt" : idClientOpt,
            };

            $.ajax({
                    async: true,
                    data:  params,
                    url:   'ajax/reload.client.php',
                    type:  'post',
                    success:  function (response) {
                            $("#div-client").html(response);
                    }
            });
    }

The function calls "ajax/reload.client.php", which writes the html select code generate this code:

<select name="idClient" id="idClient">
    <option value="1">Miguel Cervantes</option>
    <option value="2">William Shakespeare</option>
    <option value="3">George Orwell</option>
</select>

Thanks, Cheers

Upvotes: 1

Views: 2467

Answers (4)

rrk
rrk

Reputation: 15846

You can save form data to a global JSON variable and repopulate.

Note : You need to make proper adjustments based on your situation.

<script>
  var $data = [];

  function callAjaxSelectClient(idCity, idClientOpt) {
      var params = {
          "idCity": idCity,
          "idClientOpt": idClientOpt,
      };
      $data = $("form#form_id").serializeObject();
      $.ajax({
          async: true,
          data: params,
          url: 'ajax/reload.client.php',
          type: 'post',
          success: function(response) {
              $("#div-client").html(response);
              repopulateForm();
          }
      });
  }

  //Create JSON from form.
  $.fn.serializeObject = function() {
      var o = {};
      var a = this.serializeArray();
      $.each(a, function() {
          if(o[this.name]) {
              if(!o[this.name].push) {
                  o[this.name] = [o[this.name]];
              }
              o[this.name].push(this.value || '');
          } else {
              o[this.name] = this.value || '';
          }
      });
      return o;
  };

  //Populate form
  repopulateForm = function() {
      $.each($data, function(name, val) {
          var $el = $('[name="' + name + '"]'),
              type = $el.attr('type');
          switch(type) {
              case 'checkbox':
                  $el.attr('checked', 'checked');
                  break;
              case 'radio':
                  $el.filter('[value="' + val + '"]').attr('checked', 'checked');
                  break;
              default:
                  $el.val(val);
          }
      });
  }
</script>

Upvotes: 0

n4gash
n4gash

Reputation: 13

Solved! the code is correct, the problem was on the ID of my select fields which I reload by Ajax ("idClient" instead "idClientOpt"), so when I tried to get the value of the new select reloaded, I didn't found it..

Thanks by your time.

Upvotes: 0

RuubW
RuubW

Reputation: 556

Try this:

bindAjaxSelectChange();

function callAjaxSelectClient( idCity, idClientOpt ) {
        var params = {
                "idCity" : idCity,
                "idClientOpt" : idClientOpt,
        };

        $.ajax({
                async: true,
                data:  params,
                url:   'ajax/reload.client.php',
                type:  'post',
                success:  function (response) {
                        $("#div-client").html(response);

                        bindAjaxSelectChange();
                }
        });
}

function bindAjaxSelectChange() {
        $(document).unbind('change').on('change', '#myDate', function(e) { 
                callAjaxSelectClient($("#idCity").val(), $('#idClientOpt option:selected').val());
                callAjaxSelectLuggage($("#idCity").val(), $('#luggageOpt option:selected').val());     
        });
}

Basically, dynamically added elements are not respected by existing event handlers so we need to rebind the event after every change. Notice the ".off('change')" - we're removing the old handler before anything else.

Upvotes: 1

Praveen D
Praveen D

Reputation: 2377

To solve this keep hidden in view page.

and load only ooption from callAjaxSelectClient function.

OR

you need to load jquery.js with ajax/reload.client.php

Upvotes: 0

Related Questions