I am currently using Rails to develop a webpage that allows users to submit contact information and create a contact object. The controller responsible for creating contacts is as follows:
def create
@contact = Contact.new(contact_params)
if @contact.save
render json: @contact, status: :created
else
render json: @contact.errors.full_messages, status: :unprocessable_entity
end
end
The "contact_params" method looks like this:
def contact_params
params.require(:contact).permit(:name, :email, :phone, :company, :message)
end
Although the form works well when handling everything through a redirect, I would like to handle the creation process using JavaScript. While this approach has worked for me in the past without any issues, when I try running the following code:
$(document).ready(function(){
$('#new_contact').on('submit', function(ev){
ev.preventDefault()
$.post({
url: $(ev.target).attr('action'),
data: new FormData(ev.target),
processData: false,
contentType: false,
success: function(data){
$('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm- offset-3"><h3>Thanks for contacting me,' + data.name + '. I will get back to you as soon as I can.</h3></div>')
document.getElementById('new_contact').reset()
$('#new_contact input[type="submit"]').prop('disabled', false)
},
error: function(error){
$('#new_contact').append('<div class="col-xs-12 col-sm-6 col-sm-offset-3"><h3>Sorry, I need at least a name and valid e-mail.</h3></div>')
$('#new_contact input[type="submit"]').prop('disabled', false)
}
})
})
})
However, upon hitting the post request, my server responds with the error message:
ActionController::RoutingError (No route matches [POST] "/[object%20Object]"):
This is an issue I have not come across before and I am uncertain of how best to address it. Any assistance on resolving this matter would be greatly appreciated.