Empty value for $_POST variable following xmlhttp request

When my code makes an xmlhttp request to a php file with an ID for record deletion from the database, I encounter an issue. The error message 'comicID' is undefined shows up when attempting to delete. This signifies that the variable containing the ID value sent by POST is not properly defined. Currently, the error messages received are: "No comic supplied" with error handling and "Error. Pages in comic not deleted" upon removing the ISSET section of code, rendering the delete query ineffective.

Javascript:

function delComic()
{
    var radioButtons = $("#listID input:radio[name='comicList']");
    var radioID = radioButtons.index(radioButtons.filter(':checked'));
    console.log(radioID);
    if (radioID < 0)
    {
        window.alert("You must select a comic before deleting.");
    }
    else
    {
        var xmlhttp = new XMLHttpRequest();
        var url = "delCom.php?comicID="+radioID;

        xmlhttp.onreadystatechange=function()
        {   
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                var message = xmlhttp.responseText;
                loadComic();
                window.alert(message);
            }
        }
        xmlhttp.open("POST", url, true);
        xmlhttp.send();
    }

}

PHP:

<?php

if (isset($_POST["comicID"])) 
{
    $comic = $_POST["comicID"];
    $dir = 'comics/'.$comic.'/';

    if (!file_exists($dir)) 
    {
        mkdir($dir, 0777, true);
    }

    include_once('includes/conn.inc.php');

    mysqli_query($conn, "DELETE FROM serieslink WHERE comicID = '$comic'");
    $query = ("DELETE FROM page WHERE comicID = '$comic'"); 
    if (!$result = mysqli_query($conn, $query))
    {
        echo ("Query1 error: " . mysqli_error($conn));
        exit;
    }
    else
    {
        if (mysqli_affected_rows($conn) > 0)
        {
            $dirHandle = opendir($dir);
            while($file = readdir($dirHandle))
            {
                if(!is_dir($file))
                {
                    unlink("$dir"."$file");
                }
            }
            closedir($dirHandle);

            rmdir($dir);
            $query2 = ("DELETE FROM comic WHERE comicID = '$comic'");
            if (!mysqli_query($conn, $query2))
            {
                echo ("Query2 error: " . mysqli_error($conn));
                exit;
            }
            else
            {
                if (mysqli_affected_rows($conn) > 0) 
                {
                    echo ("The selected comic was successfully deleted.");
                }
                else
                {
                    echo ("Error. Comic not deleted.");
               }
           }
       }
       else
       {
            echo "Error. Pages in comic not deleted.";
       }
   }   
    $conn->close();
}
else
{
    $comic = null;
    echo "No comic supplied";
}

?>

Answer №1

When using POST for your Ajax request, the process is different compared to using GET. The query string is passed as an argument to the send() function instead of being part of the URL, and you do not need to include the ?:


var xmlhttp = new XMLHttpRequest();
var url = "delCom.php";

xmlhttp.onreadystatechange=function()
{   
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        var message = xmlhttp.responseText;
        loadComic();
        window.alert(message);
    }
}
xmlhttp.open("POST", url, true);
xmlhttp.send("comicID="+radioID);

Edit:

If the parameter values can contain spaces or special characters, it's important to urlencode them. Additionally, to avoid potential browser caching issues, you can include a timestamp parameter:


var d = new Date();
xmlhttp.send("comicID="+encodeURIComponent(radioID)+"&ts="+d.getTime());

The timestamp parameter doesn't need to be processed on the server-side; it's simply used to prevent caching by the browser.

Answer №2

Simply update the initial three lines to resolve any issues.

if (isset($_GET["comicID"])) 
{
$comic = $_GET["comicID"];

Answer №3

By sheer chance, I managed to resolve the issue on my own. It appears that the problem lies in the program halting when attempting to remove all pages linked to a comic. If the comic is already empty, it ends up trying to delete non-existing entries. The simple workaround was to manually insert a page into the comic before deleting it, which worked flawlessly.

Essentially, what I need is proper error handling for empty comics. I appreciate the advice regarding POST, though.

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

Fuzzy background when you scroll

My container has an image that blurs when you scroll down the page by 50 pixels. I feel like I've seen this effect somewhere before, but I can't quite recall where. I want the text to remain unaffected and not turn blue. Here is the HTML: <d ...

Node app experiencing issues with passport authentication request route only in production mode

Currently, I am facing an issue with my MERN app that includes passport for authentication flow. It runs smoothly in development mode but encounters major problems in production mode that I am struggling to resolve. The bug seems elusive and I can't p ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

Using JQUERY to create a dropdown menu that dynamically changes based on the date field

I am currently working on a JQUERY project and facing a challenging situation. I usually know how to create dropdown menus that depend on one another, but this time I need a dropdown menu that displays age ranges based on the date entered in the birth-date ...

What are the steps to sorting in JavaScript?

I need help with sorting an array. The array I have looks like this: var temp = [{"rank":3,"name":"Xan"},{"rank":1,"name":"Man"},{"rank":2,"name":"Han"}] I've tried to sort it using the following code: temp.sort(function(a){ a.rank}) But unfortun ...

"Learn the steps to enable a click-to-select feature for an item, allowing you to drop it in a different location

I've been spending quite some time trying to come up with a solution for my dilemma. The issue arises because I'm not looking to use drag and drop functionality. https://i.stack.imgur.com/Nh1Db.png My goal is to have 3 divs named 1,2,3 as desig ...

The Ajax.ActionLink feature is causing the entire view to be duplicated and inserted into a <div> within the same view

Recently, I started learning MVC and taking on the task of developing an e-commerce application for my aunt's business. The challenge arises with a Product List page that includes a menu to search by category as a partial view. Initially, everything s ...

Sending information from AngularJS to nodeJs/Sequelize

I am currently in the process of developing an e-commerce website using Node.js/Sequelize and AngularJS. For my project, I have organized it into 2 main folders: Client (which houses AngularJS starter files) https://i.stack.imgur.com/0vzsF.png Server ...

Seeking the "onChange" functionality while implementing the "addEventListener" method

I've been busy with a React project lately. Instead of adding 'onChange' to each button within the html object like this: <input type='text' onChange={myFunction} /> I'd prefer to include it in the JS code like so: doc ...

Tips for converting spaces to tabs exclusively on a new line?

I am struggling with converting multi-line strings that are indented with spaces into tabs. Consider this script for example.php <?php echo <<<EOT ----------------------------------------------------------------------- Example with spaces: - ...

What is the method for initializing fancybox with the precise image index?

My current usage of fancybox involves the following code snippet: $("a[rel=Fancy" + UserId + "].Items").fancybox({ 'autoscale': 'false', 'cyclic': true, 'transitionIn': 'elastic', & ...

Using Conditional Tags for CSS Display

I'm working on implementing Conditional Tags to toggle a CSS class on or off based on the current displayed page. However, I'm running into an issue where the code isn't executing properly. There might be a syntax or logic error causing the ...

JSF not triggering Ajax event

I'm facing an issue where the Ajax event is not firing to call the actionListener or update the second select menu. Can anyone help me with what might be causing this problem? <p:selectOneMenu value="#{player}" converter="playerCon ...

The recent upgrade to Laravel 5.2 has caused issues with PHPUnit, rendering it inoperable

To ensure our project stays current and can benefit from the latest developments, we made the upgrade from Laravel 5.1 to 5.2 yesterday. After spending some time tweaking our codebase, everything appears to be functioning normally, except for the fact that ...

Executing a controller function in AngularJS from an event

I am facing an issue with my AngularJS code. I have defined a function within my controller, and I am trying to call it inside an event listener, but I keep getting an 'undefined' error. Here is how the controller code looks like: inputApp.cont ...

Search and extract JSON data in MySQL

Currently, I am inputting JSON objects into a MySQL Database and then executing queries on them. Within the database is a table structured as follows: subjects | ----------------------------------------------- ...

Steps for changing the language in KeyboardDatePicker material ui

Currently, I am utilizing material ui on my website and leveraging the KeyboardDatePicker API with successful results. The only issue is that the months' names and button text are displayed in English, whereas I would prefer them to be in Spanish. Des ...

What is the best way to utilize Ajax and Jquery in order to retrieve data from a PHP database and dynamically update elements with the fetched information?

I am currently enhancing a website to simplify the process for employees when editing products. At present, in order to change prices, someone has to log in to the database and manually alter them, followed by making adjustments to the HTML of the website ...

How to use the Enter key to submit a form in react.js with the help of "@material-ui/core/Button"

Here is the form I have created using the render method for user sign-in. <form onSubmit={this.handleSubmit}> <Avatar className={classes.avatar}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" varia ...