Issue with Remote Form in Rails: Encountering Syntax Error Due to Unexpected Token

I am trying to update a form:

<%= form_for([@group, lesson], remote: true) do |f| %>
            <tr id='<%= lesson.id%>' >
                <td><%= f.text_field :time %></td>
                <td><%= f.text_field :day %></td>
                <td><%= f.text_field :subject %></td>
                <td><%= f.text_field :teacher %></td>
                <td><%= f.text_field :room %></td>
                <td><%= f.submit 'Update'%></td>
                <td><%= link_to 'Delete', [lesson.group, lesson], remote: true,method: :delete%></td>
            </tr>
        <%end%>

This is the controller code:

def update

@lesson = @group.lessons.find(params[:id])

@lesson.update_attributes(params[:lesson])

respond_to do |format|
    if @lesson
        format.html { redirect_to edit_group_path(@group), notice: 'Successfully updated lesson' }
        format.js { render :json => @lesson, location: edit_group_path(@group) }
        format.json { render json: @lesson}
    else
        format.html { redirect_to edit_group_path(@group), notice:'Error!' }
        format.json { render json: @lesson }
    end
end
end

And here is the JavaScript part:

$(document).ready ->
    $('#new_lesson').on("ajax:success", (e, data, status, xhr) ->
        $('.notice').append data
        ).bind "ajax:error", (e, xhr, status, error) ->
            $('.notice').append '<p>ERROR:'+error+'</p>'

    $(".edit_lesson").on("ajax:success", (e, data, status, xhr) ->
        $('.notice').append data
        ).bind "ajax:error", (e, xhr, status, error) ->
            $('.notice').append '<p>ERROR:'+error+'</p>'

Although the request goes through successfully and entries are updated, I keep getting a syntax error in the '.notice' section:

SyntaxError: Unexpected token :

I have tried other solutions found online, but none of them seem to work for me.

Answer №1

It is important to gather more information about the error, such as which file and function is calling it. There may be an issue with the following line in your controller:

format.js { render :json => @lesson, location: edit_group_path(@group) }

Questionably, why are you passing JSON to a JS request? Typically, if you want JSON data back, you would use the datatype as JSON. If JSON is being used for an API or another purpose, further investigation will be necessary.

In my opinion, I recommend testing this line:

format.js 

Then, in update.js.erb, consider using the following:

alert(<%=j @lesson %>);

This test will help determine if that specific line is causing the problem. If so, adjustments to your system may be required. Please provide the outcome of this test, and we can offer a more precise solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to choose the initial p tag from an HTML document encoded as a string?

When retrieving data from a headless CMS, the content is often returned as a string format like this: <div> <p>1st p tag</p> <p>2nd p tag</p> </div> To target and select the first paragraph tag (p), you can extract ...

Encountering an issue with getDerivedStateFromProps in React where an error states: Unable to retrieve property 'setState' of null

Just found out that componentWillReceiveProps is deprecated and now we should be using the getDerivedStateFromProps lifecycle method. You can find more information about it at this link. This is how I'm implementing it: class Main extends Component ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

How can I generate codegen types using typeDefs?

I have been exploring the capabilities of graphql-codegen to automatically generate TypeScript types from my GraphQL type definitions. However, I encountered an issue where I received the following error message: Failed to load schema from code file " ...

Extending the href value using jQuery at the end

Can someone help me with this link: <a id="Link" href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2745425453424b4b524940674e0a4355464e4909494253">[email protected]</a>?subject=I-Drain Bestellung& ...

React Object Array Item State management

After spending a considerable amount of time on this task, I have been trying to achieve the functionality of changing a checked value upon checkbox click. Here is how my initial state is set up: const [todoList, setTodoList] = useState({ foundation: ...

Ember - connecting to a JSON data source

Recently, I have been following a tutorial/example from codeschool and everything is going well. However, the example code includes the line: App.ApplicationAdapter = DS.FixtureAdapter.extend(); Now, I want to maintain all the existing functionality but ...

Unable to display the popup modal dialog on my Rails application

I currently have two models, Post and Comment. A Post has many Comments and a Comment belongs to a Post. Everything is functioning properly with the creation of posts and comments for those posts. Now, I have a new requirement where when clicking on "crea ...

"Despite the successful execution of the PHP script, the error function in the Ajax POST request

I am working on developing a mobile app using jQuery, jQuery Mobile, and HTML with PhoneGap. I have successfully implemented AJAX to call PHP scripts on the server for tasks like updating, inserting data, and sending emails. However, I consistently encoun ...

Lightbox fails to function within Ajax.Updater container in prototype framework

Currently, I am utilizing an Ajax.Updater function to display information about a single rental listing in a div. The process begins with a dropdown menu containing all available rental listings, and the hidden div becomes visible once the user selects a s ...

What is the process for updating the source in an input box?

How can I use JavaScript to update the src value of an iframe based on input? <input class="url" id="url1" type="url" value="youtube url"> <input onclick="changevideo()" class="add-video" id="add-video1" type="submit" value="add to play ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

What sets Gulp-Browserify apart from regular Browserify?

After switching from Grunt to Gulp recently, I find myself still learning the ropes. Can anyone shed some light on the distinction between using Gulp-Browserify versus just Browserify? I've heard that Gulp-Browserify has been blacklisted and seen som ...

Which tool would be better for starting a new Angular project: angular-seed or yeoman?

I'm having trouble deciding on the best approach to create a new AngularJS application. There seem to be various methods available, such as using angular-seed from https://github.com/angular/angular-seed or yeoman - http://www.sitepoint.com/kickstar ...

What is the purpose of encasing the routes within the <Switch> element in react-router, when they seem to function perfectly fine without it

Currently utilizing react-router-dom version 5.2.0. As a practice, I typically enclose all my Route components within a Switch component. For instance: const MyRoutes = () => ( <Switch> <Route path='/route1' exact ...

Tips for ensuring an element is visible in CUCUMBER JS?

Whenever I run my code, it keeps returning the error message: NoSuchElementError: no such element: Unable to locate element Even though I have set up a wait function, it does not seem to actually wait. The step fails immediately without waiting for the s ...

Tips on placing a button at the bottom of the AppBar and keeping it fully responsive

I am attempting to place my login and log out buttons at the end of the AppBar. When I try forcing it with marginLeft: '70%',, it works but only on large resolutions. On smaller resolutions, the buttons go out of place. Here is an example of forc ...

Displaying identical images repeatedly, alter just one using JQuery with each change

In the design, I have both gray and blue stars displayed multiple times on the page. What I'm trying to achieve is that when a user clicks on a gray star, it should switch to blue, and vice versa. However, the current issue I'm facing is that cli ...

Utilizing dynamically assigned ng directives in my unique custom directive

I'm in the process of creating a customized table element that looks like this: <datatable items='tableItems' columns='columnsConfig' /> Here, 'tableItems' represents my array of items and 'columnsConfig&apos ...

Alter the color of the text within the `<li>` element when it is clicked on

Here is a list of variables and functions: <ul id="list"> <li id="g_commondata" value="g_commondata.html"> <a onclick="setPictureFileName(document.getElementById('g_commondata').getAttribute('value'))">Variable : ...