Matthew Smith
Matthew Smith

Reputation: 123

DOM element properties undefined - jquery / ruby on rails

I'm running into a problem with a Rails app I'm working on. Objects are successfully saving to the database but when they are rendered in the DOM, their properties are initially showing up as undefined. When I refresh the browser everything is fine.

I'm not sure where this problem needs to be addressed.

Document.ready:

$(function() {
    fetchClientsAndJobs();
});

The functions in question:

function fetchClientsAndJobs() {
    $.get('/clients').done(function(clientData) {
        clientData.forEach(renderClient);
        $.get('/jobs').done(function(jobData) {
            jobData.forEach(renderJob)
        });
    });
}

and:

function addClient() {    
    var clientNameInput = $('input[name="name"]').val();
    var clientRateInput = $('input[name="rate"]').val();
    var clientEmailAddress = $('input[name="email-address"]').val();
    var newClient = {
        client: {
            name: clientNameInput,
            rate: clientRateInput,
            email_address: clientEmailAddress
        }
    };
    $.post('/clients', newClient).done(function(clientData) {
        renderClient(clientData)
        });
    $('input[name="name"]').val('');
    $('input[name="rate"]').val('');
    $('input[name="email-address"]').val('');
}

Controller action:

def create
    @client = Client.new(client_params)
    @client.user_id = session[:current_user]
    if @client.save
        redirect_to root_path
    else
        redirect_to new_client_path
    end     
end

Any input would be appreciated. Thanks!

Upvotes: 0

Views: 87

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

Your client side code seems to be expecting the post to the create action to return data about the newly created client (since you are calling renderClient in your done.

However your create action redirects to the root of your app - I don't know what that renders but almost certainly not the data you expect.

Typically you'd have something along the lines of

respond_to do |format|
  format.json { render json: @client } #or whatever you are using to serialize your models to json
  format.html { redirect_to root_path }
end

Upvotes: 1

Related Questions