Steve
Steve

Reputation: 89

Rails render json displaying on screen

I have a Rails 5.1 app using Webpacker, jQuery 3. I'm trying to render json back to the browser after making an Ajax post. Here's my controller:

def create
  @giver = Giver.new(giver_params)
  return unless @giver.valid?
  if @giver.save
    render json: { location: 'url' }, status: :ok
  end
end

Here's my javascript (I have a route that directs /give to the controller's create method):

  $form.get(0).submit();

  var jqxhr = $.ajax({
      url: '/give',
      type: 'POST',
      dataType: 'json',
      data: $form.serialize()
    })
    .done(function() {
      console.log(jqxhr['responseText']);
      $('#new-gift').hide(function() {
        $('#confirm-gift').show();
      });
      return false;
    })
    .fail(function() {
    })
    .always(function() {
    });
}

I've done this so many times without any trouble, but for some reason it's now rendering

{"location":"url"}

on the screen, not performing any of the functions (hiding/showing divs) in the .done call. It saves everything to the db just fine, as well. I figured the return false; in the .done section would do the trick, but it doesn't. Any ideas? I can't see any other questions that address this - if they are out there, please direct me to the answer. Thank you.

.container.active-div#new-gift
  = form_for @giver, url: give_path, remote: true, html: { id: "payment-form" } do |f|
    %h3 Your Information
      .panel-body
        .row
          .col-md-6
            = f.text_field :first_name, class: "form-control", placeholder: "First Name"
            %br/
          .col-md-6
            = f.text_field :last_name, class: "form-control", placeholder: "Last Name"
            %br/          
    .row
      .col-md-12.text-center
        %br/
        = button_tag "Donate", class: "btn btn-primary btn-lg submit", style: "width: 150px; margin-bottom: 50px;"

Upvotes: 2

Views: 538

Answers (1)

Muhammed Anees
Muhammed Anees

Reputation: 1850


Since you are triggering a manual ajax form submission, remote: true is not required in the form. Just remove remote: true from the form and prevent the form submission event once it is triggered. Then, the code will look like

 $("#payment-form").submit(function(event){
   var jqxhr = $.ajax({
      url: '/give',
      type: 'POST',
      dataType: 'json',
      data: $form.serialize()
    })
    .done(function() {
       console.log(jqxhr['responseText']);
       $('#new-gift').hide(function() {
         $('#confirm-gift').show();
       });
    });
    .fail(function() {
    })
    .always(function() {
    });
    event.preventDefault();
 });


Hope this will help.

Upvotes: 3

Related Questions