Saving data to a variable with AJAX/JSON when the column name is numerical: Best practices

When attempting to save a JSON value as a variable from an AJAX response ...

$.ajax({
url:'example.php',
type:'POST',
dataType: 'json',
success:function(data){

    var checkname = data.name;  // works fine
    var check1m = data.1m;      // SyntaxError occurs here

}
}); 

... and the column name starts with a number (e.g. 1m):

[{"name":"Peter","city":"London","1m":"not attending","2m":"attending"}]        

The error received is:

SyntaxError: identifier starts immediately after numeric literal

Is there a way to save the value in the variable (check1m)?

Answer №1

To retrieve a value, you can use the offset method like so:

 var check1m = data['1m'];    

Here's an example:

var json = [{"name":"Peter","city":"London","1m":"not attending","2m":"attending"}] ;
console.log(json[0]['1m']);

Answer №2

It's as easy as using data["1m"] instead of the previous method

Answer №3

give this a shot

$.ajax({
url:'sample.php',
type:'POST',
dataType: 'json',
success:function(data){

    var nameCheck = data[0]['name'];  // successful
    var checkOneM = data[0]['1m'];     // SyntaxError occurs here

}
}); 

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

Tips on implementing the onChange event in a custom text input for React Native applications

Recently, I started exploring React Native and attempted to create a custom text input with suggestions following a tutorial. However, I encountered an issue where I couldn't use onChange on my custom text input. I attempted to set up a state in App.j ...

What is the best way to arrange four divs in a row on a mobile device that is responsive?

I am facing an issue with displaying 4 divs of equal size on my website. In desktop view, they appear side by side but in mobile view, they stack on top of each other. I have tried using display: flex; and bootstrap classes like col-3, col-sm-3, col-md-3, ...

"Encountering a net::ERR_UNKNOWN_URL_SCHEME error message when making an Ajax post request

I'm encountering an issue while attempting to make a post call using Ajax from my frontend to my Express server. The error message I'm getting is net::ERR_UNKNOWN_URL_SCHEME. Here's the code snippet for the Ajax request: function sendStep ...

An unexpected import token was encountered while using ReactJS and Babel

Every time I attempt to launch my application, an error message pops up that says: (function (exports, require, module, __filename, __dirname) { import { Row } from '../grid' SyntaxError: Unexpected token import I've experimented with vari ...

Avoid retrieving all JSON data simultaneously when using the Android News App

I have been working on a new android news application. The mobile client app fetches news from a web server using HttpRequest and 'HttpResponse'. To handle loading images asynchronously, I implemented Volley and found a helpful guide in this art ...

Combining multiple data sources into a single input field in VueJs

I've been exploring the idea of incorporating multiple values into a vue form input binding Here's an example snippet of my code. <template> <div> <label for=""> Employee </label> <input class="form-contro ...

Is it appropriate to utilize response headers (specifically 400 error codes) to communicate errors, especially when working with x-editable?

Exploring the capabilities of the plugin reveals that it offers two distinct callbacks upon posting a result: error and success. The error callback is triggered in cases where the server does not respond with a 200 header. This means that if the server d ...

Failed to convert value to a string

I'm dealing with a frustrating issue and I just can't seem to figure it out. The error message I'm getting is Cast to string failed for value "{}" at path "post". { "confirmation": "fail", "message": { "message": "Cast to string fai ...

Error message in Angular 2, Problem found in inline template while utilizing eval() function

<li *ngFor="let pdfifRecord of pdf.ifRecord;let i=index"> <p>{{eval(pdfifRecord.labelMsg)}}</p> </li> I need to show the output of the eval function. Encountering an error message: Error in inline template c ...

Do specific elements of typography adjust according to the size of the window?

I'm always amazed by the creative solutions that come out of this community. So I'm reaching out to see if anyone knows a way to achieve something unique with CSS! Specifically, I'm curious if it's possible to make certain horizontal p ...

Combining multiple snippets of CSS classes in Material UI Emotion/Styled: How to do it effectively?

In previous versions, Material UI styled components allowed for the use of the className property to selectively apply styles. For example, a component could be styled like this: const styles = (theme: ThemeType) => ({ root: { width: '1 ...

Troubleshooting Problem with Bootstrap CSS Menu Box Format

I'm having trouble creating a simple menu for my Bootstrap site. What I want to achieve is something like this: https://i.sstatic.net/abZXC.png This is what I have accomplished so far: https://i.sstatic.net/JFVC2.png I've attempted to write th ...

Avoid overwriting the success response parameter in jQuery Ajax

I've encountered a perplexing issue where the response parameter from the first ajax call is being overridden by the second call's parameter. Here is the code snippet: http://pastebin.com/degWRs3V Whenever both drawDonutForExternalLogin and dra ...

Customize a web template using HTML5, JavaScript, and jQuery, then download it to your local device

I am currently working on developing a website that allows clients to set up certain settings, which can then be written to a file within my project's filesystem rather than their own. This file will then have some parts overwritten and must be saved ...

Updating items within an array in a MongoDB collection

I am facing a challenge where I have to pass an array of objects along with their IDs from the client-side code using JSON to an API endpoint handled by ExpressJS. My next task is to update existing database records with all the fields from these objects. ...

What is the best way to retrieve CoinEx API using access ID and secret key in JavaScript?

Having trouble fetching account information using the CoinEx API and encountering an error. For more information on the API, please visit: API Invocation Description Acquire Market Statistics Inquire Account Info Note : This account is only for test p ...

Is there a way to track whether a user has logged into the Google Chrome browser using cookies?

While the LSID cookie can indicate if a user is logged into a Google account, it cannot be reliably used to determine if someone is signed into the Chrome browser because it may also appear when a person is signed into Gmail without being signed into Chrom ...

The edit form components (dropdown and date input) are failing to load properly

I am currently facing a challenge with my project, specifically with the edit form that opens through a modal. This form consists of 8 text fields, 4 dropdowns (2 of which are dynamic dropdowns as discussed in my previous issue), and a single standard date ...

Converting a JSON object into a list in C#

I'm currently working on deserializing a JSON file in C# following a helpful guide by Bill Reiss. While I've had success with XML data in a non-list format using his method, I now need to deserialize a JSON file structured like this: public clas ...

Exploring the functionality of maximizing and minimizing logic in an Angular Bootstrap modal popup

I'm currently utilizing Angular Bootstrap Modal Popup and I'd like to include options for Maximize and Minimize in addition to the close button. By clicking on the maximize option, the popup should expand to full screen, and by clicking on minimi ...