Insert data to MySQL using PHP with SweetAlert display/button

  ajax, mysql, php, sweetalert

I want to insert the data to MySQL so the SweetAlert is already popping when I am triggering the submit button, but after clicking Ok, it doesn’t do anything.
this is my ajax from

AddResearch.php

<script>
        $("#submit").click(function(){
            var research_title = $("#research_title").val();
            var research_type = $("#research_type").val();
            var research_timeline = $("#research_timeline").val();
            var file = $("#file").val();
            var research_description = $("#research_description").val();
            var research_author = $("#research_author").val();
            var research_photo = $("#research_photo").val();
            
            event.preventDefault();

            swal({
                title: "Are you sure?",
                text: "You are about to add this file to the Repository!",
                icon: "info",
                buttons: true,
                })
                .then((addToDatabase) => {
                if (!addToDatabase) {
                    swal("Your imaginary file is safe!");
                } else {            
                    $.ajax({
                        type: 'POST',
                        url:'includes/AddResearch.php',
                        data: {research_title:research_title,research_type:research_type,research_timeline:research_timeline,
                            file:file,research_description:research_description,research_author:research_author,research_photo:research_photo},
                        dataType: 'json',
                        success:function(data){
                                            swal("Success", "Data Saved Successfully", "success");
                                        },
                                        error:function(xhr, thrownError, ajaxOptions){

                                        }
                    });     
                }
                });
        })     
    </script>

I separated my modal Ui to avoid confusion for me when coding. So I added it on the other folder.

helper/helper_AddResearch.php

              <form name="myForm" method="POST" enctype="multipart/form-data">
                  <div class="form-group " id="firstForm">
                    <label for="LabelTitle">Research Title</label>
                    <input type="text" name="research_title" class="form-control" id="research_title" aria-describedby="emailHelp" placeholder="What is the title of the Research?" required="">
                  </div>
                  <div class="form-group">
                    <label for="LabelTitle">Research Type</label>
                    <input type="text" name="research_type" class="form-control" id="research_type" placeholder="What is the type of this Research?" required="">
                  </div>
                  <div class="form-group">
                    <label for="LabelTitle">Research Timeline</label>
                    <input type="text" name="research_timeline" class="form-control" id="research_timeline" placeholder="What year was the research finished?" required="">
                  </div>
                  <div class="form-group">
                    <label for="LabelTitle">Research Files</label>
                    <input type="file" name="file" class="btn btn-default" accept="application/pdf" id="file" placeholder="Add Research Type" required="">
                    <button type="button" onclick="document.getElementById('file').value = ''" class="btn btn-info" >
                    <i class="fa fa-trash" aria-hidden="true"></i>
                    Remove File
                    </button>
                    
                  </div>
                  <div class="form-group">
                    <label for="exampleFormControlTextarea1">Research Description</label>
                    <textarea class="form-control" name="research_description" id="research_description" rows="3" required=""></textarea>
                  </div>
                  <div class="form-group">
                    <label for="LabelTitle">Research Author</label>
                    <input type="text" name="research_author" class="form-control" id="research_author" placeholder="Research Authors" required="">
                  </div>
                  <div class="form-group">
                    <label for="LabelTitle">Research Photo</label>
                    <input type="file" name="research_photo" accept="image/gif, image/jpeg, image/png" class="btn btn-default" id="research_photo" placeholder="Research Photo" required="">
                    <button type="button" class="btn btn-info" id="removePhoto" onClick="document.getElementById('research_photo').value = ''">
                      <i class="fa fa-trash" aria-hidden="true"></i>
                      Remove Photo
                    </button>
                  </div>
                  <div class="form-group">
                  <input type="submit" name="submit" id="submit" class="btn btn-primary form-control" value="ADD">
                  </div>
                </form>

and lastly for my insert code.
I separated it as well on the different folder.

includes/AddResearch.php

<!doctype html>
<html lang="en">
  <head>
    <title>Title</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  </head>
  <body>
  <?php


    include 'connection.php';

    $storedFile="../files/RepositoryFiles/".basename($_FILES["file"]["name"]);
    $research_photo="../files/Images/".basename($_FILES["research_photo"]["name"]);
    if(file_exists($storedFile) or file_exists($research_photo)){
        echo "<script type='text/javascript'>alert('Research File is already Existing!'); location.href='../admin/AddResearch.php?adding=failed';</script>";
    }
    else if($_FILES["file"]["size"] > 10000000){
        echo "<script type='text/javascript'>alert('Research File should be less than 10MB!'); location.href='../admin/AddResearch.php?adding=failed';</script>";
    }
    else if($_FILES["research_photo"]["size"] > 10000000 ) {
        echo "<script type='text/javascript'>alert('Research Photo should be less than 10MB!'); location.href='../admin/AddResearch.php?adding=failed';</script>";
    }
    else {
    $research_title = $_POST['research_title'];
    $research_type = $_POST['research_type'];
    $research_timeline = $_POST['research_timeline'];
    // $storedFile="../files/RepositoryFiles/".basename($_FILES["file"]["name"]);
            move_uploaded_file($_FILES["file"]["tmp_name"], $storedFile);
    $research_description = $_POST['research_description'];
    $research_author = $_POST['research_author'];
    // $research_photo="../files/Images/".basename($_FILES["research_photo"]["name"]);
            move_uploaded_file($_FILES["research_photo"]["tmp_name"], $research_photo);
    $sql = "INSERT INTO tbl_repository (research_title, research_type, research_timeline, research_file, research_description, research_author, research_photo) VALUES (?,?,?,?,?,?,?);";
    $stmt = mysqli_stmt_init($conn);
    if(!mysqli_stmt_prepare($stmt,$sql)){
        echo "SQL Error";
    }
    else {
        mysqli_stmt_bind_param($stmt,"sssssss", $research_title, $research_type, $research_timeline, $storedFile, $research_description, $research_author,$research_photo); 
        mysqli_stmt_execute($stmt);
    }
    }

?>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  </body>
</html>

Solutions that I’ve tried, I already replace the slim jquery to the min.js since I had an error where I had to replace the slim jquery since it does not support ajax.

Currently, right now there’s no error in the Developer Option or please do tell me if I missed something.

Source: Ask PHP

LEAVE A COMMENT