Flask: request method not picking up the datetime value from web form via AJAX The Next CEO of Stack OverflowHow to return value using ajaxAJAX request form in Internet Explorer - reCaptcha causes form fields to be reset on submitAjax request in flask not workingHow can I identify requests made via AJAX in Python's Flask?DateTime::createFromFormat How to capture a specific date-time?How to call a python script through an AJAX call?Pandas Convert Timestamp Column to Datetime$_POSt returns unexpected arrayConvert text timestamp to dateFlask - Validate several forms on Ajax request

When airplanes disconnect from a tanker during air to air refueling, why do they bank so sharply to the right?

Only print output after finding pattern

Is it my responsibility to learn a new technology in my own time my employer wants to implement?

What size rim is OK?

Term for the "extreme-extension" version of a straw man fallacy?

How do spells that require an ability check vs. the caster's spell save DC work?

Inappropriate reference requests from Journal reviewers

Explicit solution of a Hamiltonian system

Customer Requests (Sometimes) Drive Me Bonkers!

How should I support this large drywall patch?

I believe this to be a fraud - hired, then asked to cash check and send cash as Bitcoin

How to make a software documentation "officially" citable?

Rotate a column

What does "Its cash flow is deeply negative" mean?

How do we know the LHC results are robust?

Why does standard notation not preserve intervals (visually)

Unreliable Magic - Is it worth it?

Why didn't Khan get resurrected in the Genesis Explosion?

What makes a siege story/plot interesting?

Fastest way to shutdown Ubuntu Mate 18.10

How do I construct this japanese bowl?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

How can I open an app using Terminal?

Anatomically Correct Mesopelagic Aves



Flask: request method not picking up the datetime value from web form via AJAX



The Next CEO of Stack OverflowHow to return value using ajaxAJAX request form in Internet Explorer - reCaptcha causes form fields to be reset on submitAjax request in flask not workingHow can I identify requests made via AJAX in Python's Flask?DateTime::createFromFormat How to capture a specific date-time?How to call a python script through an AJAX call?Pandas Convert Timestamp Column to Datetime$_POSt returns unexpected arrayConvert text timestamp to dateFlask - Validate several forms on Ajax request










0















I am creating a web form where one two fields are of datetime data types. Then I am passing this form data to server via AJAX. Below is the code JQuery snippet.



$(document).ready(function()
$('#btnSubmit').click(function()
var start = $("#start").val();
var end = $("#end").val();
$.ajax(
type:'POST',
url: '/interuption',

data: $('#formint').serializeArray(),
success: function(response)
alert(response);
,
error: function(error)
console.log(error);

);

);
);


Associated HTML is as follows:



<form id = "formint" class="myForm" method= "post" action="/interuption">
<th>
<label>Start Time Stamp
<input id = "start" type="datetime-local" name="start_timestamp" required>
</label>
</th>

<th>
<label>End Time Stamp
<input id ="end" type="datetime-local" name="end_timestamp" required>
</label>
</th>
</form>


On the server side I am using Flask. I am using request.form.get methods to retrieve the datetime. Then I am trying to push this to MS SQL Server. Below is the Python code snippets.



cnxn = pyodbc.connect(#credentials)
cursor=cnxn.cursor()
query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp)
VALUES (?,?)"

@app.route('/interuption',methods = ['GET','POST'])
def interuption():
try:
data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
if data_1 and data_2:
cursor.execute(query_insert,(data_1,data_2))
cnxn.commit()
cnxn.close()
return json.dumps('status':'OK')
else:
return json.dumps('error':'data has not been insterted!!')
except Exception as e:
return json.dumps('excp':str(e))
return render_template('form.html')


When I am running the above codes, I am getting an error as follows



"excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"



Clearly that request.form.get is not picking up any value from the web form.



How can I get rid of this?










share|improve this question


























    0















    I am creating a web form where one two fields are of datetime data types. Then I am passing this form data to server via AJAX. Below is the code JQuery snippet.



    $(document).ready(function()
    $('#btnSubmit').click(function()
    var start = $("#start").val();
    var end = $("#end").val();
    $.ajax(
    type:'POST',
    url: '/interuption',

    data: $('#formint').serializeArray(),
    success: function(response)
    alert(response);
    ,
    error: function(error)
    console.log(error);

    );

    );
    );


    Associated HTML is as follows:



    <form id = "formint" class="myForm" method= "post" action="/interuption">
    <th>
    <label>Start Time Stamp
    <input id = "start" type="datetime-local" name="start_timestamp" required>
    </label>
    </th>

    <th>
    <label>End Time Stamp
    <input id ="end" type="datetime-local" name="end_timestamp" required>
    </label>
    </th>
    </form>


    On the server side I am using Flask. I am using request.form.get methods to retrieve the datetime. Then I am trying to push this to MS SQL Server. Below is the Python code snippets.



    cnxn = pyodbc.connect(#credentials)
    cursor=cnxn.cursor()
    query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp)
    VALUES (?,?)"

    @app.route('/interuption',methods = ['GET','POST'])
    def interuption():
    try:
    data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
    data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
    if data_1 and data_2:
    cursor.execute(query_insert,(data_1,data_2))
    cnxn.commit()
    cnxn.close()
    return json.dumps('status':'OK')
    else:
    return json.dumps('error':'data has not been insterted!!')
    except Exception as e:
    return json.dumps('excp':str(e))
    return render_template('form.html')


    When I am running the above codes, I am getting an error as follows



    "excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"



    Clearly that request.form.get is not picking up any value from the web form.



    How can I get rid of this?










    share|improve this question
























      0












      0








      0








      I am creating a web form where one two fields are of datetime data types. Then I am passing this form data to server via AJAX. Below is the code JQuery snippet.



      $(document).ready(function()
      $('#btnSubmit').click(function()
      var start = $("#start").val();
      var end = $("#end").val();
      $.ajax(
      type:'POST',
      url: '/interuption',

      data: $('#formint').serializeArray(),
      success: function(response)
      alert(response);
      ,
      error: function(error)
      console.log(error);

      );

      );
      );


      Associated HTML is as follows:



      <form id = "formint" class="myForm" method= "post" action="/interuption">
      <th>
      <label>Start Time Stamp
      <input id = "start" type="datetime-local" name="start_timestamp" required>
      </label>
      </th>

      <th>
      <label>End Time Stamp
      <input id ="end" type="datetime-local" name="end_timestamp" required>
      </label>
      </th>
      </form>


      On the server side I am using Flask. I am using request.form.get methods to retrieve the datetime. Then I am trying to push this to MS SQL Server. Below is the Python code snippets.



      cnxn = pyodbc.connect(#credentials)
      cursor=cnxn.cursor()
      query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp)
      VALUES (?,?)"

      @app.route('/interuption',methods = ['GET','POST'])
      def interuption():
      try:
      data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
      data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
      if data_1 and data_2:
      cursor.execute(query_insert,(data_1,data_2))
      cnxn.commit()
      cnxn.close()
      return json.dumps('status':'OK')
      else:
      return json.dumps('error':'data has not been insterted!!')
      except Exception as e:
      return json.dumps('excp':str(e))
      return render_template('form.html')


      When I am running the above codes, I am getting an error as follows



      "excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"



      Clearly that request.form.get is not picking up any value from the web form.



      How can I get rid of this?










      share|improve this question














      I am creating a web form where one two fields are of datetime data types. Then I am passing this form data to server via AJAX. Below is the code JQuery snippet.



      $(document).ready(function()
      $('#btnSubmit').click(function()
      var start = $("#start").val();
      var end = $("#end").val();
      $.ajax(
      type:'POST',
      url: '/interuption',

      data: $('#formint').serializeArray(),
      success: function(response)
      alert(response);
      ,
      error: function(error)
      console.log(error);

      );

      );
      );


      Associated HTML is as follows:



      <form id = "formint" class="myForm" method= "post" action="/interuption">
      <th>
      <label>Start Time Stamp
      <input id = "start" type="datetime-local" name="start_timestamp" required>
      </label>
      </th>

      <th>
      <label>End Time Stamp
      <input id ="end" type="datetime-local" name="end_timestamp" required>
      </label>
      </th>
      </form>


      On the server side I am using Flask. I am using request.form.get methods to retrieve the datetime. Then I am trying to push this to MS SQL Server. Below is the Python code snippets.



      cnxn = pyodbc.connect(#credentials)
      cursor=cnxn.cursor()
      query_insert = "INSERT INTO test.dbo.testFeed(start_timestamp,end_timestamp)
      VALUES (?,?)"

      @app.route('/interuption',methods = ['GET','POST'])
      def interuption():
      try:
      data_1 = datetime.datetime.strptime(request.form.get('start'),%Y-%m-%d %H-%M-%S')
      data_2 = datetime.datetime.strptime(request.form.get('end'),%Y-%m-%d %H-%M-%S')
      if data_1 and data_2:
      cursor.execute(query_insert,(data_1,data_2))
      cnxn.commit()
      cnxn.close()
      return json.dumps('status':'OK')
      else:
      return json.dumps('error':'data has not been insterted!!')
      except Exception as e:
      return json.dumps('excp':str(e))
      return render_template('form.html')


      When I am running the above codes, I am getting an error as follows



      "excp": "time data 'None' does not match format '%Y-%m-%d %H-%M-%S'"



      Clearly that request.form.get is not picking up any value from the web form.



      How can I get rid of this?







      ajax datetime flask






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 16:30









      pythondumbpythondumb

      1279




      1279






















          1 Answer
          1






          active

          oldest

          votes


















          0














          When sending form data as key-value pairs to the server, the key will be the name attr of the <input> (not id), so you should try request.form.get('start_timestamp') and request.form.get('end_timestamp') instead.






          share|improve this answer























          • Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

            – pythondumb
            Mar 22 at 1:40











          • It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

            – Grey Li
            Mar 22 at 2:20











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285132%2fflask-request-method-not-picking-up-the-datetime-value-from-web-form-via-ajax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          When sending form data as key-value pairs to the server, the key will be the name attr of the <input> (not id), so you should try request.form.get('start_timestamp') and request.form.get('end_timestamp') instead.






          share|improve this answer























          • Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

            – pythondumb
            Mar 22 at 1:40











          • It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

            – Grey Li
            Mar 22 at 2:20















          0














          When sending form data as key-value pairs to the server, the key will be the name attr of the <input> (not id), so you should try request.form.get('start_timestamp') and request.form.get('end_timestamp') instead.






          share|improve this answer























          • Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

            – pythondumb
            Mar 22 at 1:40











          • It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

            – Grey Li
            Mar 22 at 2:20













          0












          0








          0







          When sending form data as key-value pairs to the server, the key will be the name attr of the <input> (not id), so you should try request.form.get('start_timestamp') and request.form.get('end_timestamp') instead.






          share|improve this answer













          When sending form data as key-value pairs to the server, the key will be the name attr of the <input> (not id), so you should try request.form.get('start_timestamp') and request.form.get('end_timestamp') instead.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 22 at 0:35









          Grey LiGrey Li

          3,21411633




          3,21411633












          • Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

            – pythondumb
            Mar 22 at 1:40











          • It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

            – Grey Li
            Mar 22 at 2:20

















          • Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

            – pythondumb
            Mar 22 at 1:40











          • It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

            – Grey Li
            Mar 22 at 2:20
















          Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

          – pythondumb
          Mar 22 at 1:40





          Thanks Grey. I have another doubt, what is the difference between request.form['field'] and request.form.get['field']

          – pythondumb
          Mar 22 at 1:40













          It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

          – Grey Li
          Mar 22 at 2:20





          It's almost like what you do with dict. If you pass a non-exist key, dict['badkey'] will throw out a KeyError exception (In Flask, it will be a 400 Bad Request response), but dict.get('badkey') will return None instead. Besides, you can set a default value with get() (e.g. dict.get('key', 'default value')).

          – Grey Li
          Mar 22 at 2:20



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid …


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55285132%2fflask-request-method-not-picking-up-the-datetime-value-from-web-form-via-ajax%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

          Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?