Issue with undefined object reference in Moment.js when making an ajax request

Currently, I am working on developing a straightforward booking calendar using Eonasdan's bootstrap-datetimepicker, which relies on the moment.js library. To incorporate localization, I have included the necessary file. My setup consists of linked pickers for input fields and a button that triggers an email to be sent with the selected dates via a simple AJAX request. However, upon form submission, I encountered the following error:

// locale-hr.js (line 89, col 1)

TypeError: this is undefined switch (this.day()) {

The excerpt from the specific lines causing the issue (88-102) is as follows:

nextWeek : function () {
    switch (this.day()) {
        case 0:
            return '[u] [Sunday] [u] LT';
        case 3:
            return '[u] [Wednesday] [u] LT';
        case 6:
            return '[u] [Saturday] [u] LT';
        case 1:
        case 2:
        case 4:
        case 5:
            return '[u] dddd [u] LT';
    }
},

While the dates are successfully retrieved from the calendar, no emails are actually being sent out. Here is my Ajax script:

$(function() {
    $("#reservationForm").on("submit", function(e) {
        e.preventDefault();

        var url = "../bin/reservation.php";

        // storing dates from each picker
        var date1 = $("#datetimepicker1").data("DateTimePicker").date();
        var date2 = $("#datetimepicker2").data("DateTimePicker").date();

        $.ajax({             
            type: "POST",
            url: url,
            data: { date1: date1, date2: date2 },
        }).done(function(response) {
            alert("Message sent");
        });                     
    });
});

And here is the corresponding PHP script:

<?php
    if ( empty($_POST['date1']) || empty($_POST['date2']) ) {
        echo ERROR_NO_ARGS;
        return false;
    }

    $date1 = $_POST['date1'];
    $date2 = $_POST['date2'];

    $to = 'example@example.com';
    $email_subject = "Title";
    $email_body = "Selected dates:" . "From $date1 to $date2";
    $headers = "From: Contact form\n";      
    $headers .= "Content-Type: text/plain; charset=utf-8" . "\r\n";

    mail($to, $email_subject, $email_body, $headers);

    return true;            
?>

This seems like a mildly complex issue. If you have any suggestions or solutions regarding why the locale-hr.js file may be encountering issues referencing objects, please share. Additionally, if there are known fixes or improvements to consider, feel free to inform me. Your input is greatly appreciated. You can also view the code on jsfiddle, though it currently lacks the AJAX call due to initial unfamiliarity with the platform. I may revisit later to rectify this. Thank you in advance.

Answer №1

When using Eonasdan's bootstrap-datetimepicker, the date method returns a moment object. This means that when you try to send this object to your server, jQuery is not able to serialize it properly (refer to the jQuery.ajax data section). To fix this, you have a few options:

  • You can pass a string by utilizing moment's format function. If needed, you can specify the format as well. Your code will look like this:
    data: { date1: date1.format(), date2: date2.format() }
  • Pass milliseconds by using moment's valueOf() method. The code for this will be:
    data: { date1: date1.valueOf(), date2: date2.valueOf() }
  • You can also pass seconds by using moment's unix() function. In this case, your code will be:
    data: { date1: date1.unix(), date2: date2.unix() }

Answer №2

It is possible that there are some bugs present:

Check out the updated fiddle here:

`https://jsfiddle.net/dssoft32/d4zuxy4e/2/`

// Updated JS code

var fnMain = function(){

    // Calendar localization
    var hr = moment.locale('hr', {
        days: ["Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota","Nedjelja"],
        weekdaysShort: ["Pon", "Uto", "Sri", "Čet", "Pet", "Sub","Ned"],
        weekdaysMin: ["Po", "Ut", "Sr", "Če", "Pe", "Su", "Ne"],
        months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"],
        monthsShort: ["Sij", "Velj", "Ožu", "Tra", "Svi", "Lip", "Srp", "Kol", "Ruj", "Lis", "Stu", "Pro"],
        today: "Danas",
        }
    );
    
    // Newly added functions for date manipulation  

    var enumerateDaysBetweenDates = function( startDate, endDate ) {
        var dates = [];
      
        while (startDate<= endDate) {
            dates.push(startDate.format('D/M/YYYY'));
            startDate.add(1,  'days');
        }

        return dates;
    };


    var formatDisabledDates = function( dateSet ) {
        var newSet = [];

        for( var i=0; i < dateSet.length; i++ ) {

            newSet.push( moment( dateSet[i], "D/M/YYYY") );

        }

        return newSet;

    }

        // Define start and end dates   
        var fromDate = moment("10/07/2016", "D/M/YYYY"); 
        var toDate = moment("21/07/2016", "D/M/YYYY"); 

              var results = enumerateDaysBetweenDates(fromDate, toDate);

    //});

    var disabledSet = formatDisabledDates( results );
    console.log( disabledSet );

    var chckDate;

    $('#datetimepicker1').datetimepicker({
    useCurrent: false, 
    allowInputToggle: true,
    viewMode: 'days',
locale: hr,
format: 'DD/MM/YYYY',
        disabledDates: disabledSet
    }).on("dp.change", function (e) {
        chckDate = $(this).data("DateTimePicker").date();
        chckDate = chckDate.format('DD. MM. YYYY');
        
    }).on("dp.show", function (e){
        $("[data-day*='"+ chckDate + "']").addClass("startFrom");

    });

    $('#datetimepicker2').datetimepicker({
        useCurrent: false,
        allowInputToggle: true,
        viewMode: 'days',
locale: hr,
format: 'DD/MM/YYYY',
        disabledDates: disabledSet
    }).on("dp.change", function (e) {
    //
    }).on("dp.show", function (e){
        $("[data-day*='"+ chckDate + "']").addClass("startFrom");
    });

} // End of main code execution function



$( document ).ready( fnMain );
body {
    background-color: #eee;
}

.input-group {
    margin-top: 20px;
}


.bootstrap-datetimepicker-widget table td.disabled, .bootstrap-datetimepicker-widget table td.disabled:hover {
    background: rgba(255, 0, 0, 0.1) none repeat scroll 0 0;
    border-radius: 0;
    color: #777;
    cursor: not-allowed;
}

.bootstrap-datetimepicker-widget table td.startFrom, .bootstrap-datetimepicker-widget table td.startFrom:hover {
    background-color: orange;
    border-radius: 0;
    color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
<script src="https://github.com/moment/moment/blob/develop/locale/hr.js"></script>


<div class="container">

    <form id="reservationForm">
      <div class='col-md-6'>
      
      <!-- FROM -->
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
      </div>

      <!-- TO -->
      <div class='col-md-6'>
          <div class="form-group">
              <div class='input-group date' id='datetimepicker2'>
                  <input type='text' class="form-control" />
                  <span class="input-group-addon">
                      <span class="glyphicon glyphicon-calendar"></span>
                  </span>
              </div>
          </div>
      </div>

      <div class="col-md-12">
        <button class="logdates" type="submit">Send</button>
      </div>

    </form>
  </div>

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

Encountering an issue with extending the MUI color palette, receiving a "reading 'dark'" error due to properties of undefined

Encountering an issue when trying to expand the MUI color palette—getting this error instead: Error: Cannot read properties of undefined (reading 'dark') Take a look at my theme.ts file below: const theme = createTheme({ palette: { pri ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

What is the most effective method to arrange absolute divs generated randomly in a grid-like formation?

Hey there! I'm facing an intriguing challenge with my app. It's designed to generate a variable number of divs which are always in absolute positioning. Unfortunately, making them relative is not an option due to some other factors within the app ...

Turn off and then turn on user input without exiting the textarea

I've been working on a small project that requires me to enable and disable text input in a textarea using key commands, similar to Vi/Vim's insertion and command modes. However, I'm struggling to find an elegant solution. Disabling the tex ...

Issue: Infinite loops detected in AJAX functions

I am using $.get methods in the following code snippet: $.get("/url" , function(z) { var a = $(z).find("span"); for (var i = 0 ; i<a.length; i++){ var v = $(a).eq(i).children("strong:first").text(); alert(v); } }); However, the s ...

The error handler function is missing in Zepto's $.post method

When I was using Zepto instead of jQuery, I noticed that while the $.ajax method has an error handler, other methods like $.post and $.get do not. Do you know why this is the case? Function Signature $.post(url, [data], function(data, status, xhr){ ... }, ...

The Ajax call resulted in a bad request error response

I keep receiving a bad request response when I make my request. I have confirmed that my dictionary data is correct by using an online JSON validator, and everything appears to be in order. Here is the code I am using: // Parse datetime to timestamp and a ...

Using Ajax URL in a Wordpress Plugin

Plugin Class File: function __construct() { add_shortcode('user_registration_form', array( $this, 'shortcode' )); } public function hook() { add_action('wp_ajax_get_product_serial_callback', 'get_product_se ...

When using `parseInt` on the string "802.11 auth", the result did not match my expectations

I am developing a data parser that transforms the output of a command into a JSON object for sending to a live logging and graphing platform. All data extracted by the parser is returned as strings, but I need numerical values to be preserved as numbers. H ...

Ways to show dropdown menu link exclusively on mobile browsers and not on desktop browsers

<li class="megamenu-content"> <div class="megamenu-content-wrapper clearfix"> <ul class="col-lg-3 col-sm-3 col-md-3 "> <li class="cat-header">DISPLAY MEMBERS</li> ...

Pass data from controller using Ajax in CodeIgniter

Here is my JavaScript code: $(document).ready(function(){ $("input[type='checkbox']").change(function(){ var menu_id = this.value; if(this.checked) var statusvalue = "On"; else var statusvalue = "Off"; $.ajax( ...

Retrieve data from a database using Ajax and PHP's `.load()` method

I am facing a dilemma with updating a value from a database ($learner->idnumber). The scenario involves a form that posts to process.php upon submission (which then edits the database). The challenge is updating the PHP database value $learner->idn ...

What strategies can I use to solve this JavaScript puzzle?

One of my acquaintances has a webpage online that contains an inline script tag, featuring a JavaScript function: (#1): var domain = window.location.protocol + "//" + window.location.host + '/'; $(document).ready(function() { var count = 5 ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...

Is it possible to transfer data from javascript to php through ajax?

I am attempting to extract the data speedMbps from my JavaScript code using Ajax to send the data to my PHP script, but unfortunately, I am not receiving any output. My experience with Ajax is limited to implementing auto-completion feature. <script sr ...

Retrieve the HTML contents of a cell that contains a checkbox with the value of "jquery"

Here is an example of a table row: <tr> <td><input type='checkbox' name='post[]' value="1"></td> <td>08-Apr-2014</td> <td>injj team</td> <td>merchant.testyy.com</ ...

In JavaScript, you can use the document.cookie property to delete specific cookie values identified by their names and values

Within my JavaScript code, I am working with a cookie that contains multiple names and values: "Token=23432112233299; sessionuid=abce32343234" When I download a file from the server, a new cookie is added to the document, resulting in the following cooki ...

Sequelize synchronization does not generate the database table

I am currently working on a project with the following directory structure: ├── index.ts ├── package.json ├── package-lock.json ├── src │ ├── controllers │ ├── models │ │ └── repository.ts │ ├ ...

Using JQuery, you can easily add a new row right after the row that you have

I need to insert a new row after the selected row, but my current code inserts the row at the end if no row is selected. Is there a way to fix this issue? strGridId = update_GridID(strGridId); var grid = jQuery('#' + strGridId); var columnModel ...

Exclude items from AngularJS watch list

Is there a way to manually run a digest loop on specifically selected watches? Take, for example, the scenario where I need a directive that constantly displays the current time (including seconds), but without triggering the digest loop every second. One ...