"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected.

Check out my code below:

function submitViaAjax() {
    $("#new_comment_button").on("click", function (e) {
        e.preventDefault();

        url = $(this.form).attr('action')

        data = {
            'comment': {
                'content': $("#comment_body").val()
            }
        };

        var myJSON = JSON.stringify(data);

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            url: url,
            data: myJSON,
            // headers: { 'Content-Type': 'application/json' },
            success: function (response) {
                var $ul = $("div.comments_section ul");
                $ul.append(response)
            }
        }).done(function(response){
            debugger
            var $ul = $("div.comments_section ul");
            $ul.append(response)
        })
    })
};

Even though

var myJSON = JSON.stringify(data);
works well when run in the browser console, it seems like it's not functioning properly within my code.

I would greatly appreciate any assistance with this issue.

Answer №1

After some investigation, I discovered the reason for the unexpected lack of response. It turns out that instead of using a jQuery function, I mistakenly utilized JavaScript variable declaration to define myJSON.

To rectify this issue, all I had to do was remove var from

var myJSON = JSON.stringify(data);

UPDATE:

By implementing 'use strict'; within the function, it caused those variables to become undefined, leading me to believe that I may have been inadvertently overriding them - resulting in the 400 and/or 422 errors.

UPDATE 2:

The reason behind the 422 error was due to my data object containing a key named content while the parameter expected body instead.

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

Dealing with undefined or null values when using ReactJS with Formik

Issue Resolved: It seems that Formik requires InitialValues to be passed even if they are not necessary. I'm currently working on a formik form in React, but every time I click the submit button, I encounter an error message stating "TypeError: Canno ...

The Access-Control-Allow-Origin policy does not permit requests from applications running with an origin of null, specifically for those using a file:// URL

I am in the process of creating a webpage that utilizes jQuery's AJAX feature to fetch images from both Flickr and Panoramio. While the image retrieval from Flickr is functioning properly, I encounter an issue when attempting to use $.get(url, callba ...

I'm having trouble with my AJAX Update Panel. Can someone please help me figure out what I'm doing wrong?

--------------Handling Gridviews DataBound Event ----------------- protected void grdShowCallingList_DataBound(object sender, EventArgs e) { if (grdShowCallingList.Rows.Count > 0) { foreach (GridViewRow row in grdShowCallingList.Rows) ...

Leveraging Amplify for offline storage while transitioning between HTTP and HTTPS protocols

Recently, I encountered an issue with Amplify 1.0a1 on my website. It seems that when storing the value of prod_id in localStorage on a page using HTTP, and then navigating to a page using HTTPS (such as the 'list' page), I am unable to access th ...

Is Turbopack compatible with frameworks other than NextJs?

With its impressive speed, it would be great to utilize it in various outdoor projects like Vite. Unfortunately, there does not seem to be much information about it on their website I also checked out https://github.com/vercel/turbo but the details were s ...

Highlighting the current menu item by comparing the URL and ID

Looking to make my navigation menu items active based on URL and ID, rather than href. None of the suggested solutions (like this one, this one, or this one) have worked for me. This is how my Navigation is designed: <nav id="PageNavigation"& ...

The slider in Foundation 5 displays precision up to two decimal points

<div class="range-slider round" data-slider="1" data-options="display_selector: #questions_off_count; initial: 1; end: 4 ;"> <span class="range-slider-handle" role="slider" tabindex="0" aria-valuemin="0" aria-valuemax="4" aria-valuenow=" ...

Unable to center align a .swf file vertically

I recently added a .swf file to my webpage within a div element, and I attempted to center it vertically in the middle of the div. Unfortunately, my attempts were only successful in horizontal alignment, which is not the desired outcome. I even tried pla ...

Problem with fetching Grails

I have a table nested within an anchor tag. The table is centered on the page, with each row containing an image. When the page loads, I noticed the following: a) The table initially appears at the top-left corner of the screen. b) As there are multiple v ...

Jquery - Ajax: Error in Syntax JSON.parse: character not expected

I am encountering an issue with parsing JSON data on my client-side code. The JSON received from the server looks like this: [{"name":"Bubble Witch Saga 2","impressions":10749},{"name":"Grinder","impressions":11284},{"name":"Loovoo","impressions":12336},{" ...

Tips for patiently waiting for an axios request to finish

Within my vuejs application, I am faced with the challenge of initializing an object using data retrieved from an ajax call: let settings = {} api.readConfig().then((config) => { settings = { userStore: new Oidc.WebStorageStateStore(), author ...

Issue with loading controllers in route files [Node.js]

I've encountered an issue while trying to include a user controller into my routes for a node js app. Everything was working fine until suddenly it started throwing an error message. I've thoroughly checked the code for any potential issues but s ...

Spinning Wheel with Ajax in jQuery Mobile

When loading Ajax data for the next page, I am trying to display a spinning wheel. Interestingly, I can see the Ajax start and stop events in the console log, but the spinning wheels are not visible on the page! $(document).ajaxStart(function(){ conso ...

The jQuery form validator doesn't seem to work with AJAX for me, but I've figured out how to make jQuery validate without using

I have been facing an issue with my code that involves the jquery validator and ajax. The code seems to validate properly and the serialize() function appears to be working as I can see the data in the browser. However, the problem arises when the data d ...

Tips for invoking the ajax method repeatedlyWould you like to learn

I am facing an issue with my ajax call. In the code snippet below, the pageReload() function is automatically triggered when the page loads, subsequently calling the ajaxCall() function every 10 seconds. I am trying to invoke a method in a Grails control ...

JavaScript code: "Retrieve the div element and append metadata to the HTML file

Currently, I am utilizing the subsequent technique to save a target tag on my webpage as an HTML file. function retrieveHtml(filename, elId, format) { var htmlEl = document.getElementById(elId).innerHTML; if (navigator.msSaveBlob) { // IE 10+ ...

Retrieving the value from a concealed checkbox

I have been searching everywhere, but I can't seem to find a solution to this particular issue. There is a hidden checkbox in my field that serves as an identifier for the type of item added dynamically. Here's how I've set it up: <inpu ...

Sort with AngularJS: orderBy multiple fields, with just one in reverse

Currently, I am faced with the challenge of filtering data based on two variables: score and name (score first, followed by name). This task involves various games, some of which have scores in reverse order (like golf) while others maintain a normal scor ...

Function with defer that calls itself repeatedly

I am attempting to utilize a recursive function where each function runs only after the previous one has completed. This is the code I have written: var service = ['users', 'news'], lastSync = { 'users' : ...

What is the best way to use jQuery to retrieve information from one child element in an XML API in order to locate another child

Hi there, I'm new to jQuery and could use some help. I'm attempting to retrieve specific information like CPU and RAM details from a particular phone model. I've written the jQuery code, but I'm having trouble displaying the RAM and CPU ...