Following the ajax request, the subsequent code was unable to be executed as it awaited the JSON response

My latest project involves using Django2 to create a web application. I encountered an issue in the frontend where, despite receiving a 200 status code in the network tab after an ajax call, no alert box was displayed. The app seemed to be stuck at a particular line where it was waiting for JSON data. The following alert function did not execute as expected:

async function myFunction() {
  Swal.fire({
    title: '',
    text: "Do you want to confirm entries?",
    type: 'warning',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    cancelButtonColor: '#d33',
    confirmButtonText: 'Yes',
    cancelButtonText: 'No'
  }).then(
    async(result) => {
      if (result.value) {
        $.ajax({
          url: '/content_checklist_name_url/',
          type: 'POST',
          data: $(this).serialize(),
          cache: false,
          success: function(data) {
            var comment_html = "<div id='myform_1'>" + data['log_info'] + "</div>";
            $('#myform_1').remove();
            $('#ajax_data').prepend(comment_html);
            $('#myform_input').val('');
          },

        });
        const response = await fetch({ % url 'bms:content_checklist_name_url' %
        });
        const msg_json = await response.json();

        alert(msg_json.responseText)
        let a = msg_json;
        if (a === "Duplicate Entry. This Course Code already exists.") {
          Swal.fire({
            title: '',
            text: 'Duplicate Entry. This Course Code already exists.',
            type: 'error',
          })


        } else {
          Swal.fire({
            title: '',
            text: 'Entries have been saved.',
            type: 'success',
          })


        }
      
      } else {
        window.stop();
      }
    }
  )
}
<form id="myform" action="/content_checklist_name_url/" method="POST">
  ...
</form>
<button class="button" onclick="myFunction()" type="button" id="submit">SUBMIT</button>

In the backend view.py file:

    @csrf_exempt
def content_checklist_name_url(request):

  if request.method == 'POST':    
    
         ...
    msg = "success"   

    obj = {"msg": msg}

    context = {'msg_json': json.dumps(obj)}
    return render(request, 'bms/main.html',context=context)

I also noticed an error in the console:

VM355:4 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 3

Despite this, no alert box is being displayed.

How can I investigate and identify where the problem lies?

Answer №1

If your expectation is to receive a POST, sending a GET request will not trigger the execution of this particular branch. Furthermore, when submitting a form in HTML, the browser typically navigates to a different page upon submission, preventing the Ajax call from being made.

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 is the best way to obtain the SearchIDs for various searchNames using JavaScript?

Who can assist me in resolving this issue? I am trying to retrieve the id of a searchName whenever a user selects the checkbox. Ideally, I would like to assign the value of the PHP line $search_row->searchid to the id attribute in the input field. Apolo ...

Error message: Unhandled error - $(...).sidr does not exist as a function. [Chrome developer console]

I included this code in the basic module HTML block of a WordPress page builder and encountered the white screen of death. According to the Chrome developer console, the following error occurred: helpers.js?ver=4.5.3:15 Uncaught TypeError: $(...).sidr is ...

How can I best fill the HTML using React?

After attempting to follow various React tutorials, I utilized an API to fetch my data. Unfortunately, the method I used doesn't seem to be very efficient and the code examples I found didn't work for me. I am feeling quite lost on how to proper ...

Utilize a function from another component

Is there a way to access a function inside main.js using a button in navbar.js to open a drawer that is located within the main.js component? Do I need to utilize Redux for this task? <Navbar /> <main /> navbar.js <Button type="default ...

Avoid the need to refresh the HTML content every time there is a change in the Angular $

One of the challenges I'm facing is with a for loop in my JavaScript: for (var i=0;i<2;i++) { $scope.widget = widgets[i]; $scope.header = widgets[i].data.header; $scope.items = widgets[i].data.items; $scope.footer = widgets[i].data ...

deleting the current product information during an ajax request

After executing the query provided below, I have $product_list in this code. However, I want to use ajax so that when I click on the button link1, $product_list gets emptied. How can I clear the content within products_list using an ajax call triggered by ...

Confirmation message for deletion using jQuery on dynamic elements

My div is populated with dynamically added records. Whenever I click on the 'Remove' link, a confirmation box pops up multiple times corresponding to the number of records present in the div. I want the confirmation box to appear only for the spe ...

The AngularJS directive seems to be having trouble receiving the data being passed through its scope

Check out this HTML code snippet I created: <div ng-controller="ctrl"> <custom-tag title = "name" body = "content"> </custom-tag> </div> Take a look at the controller and directive implementation below: var mod = angular.mod ...

What is the best way to retrieve an image using jQuery ajax?

let imageHolder = new Image(); //img holder $(imageHolder).load(function () { $("#div").append(this); }).error(function () { // inform the user that there was an error loading the image alert('Error loading image') ...

Is there a way to automatically fill number fields by clicking on radio buttons using a JavaScript function?

Currently, I am facing an issue with a task that involves three elements: 1. Two Number fields (from standard class) that need to be populated dynamically. 2. A Javascript function designed to extract coordinates using geolocator. 3. A radio button which, ...

How come I am unable to pass JavaScript values to my PHP5 code?

I'm struggling with this code snippet: <?php $html=file_get_contents('testmaker_html.html'); echo $html; ?> <script type="text/javascript"> document.getElementById('save_finaly_TEST').addEventLis ...

Having trouble installing the 'ws' npm package on MacOS Big Sur?

Every time I try to install the websocket package using "npm install ws", I keep getting this error message: npm ERR! code ENOSELF npm ERR! Refusing to install package with name "ws" under a package npm ERR! also called "ws". Did you name your project the ...

An issue occurred while testing with React-Native Testing Library/Jest, where the property 'TouchableOpacity' could not be read

I am currently in the process of conducting tests using jest and react-native testing. Unfortunately, I have encountered an issue where TouchableOpacity is not being recognized and causing errors. Card.test.js import Card from "../Card" import R ...

Turn off link preview feature on Android messages

As a developer, I am looking for a way to disable or hide link previews on Android devices when someone receives a text message with a link to our website. I still want the URL address to be visible, but I prefer to keep the link previews on IOS devices. I ...

[Symfony 1.4][sfForm] show | hide row

What is the best method for using Ajax to hide and un-hide a row (including placing the entire row in a div with an id)? ...

Securely transmit data using a JQuery modal dialog form with HTTPS encryption

I currently have a functional modal login dialog. The only issue I'm facing is that when the original page is loaded through http, I still need to securely pass credentials to the server via https. Ideally, I would like to achieve this with minimal mo ...

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

Days and Their Corresponding Names Listed in Table

Currently, I am working on creating a "timesheet" feature that requires the user to input 2 dates. The goal is to calculate each month and year based on the input dates and then display them in a dropdown menu combobox. I would like to dynamically update ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

"An error occurs in Django due to a local variable being referenced

Currently working on a Django application and running into some issues. The error "local variable 'sigtracker' referenced before assignment" keeps popping up, specifically in the code below. I suspect it has to do with form validation but can&apo ...