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

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

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