October 22, 2024
Chicago 12, Melborne City, USA
jQuery

Why can't I save notes in a multi-entry journal setup using jQuery and AJAX?


I’m working on a web application where users can maintain multiple journal entries on a single page. Each entry allows users to add notes through a Markdown editor. The problem is

const notesContent = notesDisplay.find('.markItUp').val();

is returning null when it should be getting the content inside the textarea when clicking save

full code:

@foreach($notes as $note)
    <div class="notes-display">
        <div class="notes-text">{!! $note->Daily_Notes_HTML !!}</div>
        <button class="add-notes-button" onclick="showEditor(this)">Add Notes</button>
        
        <div class="editor-container" style="display: none;">
            Notes:
            <textarea class="markItUp" style="padding: 5px; width: 100%; height: 225px; box-sizing: border-box;"></textarea>
            <button class="save-notes-button">Save</button>
            <button onclick="cancelEditor(this)">Cancel</button>
        </div>
        
        <input type="hidden" class="notes-markdown" value="{{ $note->Daily_Notes }}">
        <input type="hidden" class="journal-date" value="{{ $note->Date_of_Day }}">
    </div>
@endforeach

<script type="text/javascript">
function showEditor(button) {
    const notesDisplay = $(button).closest('.notes-display');
    notesDisplay.find('.add-notes-button').hide();
    notesDisplay.find('.notes-text').hide();
    notesDisplay.find('.editor-container').show();

    notesDisplay.find('.markItUp').val(notesDisplay.find('.notes-markdown').val());
    // Initialize editor...

    notesDisplay.find('.save-notes-button').off('click').on('click', function() {
        const notesContent = notesDisplay.find('.markItUp').val(); // Current notes content
        const journalDate = notesDisplay.find('.journal-date').val(); // Journal date

        $.ajax({
            url: "{{ route('journal.saveNotes', ':date') }}".replace(':date', journalDate),
            type: 'POST',
            data: {
                notes: notesContent,
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                if (response.html) {
                    notesDisplay.find('.notes-text').html(response.html);
                }
                alert(response.message); 
                cancelEditor(button);
            },
            error: function(xhr) {
                console.log(xhr.responseText);
                alert('An error occurred while saving the notes. Please try again.');
            }
        });
    });
}
</script>



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video