javascript - Undefined append after an ajax post in rubyonrails -


i'm trying append information after posting ajax

this routes:

match 'api/people/', to: 'people#people_get_all', via: [:get] match 'api/people/:id', to: 'people#people_get', via: [:get]  match 'api/people/', to: 'people#create', via: [:post] 

this javascript:

var $people = $('#people'); var $first_name = $('#first_name');  $('#add_user').on('click', function(){      var person = {         person: {             first_name: $first_name.val(),             last_name: $last_name.val(),             location: $location.val(),             phone: $phone.val()         }     };      $.ajax({         type: 'post',         url: '/api/people/',         data: person,         success: function(newperson){             $people.append('<p><strong>first name: </strong>' + newperson.first_name + '</p>');         },         error: function(){             alert('error saving person database');         }     });  }); 

when click on button, save record in database when append happens brings undefined value.

do have wrong here?

this controller:

before_action :set_person, only: [:show, :edit, :update, :destroy] def create   @person = person.new(person_params)    respond_to |format|     if @person.save       format.html { redirect_to @person, notice: 'person created.' }       format.json { render :show, status: :created, location: @person }     else       format.html { render :new }       format.json { render json: @person.errors, status: :unprocessable_entity }     end   end end  private    def set_person     @person = person.find(params[:id])   end     def person_params     params.require(:person).permit(:first_name, :last_name, :location, :phone)   end 

this happens after pressing button, brings undefined

enter image description here

you need tell $.ajax response json, using datatype: option.

$.ajax({     type: 'post',     url: '/api/people/',     data: person,     datatype: 'json',     success: function(newperson){         $people.append('<p><strong>first name: </strong>' + newperson.first_name + '</p>');     },     error: function(){         alert('error saving person database');     } }); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -