Following each AJAX request, the page initiates a reload

Each time I make an ajax call, my page reloads, and I've attempted the following actions:

Changing the button type to button

Using event.preventDefault()

Also attempted event.stopPropagation();

Below is a snippet of my app.js:

$(document).ready(() => {
    $('#importImg').click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        if ($('#image')[0].files[0] != null) {
            $('#loading')[0].style.display = '';
            var file = $('#image')[0].files[0];
            var formData = new FormData();
            formData.append('file', file);
            console.log(formData);
            $.ajax({
                url: 'http://127.0.0.1:8000/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (data) => {
                    var div = document.getElementById("content");
                    var image = document.createElement("img");
                    image.src = data;
                    image.setAttribute("class", "img-site");
                    div.appendChild(image);
                    $('#loading')[0].style.display = 'none';
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.log(jqXHR);
                    $('#loading')[0].style.display = 'none';
                }
            })
        } else {
            alert('Choose a file first!');
        }
    })
})

Here is a glimpse of my html:

   <div class="addimg" style="margin-top: 5rem;">
    <input type="file" class="btn btn-primary" name="image" id="image"> 
    <button id="importImg" class="btn btn-danger">Upload</button><span><img style="width: 25px; margin-left: 5px; display: none" id="loading" src="200.gif" alt=""></span>
   </div>

Any help or advice would be highly appreciated. Thank you in advance!

Answer №1

Give this JavaScript code a try:

$(document).ready(() => {
    $('#importImg').click(function (event) {
        event.preventDefault();
        event.stopPropagation();
        if ($('#image')[0].files[0] != null) {
            $('#loading')[0].style.display = '';
            var file = $('#image')[0].files[0];
            var formData = new FormData(event.target);
            formData.append('file', file);
            console.log(formData);
            $.ajax({
                url: 'http://127.0.0.1:8000/upload',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: (data) => {
                    var div = document.getElementById("content");
                    var image = document.createElement("img");
                    image.src = data;
                    image.setAttribute("class", "img-site");
                    div.appendChild(image);
                    $('#loading')[0].style.display = 'none';
                },
                error: (jqXHR, textStatus, errorThrown) => {
                    console.log(jqXHR);
                    $('#loading')[0].style.display = 'none';
                }
            })
        } else {
            alert('Choose a file first!');
        }
    })
})

Answer №2

Include "type=button" and have the click handler return false

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

jQuery popups are not being initialized properly following an ajax response

My current setup involves using a pageless solution to showcase a listing of various locations. Among these locations, there is a jQuery popup that displays additional data in a box. The issue arises when new locations are added dynamically via ajax, as th ...

Get alerts from Twitter pushed to my site

Is it possible to create a web application that utilizes JavaScript to receive notifications from Twitter? I want my website app to send me notifications whenever a person I follow posts a new article. I'm having difficulty with this task and would gr ...

Adding content between previous and next buttons with the use of JavaScript

After successfully implementing the functionality for the previous and next buttons in my script, I was requested to include the date between the buttons like this: btnPrev issueDate btnNext < Date > Although I tried adding the date between the PREV ...

Verify if the input field is devoid of any content or not

I am planning to create a validation form using Vanilla JavaScript. However, I have encountered an issue. Specifically, I want to validate the 'entername' field first. If the user does not enter any letters in it, I would like to display the mess ...

What is the significance of receiving a status code of 0 in an HTTP request?

When JavaScript network calls like fetch or XMLHttpRequest, or any other form of HTTP network request, fail with an HTTP status code of 0, what does that signify? This doesn't adhere to the standard three-digit format seen in HTTP codes, making it an ...

I am experiencing an issue with my React app deployed on Heroku where it successfully loads the home page but fails

My react application performs perfectly when run locally and is successfully deployed on heroku. However, upon clicking any link from the home page to another page, a blank page with 'not found' message appears. No other error messages are displa ...

Is it possible to remove Sprites from a three.js scene?

Currently facing an issue where I am trying to update axis labels on a 3D plot by removing the old labels (implemented as sprites) before adding new ones. Unfortunately, I am experiencing difficulties. The previous labels seem to persist in the scene even ...

What is the best way to retain checkbox states after closing a modal?

I have a modal that includes multiple checkboxes, similar to a filter... When I check a checkbox, close the modal, and reopen it, the checkbox I clicked on should remain checked. (I am unsure how to achieve this :/) If I check a checkbox and then click t ...

"AngularJS makes it easy for the logged-in user's information to be accessible and available across

I need to ensure that user information is accessible across all views after logging in. How can I adjust the code to be able to retrieve the pseudonym from another view? Could you provide an example as well? Below is my login controller: app.controller ...

Angular component injected with stub service is returning incorrect value

While attempting to write tests for my Angular component that utilizes a service, I encountered an issue. Despite initializing my userServiceStub property isLoggedIn with true, the UserService property appears false when running the tests. I experimented ...

Angular Error: Issue: Unable to locate the specified column ID within the TS file

Within my application, I have a table containing multiple columns. I am attempting to populate it with the appropriate data, but upon opening the page, I encounter the error Could not find column with id "PublishedParty", despite it being present ...

Difficulty retrieving information using AngularJS service post selection of item

Currently, I am working on a project involving an AngularJS application. While using the service testPanelService, I encountered a problem where selecting an item from a list correctly logs the details of the selected item. However, when attempting to fetc ...

Tips for avoiding the need to reload a single page application when selecting items in the navigation bar

I am in the process of creating a simple Single Page Application (SPA) which includes a carousel section, an about us section, some forms, and a team section. I have a straightforward question: How can I prevent the page from reloading when clicking on nav ...

Retrieve the current system datetime with just a click of a button

Does anyone know how to use JSF + RichFaces to automatically display the current date and time in an inputText field when a button is clicked? Any guidance on this would be greatly appreciated. Thank you! ...

Creating a sticky v-stepper-header while scrolling in VuetifyJS

Can anyone help me figure out how to make the <v-stepper-header> component stay sticky when scrolling? I attempted to create custom CSS for this but was unsuccessful. Below is a snippet of code that I tried: <v-stepper v-model="step"&g ...

After updating Angular Material, the alert dialogs are now transforming into a large dark region

Recently, I encountered an issue while attempting to upgrade my old version of angular-material (v0.9.0) to a newer one. The reason behind this upgrade was the necessity to utilize the new htmlContent for an alert using $mdDialog. However, after replacing ...

What is the process of creating a mongoDB schema object in JavaScript when dealing with dynamically changing keys in a JSON?

I need to design a schema in mongoDB for an AngularJS project, but the json keys are dynamic. The structure of the json is as follows: { “1” : { “Name” : “John”, “City” : “London” }, “2” : { ...

Using the attribute to pass an object to a directive and including a variable inside

Is it possible to transfer $scope.data to a directive through its attribute in an Object, without using separate attributes? I would like to achieve the below format with any solution. <custom-directive detail="{index:1, data: {{data}}}"> </custo ...

How can I create a customized scrollbar for a div element in an Angular 2.0 CLI project?

I am attempting to create a sleek horizontal scroll bar within one of my div elements, similar to the example shown here: https://i.stack.imgur.com/ziWhi.png My project is based on the angular2 CLI. Progress so far: I came across this package angular2-s ...

Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to ...