0

I am new to Ajax and PHP. There are many similar questions already asked regarding this issue but i could not find any appropriate answer yet.

I have three files

createPackage.php

<!DOCTYPE html>
<html>
<head>
    <title>Create Package</title>
    <script type="text/javascript" language="javascript" src="js/createPackage.js"></script>
  <?php include 'include/links.html' ?>
</head>

<?php include 'include/header.php' ?>

<body style="background: #edecec;">

  <div id="layoutSidenav">
    <?php include 'include/sidenav.php' ?>
    <div id="layoutSidenav_content">
        <main>
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="index.php">Home</a><i class="fa fa-angle-right mx-2 text-dark"></i>Create Package </li>
        </ol>
        <div class="crudModal">
            <!-- Button trigger modal -->
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">Create Package
            </button>
            <!-- Modal -->
            <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-fullscreen">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="exampleModalLabel">Create Package</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="CreatePackage">
                                <div class="container-fluid p-3">
                                <!--  form   -->
                                    <form method="POST" class="form">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="PackageName">Package Name</label>
                                                <input type="text" class="form-control" name="pkgType" placeholder="Package Name" id="PackageName">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="PackageType">Package Type</label>
                                                <input type="text" name="packagetype" class="form-control" placeholder="Package Type eg-Family Package / Couple Package" id="PackageType">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                    </div>

                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="PackageLocation">Package Location</label>
                                                <input type="text" name="pkgLocation" class="form-control" placeholder="Package Location" id="PackageLocation">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="PackagePrice">Package Price</label>
                                                <input type="text" name="pkgPrice" class="form-control" id="PackagePrice" placeholder="Package Price in PKR">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                    </div>
                                    <!--  row   -->
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="PackageFeature">Package Features</label>
                                                <input type="text" name="pkgFeatures" class="form-control" id="PackageFeature" placeholder="Package Features eg-Free Pick & Drop Facility">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                        <div class="col-md-6">
                                            <div class="form-group">
                                                <label for="uploadFile">Package Images</label>
                                                <input type="file" name="Image" class="form-control" id="uploadFile" placeholder="image">
                                            </div>
                                        </div>
                                        <!--  col-md-6   -->
                                        <!--  row   -->
                                        <div class="row" style="--bs-gutter-x: 0.7rem;">
                                            <div class="col-12">
                                                <div class="form-group">
                                                    <textarea class="form-control" name="pkgDetails" rows="5" cols="50"  id="packagedetails" placeholder="Package Details" required="required"></textarea>
                                                </div>
                                            </div>
                                        </div>
                                    </div><!-- createPackage -->
                                    <div id="status" style="border:1px solid red;">
                                    </div>

                                    <!--     <div class="d-flex mb-2">
                                    <div class="mx-auto">
                                        <input type="submit" name="submit" class="btn btn-success px-5 py-2" value="submit">
                                        <input type="reset" class="btn btn-danger px-5 py-2">
                                    </div>
                                </div> -->
                                <div class="modal-footer">
                                    <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> -->
                                    <input type="reset" ata-bs-dismiss="modal" class="btn btn-secondary px-5 py-2">
                                    <input type="button" onclick="sub_form();" class="btn btn-primary px-5 py-2" value="submit">
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div> 
</main>
        <?php include 'include/scripts.html' ?>
</body>
</html>

createPackage.js

var xmlhttp;
 
/////////////////////////////////////////////////////
function GetXmlHttpObject()
{
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        return new XMLHttpRequest();
    }
    if (window.ActiveXObject) {
        // code for IE6, IE5
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    return null;
}
//======================================
     
 
function sub_form()
{
    xmlhttp=GetXmlHttpObject();
    if (xmlhttp==null) {
        alert ("Browser does not support HTTP Request");
        return;
    }
    // if($("#formID").validationEngine('validate')==false){
    //      return false;
    //      } 

    var pkgName = document.getElementById("PackageName").value;
    var pkgtype = document.getElementById("PackageType").value;
    var pkgLocation = document.getElementById("PackageLocation").value;
    var pkgPrice = document.getElementById("PackagePrice").value;
    var pkgFeatures = document.getElementById("PackageFeature").value;
    var pkgimage = document.getElementById("uploadFile").value;

    // if(Password == "")
    // {
    //  document.getElementById("password").style.border="1px solid red";
    //  document.getElementById("abc").innerHTML="<p class = text-danger>Please Enter Password</p>";
    //  exit(1);
    // }

 
    var url = "createPackage_ajax.php";
    url = url + "?func=insert&pkgName="+pkgName+"&pkgtype="+pkgtype+
                "&pkgLocation="+pkgLocation+"&pkgPrice="+pkgPrice+
                "&pkgFeatures="+pkgFeatures+"&pkgimage="+pkgimage;

    // var url = "signup_ajax.php";
    // url = url + "?func=insert&FullName="+FullName+"&email="+email+"&phone="+phone+"&password="+password+"&cpassword="+cpassword;

    xmlhttp.onreadystatechange=abc_callback;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);

    // document.getElementById("FullName").value="";
    // document.getElementById("FullName").style.border="1px solid #ced4da";
    // document.getElementById("email").value="";
    // document.getElementById("email").style.border="1px solid #ced4da";
    // document.getElementById("phone").value="";
    // document.getElementById("phone").style.border="1px solid #ced4da";
    // document.getElementById("password").value="";
    // document.getElementById("cpassword").value="";
} 

function abc_callback()
{
    if (xmlhttp.readyState==4){ 
        // document.getElementById("quantity").value="";
        //document.getElementById("pp").value="";
        //document.getElementById("total_p").value="";
        //document.getElementById("gst_p").value="";
        //document.getElementById("gst").value="";   
        //document.getElementById("total_p2").value="";
        0
        var responce= xmlhttp.responseText;
        // alert(responce);
        //getall();
        document.getElementById("status").innerHTML=xmlhttp.responseText;
        //document.getElementById("prin").style.display="";
        
        // document.getElementById("mesage").innerHTML=xmlhttp.responseText;
        // document.getElementById("name").select();
    }
}

//=================================================================//

////////////////////GET ALL RECORDS STARTS  /////////////

createPackage_ajax.php

<?php
    // error_reporting(0);
    $func= $_GET['func']?$_GET['func']:$_POST['func'];

    include 'include/config.php';
    if($func == "insert") {
        $PACKAGENAME = mysqli_real_escape_string($con, $_GET['pkgName']);
        $PACKAGETYPE = mysqli_real_escape_string($con, $_GET['pkgType']);             //line 9
        $PACKAGELOCATION = mysqli_real_escape_string($con, $_GET['pkgLocation']);
        $PACKAGEPRICE = mysqli_real_escape_string($con, $_GET['pkgPrice']);
        $PACKAGEFEATURE = mysqli_real_escape_string($con, $_GET['pkgFeatures']);
        $PACKAGEDETAILS = mysqli_real_escape_string($con, $_GET['pkgDetails']);          // line 13
        $PACKAGEIMAGE = mysqli_real_escape_string($con, $_GET['Image']);                //line 14

        $INSERT = "INSERT INTO `packages`
                            (pkgName, pkgType, pkgLocation, pkgPrice, 
                            pkgFeature, pkgDetails, Image) 
                    VALUES ('$PACKAGENAME', '$PACKAGETYPE', 
                            '$PACKAGELOCATION', '$PACKAGEPRICE', 
                            '$PACKAGEFEATURE', '$PACKAGEDETAILS', 
                            '$PACKAGEIMAGE')";

        $INSERT_QUERY = mysqli_query($con, $INSERT);

        if($INSERT_QUERY) {
            echo "Success: Package has been Created";
        }else{
            echo "Failure: Package can't be Created";
            exit;
        }

        $INSERT = "SELECT * FROM packages";
        $QUERY = mysqli_query($con, $INSERT);
        $table = "<table border=1 cellpadding=10 >";
        $table.="<tr><th>ID</th><th>Name</th><th>Type</th><th>Location</th><th>Price</th><th>Features</th><th>Image</th></tr>";

        while($FETCH = mysqli_fetch_assoc($QUERY)) {
            $table.="<tr><td>".$FETCH['Pkg_ID']."</td>"."<td>".$FETCH['pkgName']."</td>"."<td>".$FETCH['pkgType']."</td>". "<td>".$FETCH['pkgLocation']."</td>"."<td>".$FETCH['pkgPrice']."</td>"."<td>".$FETCH['pkgFeature']."</td>"."<td>".$FETCH['Image']."</td></tr>";
        // code...
        }
        $table.="</table>";
        echo $table;
    }
?>

PROBLEM

The issue I'm facing is whenever i press submit button i got these warnings:

Warning: Undefined array key "pkgType" in C:\xampp\htdocs\WST Project\admin\createPackage_ajax.php on line 9
Warning: Undefined array key "pkgDetails" in C:\xampp\htdocs\WST Project\admin\createPackage_ajax.php on line 13
Warning: Undefined array key "Image" in C:\xampp\htdocs\WST Project\admin\createPackage_ajax.php on line 14

I dont get it why i'm facing this issue my other input fields are submiting but only these 3 are not working. P.s I have mentioned line number in the code

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • Your script is open to [SQL Injection Attack](http://stackoverflow.com/questions/60174). Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187) You should always use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's instead of concatenating user provided values into the query. Never trust ANY user input! – RiggsFolly Jun 15 '22 at 15:37
  • Good code indentation would help us read the code and more importantly it will help **you debug your code** [Take a quick look at a coding standard](https://www.php-fig.org/psr/psr-12/) for your own benefit. You may be asked to amend this code in a few weeks/months and you will thank me in the end. – RiggsFolly Jun 15 '22 at 15:38
  • I know brother. Thanks for helping but can you guide me about the problem i'm facing – Linear Data Structure Jun 15 '22 at 15:39
  • 2
    Try `var_dump($_GET); var_dump($_POST);` to see what variables they contain and which super global they're in. You're checking both GET and POST for the function, so you want to try to be consistent. I wouldn't recommend using GET for an insert request, as that can open it up for security holes. Your ajax is using GET, but your form is POST, so the ajax may not be coming into play, or may just not be preventing the regular form submission. – aynber Jun 15 '22 at 15:42
  • i changed it to the GET and I tried `var_dump() ` but it gives `string(0) "" ` . – Linear Data Structure Jun 15 '22 at 15:45
  • Even though @aynber said ___I wouldn't recommend using GET___ – RiggsFolly Jun 15 '22 at 15:47
  • I have tried with POST also – Linear Data Structure Jun 15 '22 at 15:48
  • `abc_callback()` has an odd `0` in there for some reason – RiggsFolly Jun 15 '22 at 15:51
  • Thanks for telling. But i assume that you know, this is not the factor effecting my problem – Linear Data Structure Jun 15 '22 at 15:54
  • 1
    `var_dump($_GET);` gives you an empty string? You're only getting missing array keys on some of the lines, but not others, so I'd suggest double-checking the contents of `$_GET` – aynber Jun 15 '22 at 16:06
  • 2
    `pkgtype` has a typo in your ajax, it should be `pkgType`, which would give you that error. The ajax string does not have `pkgDetails`, and you're passing `pkgimage` instead of `Image` – aynber Jun 15 '22 at 16:07
  • 1
    Oh and you cannot pass files like that, you need to look up [`FormData`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects#sending_files_using_a_formdata_object) – RiggsFolly Jun 15 '22 at 16:12
  • And it may seem trivial _the bit about the 0 in the code_ but when one bit of JS fails to compile there can often be quite a knock on to other bits of you js code not compiling and therefore not running – RiggsFolly Jun 15 '22 at 16:17

0 Answers0