简体   繁体   中英

update page elements without refresh using ajax form submit

I have a form with nested attributes and an html list element on the same page. I'm handling the form submission using an AJAX request. On submit I want to stay on the same page and update the list to show the item that was just submitted without refreshing the page.

The code below shows the javascript for the submit handler. I would like be able to just append the form data to the list using jquery but I'm not having much luck. I have tried using rails unobtrusive javascript but couldn't make that work in this scenario either.

Any help would be greatly appreciated.

$('#new_box').submit(function(event){
    event.preventDefault();

    var cube = newCube($("#box_name").val(), 25, 25, 25);
    addCube(cube);

    var data = {};
    data["box"] = {};
    data["box"]["x"] = cube.position.x;
    data["box"]["y"] = cube.position.y;
    data["box"]["z"] = cube.position.z;

    var formData = $(this).serialize() + '&' + $.param(data);

    var locker_id = $('#my-canvas').data('locker').id;

    $.ajax({
      url: '/lockers/' + locker_id + '/boxes',
      method: 'post',
      dataType: 'json',
      data: formData,
      error: function(){
        alert("Could not add box!");
      },
      success: function(data){
        $('.box-list').append(formData);
      }
    });

  });

The list partial is as follows:

<ul class="list-group box-list">
    <li class="list-group-item box" id="<%= dom_id(box) %>" data-box="<%= box.to_json %>">
      <%= link_to box.name, "javascript:void(0)" %>
      <span class="badge"><%= box.items.count %></span>
      <ul class="list-group box-items">
        <% box.items.each do |item| %>
        <li class="list-group-item"><%= item.name %></li>
        <% end %>
      </ul>
    </li> 
</ul>
$('.box-list').append($(data).children());

I ended up rendering my ajax response as an html partial and then appending that partial in the success block of the ajax request.

Controller:

respond_to do |format|
      if @box.save
        @item = Item.new
        format.html { render partial: 'boxes/box_list', locals: { box: @box } }
      end
    end

javascript:

$.ajax({
      url: '/lockers/' + locker_id + '/boxes.html',
      method: 'post',
      data: formData,
      error: function(){
        alert("Could not add box!");
      },
      success: function(response){
        $('.box-list').append(response);
        $('input[type=text]').val('');
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM