Executing Jquery AJAX will continue to submit the form regardless of the confirmation status returned by the confirm()

<div class="report" data-id="55"></div>

<script>
$('.report').click(function() {
    var id = $(this).data("id");
    confirm("do you really want to report this post?");

    $.ajax({
        url: 'forumreport.php',
        type: 'GET',
        data: 'id='+id,
        success: function(){
            alert("reported!!");
        },
    });
})
</script>

<p>Is there a way to prevent the execution of the <code>$.ajax() method if the user cancels the confirmation prompt? Despite canceling, the AJAX request is still being sent with the ID. Any suggestions on how to handle this scenario?

Answer №1

When using the confirm method, it is essential to understand that it returns a boolean value indicating whether the prompt is confirmed. This allows you to store the boolean in a variable and verify if it is true before proceeding with the AJAX request.

$('.report').click(function() {
    var id = $(this).data("id");
    var confirmed = confirm("Are you sure you want to report this post?");

    if (confirmed) {
      $.ajax({
          url: 'forumreport.php',
          type: 'GET',
          data: 'id='+id,
          success: function(){
              alert("Post has been reported successfully!");
          },
      });
    }
});

Answer №2

Confirm function will give back a boolean value to show whether OK or Cancel was chosen (true indicates OK)
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm

Make sure to check the outcome returned by the confirm function:

<script>
$('.report').click(function() {
    var id = $(this).data("id");
    if(confirm("Are you sure you want to report this post?")){
       $.ajax({
           url: 'forumreport.php',
           type: 'GET',
           data: 'id='+id,
           success: function(){
            alert("Reported successfully!!");
           },
       });
    };

})
</script>

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

Manipulate data destination using Javascript

I have a task in my AngularJS application that involves the following steps: 1) Click on a button. 2) If variableA is true, display a modal. 3) If variableA is false, redirect to another link without showing a modal. Here is the code I am using to ...

Dividing a collection of URLs into smaller chunks for efficient fetching in Angular2 using RxJS

Currently, I am using Angular 2.4.8 to fetch a collection of URLs (dozens of them) all at once. However, the server often struggles to handle so many requests simultaneously. Here is the current code snippet: let collectionsRequests = Array.from(collectio ...

Check the box to track the current status of each individual row

Recently, I encountered an issue with a form containing dynamic rows. Upon fetching records, my goal was to update the status of selected rows using checkboxes. Although I managed to retrieve checkbox values and dynamic row IDs successfully in the console ...

Managing the appearance of one DOM element using another DOM element

Hey there, I'm currently working on an Angular Material tooltip implementation. When I hover over my span element, the tooltip appears. Now, I'm wondering how I can dynamically change the background color of the tooltip based on certain condition ...

What is the best way to update image CSS following a rotation using JavaScript?

Discover a neat CSS trick for always centering an image in a div, regardless of its size or aspect ratio. <style> .img_wrap { padding-bottom: 56.25%; width: 100%; position: relative; overflow: hidden; } #imgpreview { display: bl ...

Add content or HTML to a page without changing the structure of the document

UPDATE #2 I found the solution to my question through Google Support, feel free to read my answer below. UPDATE #1 This question leans more towards SEO rather than technical aspects. I will search for an answer elsewhere and share it here once I have th ...

import component dynamically from object in Next.js

Currently, I have a collection of components that I am aiming to dynamically import using next/dynamic. I'm curious if this is achievable. Here's the object in interest: // IconComponents.tsx import { Tick, Star } from 'components ...

Filtering Key Presses in Quasar: A Comprehensive Guide

Seeking Assistance I am looking to integrate an "Arabic keyboard input filtering" using the onkeyup and onkeypress events similar to the example provided in this link. <input type="text" name="searchBox" value="" placeholder="ب ...

Mars Eclipse, AngularJS and the power of NodeJS

Could you please assist me in understanding the workings of node.js and angular.js within Eclipse? I am using Eclipse Mars and I would like to run my Angularjs project on a local server (localhost:8080) but I am unsure of how to accomplish this. I have a ...

React: Remove a particular row from the table

I am currently working on a project that involves building a table component. Each row in this table is also a separate component. class FormulaBuilder extends Component { constructor(props) { super(props); this.state = ...

Utilizing Sequelize to Convert and Cast Data in iLike Queries

When using Sequelize for a full-text search, I encountered an issue with applying the iLike operator to columns of INTEGER or DATE type. How can I cast off a column in this case? To illustrate, here is an example of what I am trying to achieve with a Post ...

transferring background-image in html between elements

Imagine having a three-level hierarchy HTML code structured like this: <section> <div id="outer"> <div id="inner"> </div> </div> </section> If we set background-image:someImage.jpg to the section, and backg ...

Having issues with passing data to a Modal on eventClick using FullCalendar with ReactJS, receiving a "cannot read property of undefined" error. Any advice on how

My MERN stack application utilizes the FullCalendar plugin, even though I am aware that mixing jQuery with React is not ideal. Unfortunately, I am a novice developer and running behind schedule. The goal is to allow users to click on an event on the calen ...

Managing numerous invocations of an asynchronous function

I have an imported component that triggers a function every time the user interacts with it, such as pressing a button. Within this function, I need to fetch data asynchronously. I want the function calls to run asynchronously, meaning each call will wait ...

"Viewed By" aspect of Facebook communities

I'm working on implementing a feature that shows when a post has been seen, similar to Facebook groups, using JS and PHP. I've been able to track the number of times a post has been seen through scrolling actions, but now I want to determine if u ...

A guide on fetching the selected date from a datepicker in framework7 with the help of vuejs

Here is a snippet of the code for a component I am working on: <f7-list-input label=“Fecha de nacimiento” type=“datepicker” placeholder=“Selecciona una fecha” :value=“perfil.fecha_nacimiento” @input=“perfil.fecha_nacimiento = $event.t ...

Please send the canvas image as an attachment, without using ajax to submit it

Is there a way to retrieve the attached file using $_FILES['name'] even when data is sent via AJAX in the POST variable with base64 encoding? Your assistance is greatly appreciated. ...

Displaying the output of a PHP script in an AJAX request

I am trying to display feedback from certain checks, like checking if a file already exists, after making an ajax call to upload a file using my script. However, for some reason, I can't get the response to show up. Why is the response not appearing? ...

Exploring the CSS scale transformation alongside the Javascript offsetHeight attribute

After combining offsetHeight with scale transformation, I experienced a strange result. Below is my simple HTML code: <body> <div id="id01"> Some Text </div> <div id="id02" style="transform-origin: left top; transf ...

Capture and set the new value of the Datetime picker in MUI upon user's acceptance click

import React from 'react' import { Stack, Typography } from '@mui/material' import { DateTimePicker } from '@mui/x-date-pickers/DateTimePicker' import { renderTimeViewClock } from '@mui/x-date-pickers/timeViewRenderers&ap ...