SweetAlert: The title argument is not present

I encountered an error when the error function is triggered from sweet alert. How can I resolve this issue? Appreciate any help!

SweetAlert: Missing "title" argument!

Here is my JavaScript code:

function DeletePost() {
    swal({
        title: "Are you sure?",
        text: "This operation is irreversible and will delete the communication along with its connected comments from the database!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete communication!",
        cancelButtonClass: "btn btn-danger",
        cancelButtonText: "No, do not proceed!",
        closeOnConfirm: false,
        closeOnCancel: false
    }, function(isConfirm) {
        if (isConfirm) {

            $.ajax({
                url: "../delete_all.php",
                method: "POST",
                dataType: 'json',

                success: function(response) {
                  // swal('Deleted!', response.message, response.status);
                    swal({

                      title: response.title, 
                      text: response.message, 
                      type: response.status

                    },

                    function(){ 

                      location.reload();

                    }

                  );

                },

                error: function(response) {

                  swal({

                      title: response.title,
                      text: response.message, 
                      type: response.status

                    });


                }



            }); 

        } else {
            swal("Cancelled!", "Operation cancelled successfully!", "error");
        }
    });
}

And here is my PHP file:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Fetch the administrator's id and assign it to a variable
    $userid = $_SESSION['user_id'];

    if($delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'")){ 

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Send response message if the operation was successful
    $response['title']  = 'Messages deleted!';
    $response['message'] = 'All messages have been deleted successfully.';
    $response['status']  = 'success';

    }else{

    // Send response message if the operation failed
    $response['title']  = 'An error occurred!';
    $response['message'] = 'Unable to delete messages. Please contact system administrator';
    $response['status']  = 'error';

    }

    echo json_encode($response);

}

Answer №1

Make sure to remember converting json's response to a JavaScript object

Everything should work fine after this adjustment

 $.ajax({
      url: "../delete_all.php",
      method: "POST",
      dataType: 'json',
      success: function(response) {
         // swal('Deleted!', response.message, response.status);

         response= JSON.parse(response);

         swal({
            title: response.title, 
                  ...

I included this additional line

  response= JSON.parse(response);

Answer №2

showPopUp({
  title: response.title || 'No Title Set', 
  content: response.message || 'No Message Set', 
  style: response.status || 'Status Not Defined'
}, function() {

});

How about this?

showPopUp({
  title: JSON.parse(response.respoonseText).title
  // ...
}, function() {

});
response = JSON.parse(response.responseText);
showPopUp({
  title: response.title || 'No Title Set', 
  content: response.message || 'No Message Set', 
  style: response.status || 'Status Not Defined'
}, function() {

});

Answer №3

Thank you so much for your assistance. I discovered that the issue was within the PHP file, but after making some changes it is now functioning perfectly. My main goal was to test and validate the variable before executing a query in the database. Additionally, I wanted to display an error message if the query could not be completed successfully.

Below is a snippet of my PHP code:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    $user_id = 'prova';

    if (!filter_var($user_id, FILTER_VALIDATE_INT)) {
        // Display an error message if the operation failed
    $response['title']  = 'An Error Occurred!';
    $response['message'] = 'Unable to delete messages. Please contact the system administrator.';
    $response['status']  = 'error';

    echo json_encode($response);

    } else {

    // Sanitize and retrieve the admin ID
    $user_id = filter_var($_SESSION['user_id'], FILTER_SANITIZE_NUMBER_INT);

    $delete_inbox  = mysqli_prepare($conn, "DELETE FROM user_inbox where user_inbox_user=? AND user_inbox_status = 'trash'");

           mysqli_stmt_bind_param($delete_inbox, 'i', $userid);
           mysqli_stmt_execute($delete_inbox);
           mysqli_stmt_close($delete_inbox);

    // Message displayed upon successful operation
    $response['title']  = 'Messages Deleted!';
    $response['message'] = 'All messages have been successfully deleted.';
    $response['status']  = 'success';

    echo json_encode($response);

    }

I deliberately set $user_id as non-integer to trigger an error.

The functionality is now improved and no longer requires the use of title: JSON.parse(response.respoonseText).title or response=JSON.parse(response);

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

Managing repeated calls to a specific get function in nodejs

Utilizing an Ajax call, I am invoking the following GET function every 10 seconds to monitor the status of various URLs. app.get('/getUrl', function(req, res) { var response = {}; var keyArr = []; var urlData ...

Parameters in Typescript decorators

Can someone help me understand the various parameters of a Typescript decorator? function myDecorator(target) { // do something with 'target' ... } In the given example, I am aware that 'target' represents the function/class to wh ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Issue with Material UI TextField and Redux Form integration

Having trouble with a textfield that I am trying to integrate with Redux Form. Here is how I have set it up: const renderTextField = props => ( <TextField {...props} /> ); Usage example: <Field id="searchCif" name="sear ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

Executing a JavaScript code in a Python webdriver: A step-by-step guide

Using Selenium 2 Python webdriver: I encountered an issue where I needed to click on a hidden element due to a hover effect. In search of solutions to unhide and select the element, I came across the following examples: Example in Java: JavascriptExecut ...

Display only the offcanvas button

Having trouble with Bootstrap 5 offcanvas? The offcanvas doesn't hide when I click the button again. <button data-bs-toggle="offcanvas" role="button">Add to Cart</button> Every time I click the button again, the offcan ...

Tips for retrieving a local variable from inside a callback and using it outside the function

Recently, I started utilizing npm plaid and I'm looking for a way to access the variable trans outside of the plaidClient.getTransactions function. Any suggestions would be greatly appreciated. var trans; var startDate = moment().subtract(30, &apo ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...

"Enhance Your Website with Javascript: Combining and Incorpor

I'm struggling to assign the selected attribute to the option value that is already rendered within the object. However, despite the values being equal, the selected attribute is not being added. Could this issue be related to the appending process? ...

Tips for resolving the error "Binding element has no default value and initializer provides no value in TypeScript"

I am currently in the process of converting a JavaScript Apollo GraphQL API project to TypeScript. During this migration, I encountered an error related to a user code block: var idArg: any Initializer provides no value for this binding element and the ...

Display loading spinners for multiple ajax requests

At the moment, I am displaying spinners using the ajax setup method call: (function() { $.ajaxSetup({ beforeSend: showLoader, complete: hideLoader, error: hideLoader }); })(); While this setup is functioning properly, the ...

Tips on successfully executing the swap method in the JustSwap smart contract

I'm attempting to finalize the JustSwap-contract S-USDT-TRX Token (TQn9Y2khEsLJW1ChVWFMSMeRDow5KcbLSE), but I keep receiving a "REVERT opcode executed" response in the console. My code: const TronWeb = require("tronweb"); const ethers ...

unable to display images from a folder using v-for in Vue.js

Just getting started with Vuejs and I have two pictures stored on my website. The v-for loop is correctly populating the information inside databaseListItem. The path is /opt/lampp/htdocs/products_db/stored_images/cms.png https://i.stack.imgur.com/969U7.p ...

The art of linking JavaScript events

I'm encountering some challenges with linking events together. I've set up an eventListener on a variety of links that, when hovered over, trigger a drop-down menu to appear. Everything is functioning properly, but I also want triangular shapes ...

I want to save the information for "KEY" and "textValue" in JSON format and then return it as a response when I make a request to app.get("/api"). How can I achieve this?

Working with GCP Document AI using Node.js and react.js, I have created a JSON structure (var jsonResult) in the provided code. In the for loop, I am extracting key and text value data by using console.log(key); and console.log(textValue);. However, my g ...

What are the benefits of using CSS to convert text to uppercase?

Today, I came across an intriguing observation. While browsing through code, I noticed that text was being transformed to uppercase using CSS instead of the common JavaScript method toUpperCase(). Surprisingly, this approach caused a test to fail. The test ...

Avoid Scrolling within an iFrame in HTML with the Use of #

I have a menu loading in an iframe with links using # like http://<location>/page.html#part1. When I click inside the iframe, the entire page outside of the iframe scrolls to the location of #. How can I stop this from happening? I only want the me ...

Getting AJAX parameters from Angular in Node/Express Js

I am encountering an issue with my factory, which sends an ajax userId call to my node server. usersModel.getUser = function(userId){ return $http({ method: 'GET', url: 'http://localhost:3000/users/details', ...