Todd Williams
Todd Williams

Reputation: 267

Not able to populate form with server copy of json array without refreshing

I'm trying to populate my form with the server copy of my json array, but it seems to be pulling from the local copy. Right now I have a function that populates the form when I click on a rectangle (each of which represents a json object in the array).

For example, if I change the select option attributeName on the form and submit, it saves the change correctly to the server in the json array, but when I click on a different rectangle and come back to the rectangle with the change, it doesn't populate the form field with the change (doesn't pull from the server json array).

If I load a different array, or if I refresh the page, then it works...how can I get my local copy of the array to reflect the change without refreshing?

Here is the function:

$(function() {
  function populateForm() {

    var matchingWidth = $('#canvas-overlay > .rectangle.targeted').width();
    $(".rectangle.null").each(function() {
      if ($(this).width() === matchingWidth) {
        var ID_clicked = $(this).attr('id');

        // populate form function
        function populate(frm, data) {
          $.each(data, function(key, value){
              var ctrl = $('[name='+key+']', frm);
                    switch(ctrl.prop("type")) {
                        case "radio": case "checkbox":
                            ctrl.each(function() {
                                if($(this).attr('value') == value) {
                                  $(this).prop("checked", true);
                                  $("#attribute-form .ui.radio.checkbox").removeClass('checked');
                                  $(this).parent().addClass('checked');
                                }
                            });
                            break;
                        default:
                            ctrl.val(value);
                    }
            });
          }
          var selection = $('#templateSelection > option:selected').text();
          // create variable for and expose JSON
          var json = (function () {
            var json = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': 'server/php/data/' + selection,
                'dataType': "json",
                'success': function (data) {
                    json = data;
                }
            });
            return json;
          })();
          // search json for index value that matches id clicked
          // and populate form with associated object
          json.some(function(e) {
            if (e.ID === ID_clicked) {

                var values = json.map(function(e) { return e.ID; });
                var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);

                var data = JSON.stringify(json[index]);
                populate('#attribute-form', $.parseJSON(data));

                return true; // stops the "loop"
            }
          });
        }
      });
  }
  $(document).on('click', '#canvas-overlay > .rectangle', function() {
    $('#canvas-overlay > .rectangle').removeClass('targeted');
    $(this).addClass('targeted');
    populateForm();
  });
});

and for reference here is process.php which is the action when submitting:

<?php

   $filename = $_POST['store-template-name'];
   $myFile = "data/" . $filename;
   $arr_data = array(); // create empty array

  try
  {
       //Get form data
       $formdata = array(
          'ID'=> $_POST['ID'],
          'attributeName'=> $_POST['attributeName']
       );
       //Get data from existing json file
       $jsondata = file_get_contents($myFile);
       // converts json data into array
       $arr_data = json_decode($jsondata, true);
       $updateKey = null;
       foreach ($arr_data as $k => $v) {
            if ($v['ID'] == $formdata['ID']) {
                $updateKey = $k;
            }
        }
        if ($updateKey === null) {
            array_push($arr_data,$formdata);
        } else {
            $arr_data[$updateKey] = $formdata;
        }

       $jsondata = json_encode($arr_data);

       if(file_put_contents($myFile, $jsondata)) {
            echo 'Data successfully saved';
        }
       else
            echo "error";
   }
   catch (Exception $e) {
            echo 'Caught exception: ',  $e->getMessage(), "\n";
   }
?>

Upvotes: 1

Views: 47

Answers (1)

epascarello
epascarello

Reputation: 207527

get requests are cached, either have serverside set proper no cache headers or set cache to false in jQuery.

         $.ajax({
            'async': false,
            'global': false,
            cache: false,
            'url': 'server/php/data/' + selection,
            'dataType': "json",
            'success': function (data) {
                json = data;
            }
        });

And do yourself a favor and refactor your code to not by synchronous. Synchronous calls are a bad idea. The code after the json code should live in the success callback or use done which is the recommended way with jQuery.

Upvotes: 1

Related Questions