Troubleshooting issue with Rails 5.2.3 AJAX request: JSON key-value pairs containing the plus sign are not being received

In my Rails 5.2.3 project, I am attempting to send an AJAX request that includes a JSON representation of a callflow object (the specifics of which are not relevant). This JSON representation is located within a textarea with the id "newCallflowJsonDisplay". Here is an example of the JSON:

{
  "callflow": [
    {
      "action": "dial",
      "options": {
        "destination": 12121218
      },
      "label": "-"
    }
  ]
}

The javascript code I am utilizing is as follows:

return new Promise(function(resolve, reject){
        Rails.ajax({
            url: `some url`,
            data: `callflow_json=${document.getElementById('newCallflowJsonDisplay').value}`,
            type: "POST",
            success: function(response){resolve(response)},
            error: function(response){reject(response)}
        });
    }).then(function(res){
        console.log(res);
    }).catch(function(error){
        logError(error);
    })

When using the JSON representation and code provided above, everything functions as expected. The "label" key has a value of "-". I can see in my log:

<ActionController::Parameters {"callflow_json"=>"{\n  \"callflow\": [\n    {\n      \"action\": \"dial\",\n      \"options\": {\n        \"destination\": 12121218\n      },\n      \"label\": \"-\"\n    }\n  ]\n}", "controller"=>"callflows", "action"=>"manipulate", "callflow_id"=>"61"} permitted: false>

However, when I use the JSON below where the value for the "label" key is "+":

{
  "callflow": [
    {
      "action": "dial",
      "options": {
        "destination": 12121218
      },
      "label": "+"
    }
  ]
}

In the log, I can see:

<ActionController::Parameters {"callflow_json"=>"{\n  \"callflow\": [\n    {\n      \"action\": \"dial\",\n      \"options\": {\n        \"destination\": 12121218\n      },\n      \"label\": \" \"\n    }\n  ]\n}", "controller"=>"callflows", "action"=>"manipulate", "callflow_id"=>"63"} permitted: false>

It appears that despite ensuring that the JSON in the textarea is correct and contains the "+", when it reaches the server, the "+" sign is not present and does not show up in the log at all.

I have experimented with using letters, "*", and "/", all of which work except for "+". What could be causing this issue in my code?

Thank you in advance for any assistance!

Answer №1

Is it true that '+' is used to stand for a blank space in query strings? Perhaps it would be wise to encode the URL before sending...

Answer №2

It appears that ajax may be losing the plus sign when automatically parsing/stringifying your data. To avoid this issue, consider manually parsing the data before sending it in the ajax request. Here's an example of how you can do this:

var jsonData = '{ "callflow_json": { "callflow": [{ "action": "dial", "options": { "destination": 12121218 }, "label": "+" }] }}';

Then, simply include jsonData as your data in the ajax request so that it is parsed correctly.

Furthermore, the error message about parameters not being permitted may cause issues in the future. To address this, you could try something like:

params.require(:your_model).permit(:callflow_json)

Hopefully, these suggestions will help resolve the problem you are experiencing. Let me know if you have any further questions!

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

Adding Bootstrap alert messages dynamically and having them fade in and out

Is it possible to dynamically add a Bootstrap alert with a fadeIn effect and fadeOut effect on close without using jQuery fadeIn or fadeOut functions? function alert(title, text, type) { var html = $("<div class='alert alert-dismissible hide f ...

Creating an HTML structure that limits each li to only contain three div elements can be achieved using React and Underscore.js

To achieve this specific layout, I am looking to utilize only underscore.js functions. Below is the array that I have: var xyz = [{ 'name': 'test' },{ 'name': 'test1' },{ 'name': &ap ...

Function for Duplicating jQuery Events

I'm currently facing an issue where every time the browser is resized, a function is triggered. This function can turn a side panel into an accordion if the screen width meets certain criteria, or it can just display as an open side panel on larger sc ...

Tips for selecting a checkbox with Puppeteer

I've implemented the code in this way: await page.$eval('input[name=name_check]', check => { check.checked = true; }); This code is intended for multiple checkboxes. However, I need it to work for a single checkbox only. Is there a way ...

Tips for creating a PHP cURL request using the provided documentation

Can anyone help with creating a PHP cURL based on the following documentation? Here is the raw curl text: curl --location --request POST '/serviceRates' \ --header 'Content-Type: application/json' \ --header 'acce ...

Looping through a JSON array and encoding it using the `

I am looking to retrieve data from the database using AJAX and populate a 'select' tag with that data. Each name should be displayed in its own 'option'. Here is the code snippet: Index.php: <label>Select:</label> <sel ...

Transfer JSON data between controllers without utilizing Services or Factory in AngularJS during routing

On my Dashboard page, I have an Object. When a user clicks on the Details Page from the Dashboard, it should redirect to the Details page. I am looking to pass the JSON Object from the Dashboard Controller to the Details Controller. Is there a way to do ...

Attempting to trigger CSS transitions using JavaScript will not be successful

I'm facing an issue where CSS transitions do not work as expected when triggered by JavaScript. let isSearchBarOpen = false; function toggleSearchBar() { if (isSearchBarOpen) { searchBar.style.display = "none"; } else { searchBar.sty ...

Retrieving an array of objects from the database utilizing AJAX

I am trying to retrieve comments from a database and display them on my webpage. However, the current code is throwing a syntax error because the PHP file is not returning the JSON file properly. Here is a snippet of my PHP code (just the fetching part, n ...

Display numbers next to each other

My goal is to display the values next to each other. Below is an example and code of what I am trying to achieve. Can this be done? import requests import json r = requests.get('https://api.website.com',headers = {"content-type": "application/j ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

Execute the window.load function once the AJAX request has finished

I've integrated a WordPress theme with various styling options and functionality that are controlled by the header.php file. Here's a snippet of how it works: jQuery(window).load(function($) { <?php if($data['blog_pagination_type'] ...

What is the best way to display a div box only when a user checks a checkbox for the first time out of a group of checkboxes, which could be 7 or more, and then hide the

Is there a way to make a div box appear when the user checks any of the first checkboxes? I have attempted using the following codes: JQ Codes: $('#checkbox').change(function() { if ($(this:first).is(':checked')) { cons ...

Concentrate on Selecting Multiple Cells in ag-Grid (Similar to Excel's Click and Drag Feature)

Is there a way to click and drag the mouse to adjust the size of the focus box around specific cells in ag-Grid? This feature is very handy in Excel and I was wondering if it is available in ag-Grid or if there is a workaround. Any insights would be apprec ...

Bower consistently installs the most up-to-date version instead of the version that was explicitly specified

Despite the version specified in the "bower.json" file, bower (v1.8.0) doesn't adhere to it and instead downloads the most recent version of the library available. It seems like it's not taking the version into account at all. Even downgrading to ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...

What is the best way to set jade as a global variable in a node.js Express application?

Currently, the routing function shown below is operational: exports.summary = function(req, res, next) { var jade = require('jade'); res.render('myView', { main: jade.renderFile('./views/summary.jade') }); }; The ...

State of loading getServerSideProps in Next.js

Can we implement a loading state similar to when retrieving data on the client-side? I'm interested in having a loading state, maybe with a loading-skeleton like react-loading-skeleton On the client-side, we can achieve this by: import useSWR from & ...

javascript guide on converting an array into the correct JSON format

I'm working with an array that has the following structure: var arr = [ [{a:1}], [{b:1}], [{c:1}], [{d:1}], [{e:1}] ] My goal is to format it into the proper format as shown below: [{a:1},{b:1},{ ...

The connection to Cordova.js is established, but the deviceready event is not

I've included cordova.js in my project, called app.initialize();, but for some reason deviceready event is not being triggered. Any ideas on what might be causing this issue? Here's the JavaScript code: var app = { initialize: function() { ...