简体   繁体   中英

SQL +AJAX + PHP POST REQUEST

Im trying to use PHP to delete a row in a SQL database. The row is decided by the name of the product the user types in.

I created a simple form to delete products that have already been entered:

<article>
    <section>

        <fieldset><legend><span>Would you like to add a Product?</span>    </legend>

        <form method="POST" id = "myForm" name="myForm" onsubmit="return     false;">

        <br> &nbsp;

        <p>Enter a name of product <input type='text' id='name' name =     'name'/></p>

        <br> &nbsp;

    <input name="submit" id ="submit" type="button" value="Find Product"/>

        </form>
        </fieldset>

        <div id="fetchProduct">
        </div>

    </section>
</article>

Say I have already entered the data on another form and it goes into the database, but when I try to delete it I am getting the Undefined index: name in error when i try to delete.

Here is the script im using to delete the product:

<?php

include("database/connect_database.php");


     $name = $_POST['name'];


 $query = "DELETE FROM products WHERE product_name = '$name' ";

 $result = $database->query($query) OR die ("Failed query $query");
echo $database->error."<p>";

if($result){

    echo "Record deleted";
}
else {

    echo "Product not found!";
}

?>

Im also using AJAX to pass through the name:

  fetch = function () {

// declare the two variables that will be used
var xhr, target, changeListener;

// find the element that should be updated
target = document.getElementById("fetchProduct");

var name = document.getElementById("name").value;

var variable = "name="+name;

// create a request object
xhr = new XMLHttpRequest();

changeListener = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {

        target.innerHTML = xhr.responseText;
    } else {
        target.innerHTML = "<p>Something went wrong.</p>";
    }
};

xhr.open("POST", "deleteProductSQL.php", true);
xhr.onreadystatechange = changeListener;
xhr.send(variable);

 };


 pageLoaded = function () {
var fetchButton = document.getElementById("submit");
if (fetchButton) {
    fetchButton.addEventListener("click", fetch);
}
 };

window.onload = pageLoaded;

Could anyone point out where im going horribly wrong here because I just cant identify why it isn't allowing me to delete the row and why im receiving the undefined error.

Thankyou for your time

Put your PHP code in isset()

if (isset($_POST['name']){
//code here
}

Also

<p>Enter a name of product <input type='text' id='name' name = 'name'/></p>

In this line, <p> is not a self-closing tag so

<p>Enter a name of product <input type='text' id='name' name = 'name'></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM