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

The effectiveness of a nested for loop

In the process of developing a web-based scheduling application, I am integrating a page where users can view a schedule along with a data table. The schedule serves as a tool for reserving slots while also displaying existing reservations from various use ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

Experiment with jQuery and JavaScript compatibility specifically on Internet Explorer 6

Seeking advice on the most effective method to test my web app using IE6. I currently have IE8 installed on my computer, and am considering utilizing a Virtual Machine. Are there any other alternatives worth exploring? It is imperative that my jQuery and ...

Clicking to Load Images - Angular

Implementing a feature to load sets of images on button click instead of loading all at once. Although lazy load plugins are available, I decided to experiment with this approach. Here's the logic: Start with a data array called 'Images' co ...

Chai-http does not execute async functions on the server during testing

In my app.js file, there is a function that I am using: let memoryCache = require('./lib/memoryCache'); memoryCache.init().then(() => { console.log("Configuration loaded on app start", JSON.stringify(memoryCache.getCache())); }); app.use( ...

What is the technique for accessing dynamic object properties in Javascript?

I am dealing with a dynamic object where the property values change based on different data sets. For example: MyObj = { country:"Ind", Place:"Pune"} Now, I have a data value that determines which property value I need to retrieve. var MyArr = this.Filt ...

The functionality of two-way binding in a distinct controller is not functioning properly when integrated with angular-wizard

I've been working hard to integrate this amazing wizard controller into my project: However, I've hit a roadblock with two-way binding not functioning as expected outside of the <section> attribute: http://plnkr.co/edit/N2lFrBRmRqPkHhUBfn ...

Does the user need to download the scripts from Google API multiple times during the insertion process?

Concerned about the potential need for multiple downloads of a script from an unknown location on the user's computer, I would like to explore options to mitigate this issue. Specifically, I am considering creating a condition to check the download st ...

JavaScript: Accessing the selectedIndex of a dropdown list in RadGrid

Currently facing an issue with utilizing the RadGrid control from Telerik. I am attempting to access and manipulate the value of a GridDropDowncolumn within RadGrid using JavaScript (while in edit mode). Does anyone have any suggestions for the correct Ja ...

How can JS be used to create content without refreshing the page?

On my website, I have a staff directory where each individual can be selected by clicking on their profile. When a staff member is clicked, a jQuery mobile popup opens and loads dynamic content using AJAX. Within this popup, users have the option to delete ...

Why is the responseText of an AJAX request empty on Chrome?

Why does this simple AJAX request work in IE but not Chrome? Check out the code below: var x = new XMLHttpRequest(); x.open("GET","style.php",true); x.send(); alert(x.responseText); The last line triggers an empty 'alert' window. Here's ...

Executing a callback in Node.js after a loop is complete

As a newcomer to Node, I have been facing difficulties with the asynchronous nature of the platform while attempting to append data in a for loop of API calls. function emotionsAPI(data, next){ for(let url in data) { if(data.hasOwnProperty(url ...

Hide Address with Jquery Dialog Box

How can I securely redirect a user to another page within the same website? In my specific situation, I have a form where users input information. For cancellations, they should have options available. When a user clicks the cancellation button, a dialog ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

Modify a property of an object using the useState Hook, where the property name is dynamically retrieved from a variable

const [fee, setFee] = useState({newPatient:'',establishedPatient:''}) const field1='newPatient' const field2='establishedPatient' To modify the fee object properties, I am looking to dynamically assign ...

Are NPM and Eslint supposed to be this confusing, or am I missing something?

Recently, I've started delving into the world of JS and have been eager to learn more about linting. Following a tutorial, we set up the lint stage in our package.json file. The configuration looks like this: "lint": "./node_modules/.bin/eslint ." U ...

Adjust the size of a Highcharts chart before printing

I'm facing an issue with a chart that doesn't have a specified height or width. My goal is to print the graph in a taller and larger size when I click on the print button. I attempted to use setSize() function, but since there are no original di ...

How selection.join behaves when every node contains child elements

I have been following the amazing tutorial on to learn more about the join paradigm. Everything was working fine until I tried to make each node more complex by adding a group with text inside. The main group gets updated, but the child one does not. Sn ...

Ensure that background elements do not become the focus when using MUI backdrop

Currently, we are implementing screen dimming when a custom dialog is open using MUI backdrop. However, even though the screen is "grayed-out," users can still access the items with the keyboard. In the image below, you can see how I move from "show backd ...

Storing images in a file system in Ruby on Rails can be done using various methods

Comparing Two Models Assets - utilized for file uploads using paperclip. class AddAttachmentsPhotoToAsset < ActiveRecord::Migration def self.up add_column :assets, :photo_file_name, :string add_column :assets, :photo_content_type, :string ...