Guide for inserting a Date variable into MySQL using JSON

In my database, there is a table with a Date field. I noticed that when I try to insert a date using Postman through the API like this:

 {
   "registerDate" : "2014-06-02"
 }

It successfully inserts the date. However, when I attempt to do the same using JavaScript and jQuery by retrieving the value from an input in the format YYYY-MM-DD or even directly assigning the value "2014-06-02" to the variable, it results in inserting a NULL value in the database.

 var user = new Object();
 user.registerDate = $('#register_date').val();
 createUser(url, type, JSON.stringify(user), function(user){
 });

or

 var user = new Object();
 user.registerDate = "2014-06-02";
 createUser(url, type, JSON.stringify(user), function(user){
 });

The createUser function used is as follows:

function createUser(url, type, user, success){
 $.ajax({
     url:url,
     type: 'POST',
     crossDomain : true,
     contentType : type,
     data : user
})
.done(function (data, status, jqxhr) {
      success(user);
})
.fail(function (jqXHR, textStatus) {
    console.log(textStatus);
});
}

I am puzzled as to why it works in postman but not through JavaScript?

Answer №1

Here's a tip for you: Instead of a lengthy comment, consider converting your date to milliseconds using JavaScript's parse method:

Date.parse('2014-06-02');

Then, transmit it as JSON:

{'registerDate' : '1401685200'}

To parse it back in MySQL, utilize the FROM_UNIXTIME function.

FROM_UNIXTIME(1401685200)

Furthermore, consider storing your date as an integer in your database and convert it to a date when necessary; this approach can prevent encoding issues that may arise from storing it as a string.

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 steps should be followed to connect to the EngineYard database from my personal computer?

After creating a Rails application and hosting it on EngineYard, I am now looking to manually insert a record into my database (Database: MYSQL). How can I access EngineYard's database from my local machine? Unfortunately, I have been having trouble ...

What methods can be used to simplify JSON data in Logstash?

Here is the JSON data: { "foo1":{ "number":1, "type":"In progrss", "submit_time":"2020-10-04", "id_type":"2153707", "order_id":"1601849877", &q ...

Using Pocketbase OAuth in SvelteKit is not currently supported

I've experimented with various strategies, but I still couldn't make it work. Here's the recommendation from Pocketbase (): loginWithGoogle: async ({ locals }: { locals: App.Locals }) => { await locals.pb.collection('users' ...

Tips for transferring a variable from a hyperlink to a Flask application

Here is a snippet of my Python Flask code: @app.route('/ques/<string:idd>',methods=['GET', 'POST']) def ques(idd): print(id) And here is the accompanying Javascript code: var counts = {{ test|tojson }}; var text = ...

Once chosen, zoom in on the map to view the results

I am facing an issue with multiple selects in my code, where one select depends on the result of another. The ultimate goal is to zoom in on the area that has been searched and found, but unfortunately, it is not functioning as expected. If you'd lik ...

Tips for determining in which range a decimal variable falls based on database values

I am working with a SQL table named "tax_info" that consists of three columns: https://i.sstatic.net/cDou5.png There is also a variable called "Salary" which stores floating point values. My task is to determine the tax bracket in which the Salary falls. ...

The NextJS page is displaying a 404 error on the server, but it functions properly when accessed

Incorporated within a React component in the Next.js framework is a search feature. The component utilizes the useRouter hook from the next/router library to extract the search query from the URL and save it as the search variable. Subsequently, the compon ...

Create random animations with the click of a button using Vue.js

I have three different lottie player json animation files - congratulations1.json, congratulations2.json and congratulations3.json. Each animation file is configured as follows: congratulations1: <lottie-player v-if="showPlayer1" ...

Struggling with a component that won't load in JSX?

Having some difficulty with React not rendering data associated with a component's props: import React from 'react'; import {ItemListing} from './ItemListing.js'; export var SearchResults = React.createClass({ render: functi ...

Choose a specific parameter from a line using the body parser in Node.js

Upon receiving a post message, I am having trouble selecting a value from CSV data. Here is a sample of what I receive: { reader_name: '"xx-xx-xx-xx-xx-xx"', mac_address: '"name"', line_ending: '\n', field_delim: & ...

`How can I manage my electron.js application effectively?`

As a newcomer to electron.js, I have successfully created a game using html, css, and javascript that currently runs offline on the client side. However, I am now looking for a way to access, analyze, and make changes to this app. One solution could be lo ...

Creating mobile-friendly websites for a variety of devices, including smartphones and tablets

Creating a prototype webpage for my friend, one crucial aspect is ensuring it looks good on different devices. Utilizing Bootstrap, I've implemented vertical collapsing for certain elements, but I'm struggling with how to adjust other components ...

Can I identify the gender of visitors to my blogger.com website?

Is there a way to customize content based on the gender of the visitor using JavaScript or other methods like an AJAX call to an external server with Python/Ruby backend for GData APIs access, or by retrieving cookie information? Google, for instance, ca ...

Creating a duplicate of the Object in order to include a new key and value pair

While pre-fetching a product from a database using mongoose along with next.js and react-query, I encountered a situation where I had to perform a deep copy of a nested object to successfully add a key-value pair to it. Without this deep copy, the operat ...

Make sure accordion items stay open even when another one is clicked

I have implemented an accordion component that currently opens and closes on click. However, I am facing an issue where clicking on one item closes another item that was previously open, which is not the behavior I desire. I'm unsure of the best appro ...

The outcome of Contains function is coming back as negative

Recently, I was working on a project that I cloned from GIT, which involved a bot. However, I encountered an issue where the 'contains' function used by the bot was not functioning properly. After conducting some research using Google, I discove ...

Retrieve information from two columns and perform two comparisons simultaneously in PHP

I am unsure of the best way to phrase this, and I apologize if there are any errors in my explanation. I don't mean to cause any inconvenience, but I have received complaints from admins in the past regarding similar issues. Please forgive any languag ...

Increasing the speed of a MyISAM table set to readonly mode

We have a sizable MyISAM table dedicated to archiving old data. This archival process occurs monthly, and aside from these occasions, no new data is added to the table. Is there a method to instruct MySQL that this table is strictly for reading, in order t ...

Creating duplicates of form and its fields in AngularJS with cloning

I'm facing an issue with a form that contains various fields and two buttons - one for cloning the entire form and another for cloning just the form fields. I attempted to use ng-repeat, but when I clone the form and then try to clone fields in the or ...

Concealing Redundant Users in Entity Framework

I am faced with the task of sorting through a database containing over 4000 objects, many of which are duplicates. My goal is to create a new view that displays only one instance of each element based on the first and last name. I have already implemented ...