Wednesday 31 July 2024

how to upload images in php & jquery

 



fileupload.php :


<?php
$filename = $_FILES['file']['name'];
$location = "Images/".$filename;
$uploadOk = 1;
$imageFileType = pathinfo($location,PATHINFO_EXTENSION);
$valid_extensions = array("jpg","jpeg","png");
if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
   $uploadOk = 0;
}if($uploadOk == 0){
   echo 0;
}else{
   if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
      echo 1;
   }else{
      echo 0;
   }
}
?>

API

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: *');
header('Access-Control-Allow-Headers: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Max-Age: 3600");
include "conn.php";
$json = file_get_contents("php://input");
$obj= json_decode($json,true);
$mark= $obj["mark"];
if ($mark==1)
{
$result=mysqli_query($conn,"SELECT ID,RNUMBER,CATEGORY,r.DESCRIPTION,PRICE,rt.RID,rt.RTNAME,bt.BID,bt.BTNAME,r.STATUS FROM `room` r
JOIN roomtype rt ON r.RID=rt.RID
JOIN bedtype bt on r.BID=bt.BID
order by ID desc");
if (mysqli_num_rows($result) > 0) {
while($row[] = mysqli_fetch_assoc($result)) {
$data=json_encode($row);
}
echo $data;
}
else
{
echo json_encode("result not found.");
}
}
elseif($mark==2)
{
$iD=$obj["ID"];
$result=mysqli_query($conn,"Select * from room where ID='$iD'");
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$data=json_encode($row);
}
echo $data;
}
else
{
echo json_encode("result not found.");
}
}
elseif($mark==3)
{
$rNUMBER=$obj["RNUMBER"];
$rID=$obj["RID"];
$bID=$obj["BID"];
$cATEGORY=$obj["CATEGORY"];
$pRICE=$obj["PRICE"];
$dESCRIPTION=$obj["DESCRIPTION"];
$result=mysqli_query($conn,"INSERT INTO `room`(`RNUMBER`, `RID`, `BID`, `CATEGORY`, `PRICE`, `DESCRIPTION`) VALUES ('$rNUMBER','$rID','$bID','$cATEGORY','$pRICE','$dESCRIPTION')");
$rMID = mysqli_insert_id($conn);
$rI= (array) $obj["RI"];
for($i = 0; $i < count($rI); $i++) {
$pATH=$rI[$i]["PATH"];
$result1=mysqli_query($conn,"INSERT INTO `roomimage`(`RMID`, `PATH`) VALUES ('$rMID','$pATH')");
}
if($result1)
{
echo json_encode("Data Inserted successfully.");
}
else
{
echo json_encode("Something went wrong.");
}
}
elseif($mark==4)
{
$iD=$obj["ID"];
$rNUMBER=$obj["RNUMBER"];
$rID=$obj["RID"];
$bID=$obj["BID"];
$cATEGORY=$obj["CATEGORY"];
$pRICE=$obj["PRICE"];
$dESCRIPTION=$obj["DESCRIPTION"];
$result=mysqli_query($conn,"UPDATE `room` SET `RNUMBER`='$rNUMBER',`RID`='$rID',`BID`='$bID',`CATEGORY`='$cATEGORY',`PRICE`='$pRICE',`DESCRIPTION`='$dESCRIPTION' WHERE `ID`='$iD'");
$result1=mysqli_query($conn,"DELETE FROM `roomimage` WHERE RMID='$iD'");
$rI= (array) $obj["RI"];
for($i = 0; $i < count($rI); $i++) {
$pATH=$rI[$i]["PATH"];
$result2=mysqli_query($conn,"INSERT INTO `roomimage`(`RMID`, `PATH`) VALUES ('$iD','$pATH')");
}
if($result2)
{
echo json_encode("Data Updated successfully.");
}
else
{
echo json_encode("Something went wrong.");
}
}
elseif($mark==5)
{
$iD=$obj["ID"];
$result=mysqli_query($conn,"delete from `room` where ID='$iD'");
$result1=mysqli_query($conn,"DELETE FROM `roomimage` WHERE RMID='$iD'");
if($result1)
{
echo json_encode("Data deleted successfully.");
}
else
{
echo json_encode("Something went wrong.");
}
}
elseif ($mark==6)
{
$iD=$obj["ID"];
$result=mysqli_query($conn,"SELECT `ID`, `RMID`, `PATH` FROM `roomimage` WHERE RMID='$iD'");
if (mysqli_num_rows($result) > 0) {
while($row[] = mysqli_fetch_assoc($result)) {
$data=json_encode($row);
}
echo $data;
}
else
{
echo json_encode("result not found.");
}
}
elseif($mark==7)
{
$iD=$obj["ID"];
$rNUMBER=$obj["RNUMBER"];
$rID=$obj["RID"];
$bID=$obj["BID"];
$cATEGORY=$obj["CATEGORY"];
$pRICE=$obj["PRICE"];
$dESCRIPTION=$obj["DESCRIPTION"];
$result1=mysqli_query($conn,"UPDATE `room` SET `RNUMBER`='$rNUMBER',`RID`='$rID',`BID`='$bID',`CATEGORY`='$cATEGORY',`PRICE`='$pRICE',`DESCRIPTION`='$dESCRIPTION' WHERE `ID`='$iD'");
if($result1)
{
echo json_encode("Data Updated successfully.");
}
else
{
echo json_encode("Something went wrong.");
}
}
mysqli_close($conn);
?>

Room.php :

<?php include "Header.php" ?>
<style>
    td.details-control {
        background: url('Images/details_open.png') no-repeat center center;
        cursor: pointer;
    }

    tr.shown td.details-control {
        background: url('Images/details_close.png') no-repeat center center;
    }
</style>

<div class="container" style="padding-top:10px;height:500px">
<a  class="btn btn-primary" id="an"  >Add New</a>
<br><br>
<div class="modal fade" id="myModal" role="dialog" data-keyboard="false" data-backdrop="static" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Room Entry</h4>
        </div>
        <div class="modal-body">
        <form id="newModalForm">
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Room Number</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <input type="text" id="cn" name="cn" class="form-control" required>
                </div>
        </div>
       
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Room Type</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <select id="rt" name="rt" class="form-control">
                </select>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Bed Type</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <select id="bt" name="bt" class="form-control">
                </select>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Category</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <select id="ct" name="ct" class="form-control">
                  <option>Ac</option>
                  <option selected>Non Ac</option>
                </select>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Room Picture</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
               <input type="file" id="file" name="file1"  class="form-control" required multiple>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Price</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <input type="text" id="mn" name="mn" class="form-control" required>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3">Description</div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <textarea id="add" name="add" rows="3" class="form-control" required></textarea>
                </div>
        </div>
        <div class="row form-group">
                <div class="col-md-3 col-sm-3 col-lg-3 col-xl-3"></div>
                <div class="col-md-6 col-sm-6 col-lg-6 col-xl-6">
                <div id="divError" class="alert alert-success collapse">


<div id="divErrorText"></div>
</div>
                </div>
                </div>
        </from>
        </div>
        <div class="modal-footer">
        <input style="width:80px" type="button" value="Submit" id="btnsave" name="btnsave" class="btn btn-primary">
        <input type="reset" value="Reset" class="btn btn-primary" style="width:80px">
        </div>
      </div>
     
    </div>
  </div>
<div style="border:1px solid #ffffff">
<div class="row col-md-12 col-sm-12 col-lg-12 col-xl-12">
<table class="table table-bordered table-condensed table-hover table-responsive table-striped" id="tb">
<thead>
<tr class="bg bg-primary">
        <th></th>
        <th>ID</th>
        <th>ROOM NUMBER</th>
        <th>ROOM TYPE</th>
        <th>BED TYPE</th>
        <th>CATEGORY</th>
        <th>PRICE</th>
        <th>DESCRIPTION</th>
        <th>STATUS</th>
        <th>ACTION</th>
    </tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
    var IID;
    var uri;
    $(function(){
        uri="http://localhost:8080/Hotelpuri/API/Room";
        uri1="http://localhost:8080/Hotelpuri/API/Roomtype";
        uri2="http://localhost:8080/Hotelpuri/API/Bedtype";
        $('#myModal').on('hidden.bs.modal', function () {
        $(this).find('form').trigger('reset');
        });
        $('#an').click(function(){
            cls();
            IID=0;
            var m= $('#myModal');
            m.modal('show');
        });
        function cls() {
            $('#cn').val('');
            $('#add').val('');
            $('#mn').val('');
            $('#em').val('');
        }
      $("#tb").on('click','.x',function(){
        var currentRow=$(this).closest("tr");
         IID=currentRow.find("td:eq(0)").text();
     $('#cn-error').html('');
        $.ajax({
                    url:  uri,
                    type: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                      "mark":2,
                      PID:IID
                    }),
                    success: function (data) {
                        $('#cn').val(data.NAME);
                        $('#add').val(data.ADDRESS);
                        $('#mn').val(data.MOBILE);
                        $('#em').val(data.EMAIL);
                    },
                    error: function (t) {
                        alert(t.responseText);
                    }
                });
      var m= $('#myModal');
      m.modal('show');
    });
    $.validator.addMethod("ddl",function(value) {return value!=0;});
      $("#newModalForm").validate({
        rules: {
            cn: {
                required: true
            },
            add: {
                required: true
            },
            mn: {
                required: true
            },
            file: {
                required: true
            },
            rt: {
              ddl: true
            },
            bt: {
              ddl: true
            }
        },
        messages: {
            cn: {
                required: "Room number should not be blank."
            },
            add: {
                required: "Description should not be blank."
            },
            mn: {
                required: "Price should not be blank."
            },
            bt: {
              ddl: "Please select a bed type."
            },
            rt: {
              ddl: "Please select a room type."
            },
            file: {
              required: "Please select a picture."
            }
           
        }
    });  
    $.ajax({
                    url: uri1,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":1
                    }),
                    success: function (data) {
                        $('#rt').empty().append("<option value='0'>Select</option>")
                     for(var i=0;i<data.length;i++)
                      {
                        $('#rt').append("<option value="+data[i].RID+">"+data[i].RTNAME+"</option>")
                      }  
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });
                $.ajax({
                    url: uri2,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":1
                    }),
                    success: function (data) {
                        $('#bt').empty().append("<option value='0'>Select</option>")
                     for(var i=0;i<data.length;i++)
                      {
                        $('#bt').append("<option value="+data[i].BID+">"+data[i].BTNAME+"</option>")
                      }  
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });
                var obj=[];
      $('#btnsave').click(function(){
       
            if(IID==0)
            {
              if ($("#newModalForm").valid()) {
                obj=[];
              for(var i=0;i<$('#file')[0].files.length;i++){
            var fd = new FormData();
        var files = $('#file')[0].files[i];
        fd.append('file',files);  
        obj.push({"PATH":"Images/"+$('#file')[0].files[i].name });    
         $.ajax({
            url: 'Fileupload.php',
            type: 'post',
            data:fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                 
                }else{
                    alert('file not uploaded');
                }
            },
        });
        }
                $.ajax({
                    url: uri,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":3,
                        "RNUMBER":$('#cn').val(),
                        "RID":$('#rt').val(),
                        "BID":$('#bt').val(),
                        "CATEGORY":$('#ct').val(),
                        "PRICE":$('#mn').val(),
                        "DESCRIPTION":$('#add').val(),
                        "RI":obj
                    }),
                    success: function (data) {
                      $('#divErrorText').text('Data Saved Successfully.');
                  $('#divError').show('fade');
            setTimeout(function () {
              $('#divError').hide('fade');
              location.reload();
            }, 2000);
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });
              }
            }
            else if(IID>0)
            {
              $("[name='file1']").removeAttr('required');
               if ($("#newModalForm").valid()) {
               if($('#file')[0].files.length==0)
               {
                $.ajax({
            url: uri,
            method: 'POST',
            datatype: 'json',
            data:JSON.stringify({
                        "mark":"7",
                        "ID": IID,
                        "RNUMBER":$('#cn').val(),
                        "RID":$('#rt').val(),
                        "BID":$('#bt').val(),
                        "CATEGORY":$('#ct').val(),
                        "PRICE":$('#mn').val(),
                        "DESCRIPTION":$('#add').val(),
                    }),
                 cache: false,
                 success: function (Data) {
                  $('#divErrorText').text('Data Updated Successfully.');
                  $('#divError').show('fade');
            setTimeout(function () {
              $('#divError').hide('fade');
              location.reload();
            }, 2000);

                 }

        });
               }
               else
               {
                obj=[];
              for(var i=0;i<$('#file')[0].files.length;i++){
            var fd = new FormData();
        var files = $('#file')[0].files[i];
        fd.append('file',files);  
        obj.push({"PATH":"Images/"+$('#file')[0].files[i].name });    
         $.ajax({
            url: 'Fileupload.php',
            type: 'post',
            data:fd,
            contentType: false,
            processData: false,
            success: function(response){
                if(response != 0){
                 
                }else{
                    alert('file not uploaded');
                }
            },
        });
               }
               $.ajax({
                    url: uri,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":4,
                        "ID": IID,
                        "RNUMBER":$('#cn').val(),
                        "RID":$('#rt').val(),
                        "BID":$('#bt').val(),
                        "CATEGORY":$('#ct').val(),
                        "PRICE":$('#mn').val(),
                        "DESCRIPTION":$('#add').val(),
                        "RI":obj
                    }),
                    success: function (data) {
                      $('#divErrorText').text('Data Updated Successfully.');
                  $('#divError').show('fade');
            setTimeout(function () {
              $('#divError').hide('fade');
              location.reload();
            }, 2000);
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });

               }
           
            }
          }
        });
       
        $.ajax({
                    url: uri,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":1
                    }),
                    success: function (data) {
                        if(data!="result not found.")
                      {
                        table=$('#tb').DataTable({
                    data:data,
                    columns: [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        { "data": "ID" },
                        { "data": "RNUMBER" },
                        { "data": "RTNAME" },
                        { "data": "BTNAME" },
                        { "data": "CATEGORY" },
                        { "data": "PRICE" },
                        { "data": "DESCRIPTION" },
                        { "data": "STATUS" },
                        {  
                            "data": null,
                            "defaultContent": "<a  class='e' href='#' ><span class='glyphicon glyphicon-edit edit'></span></a> | <a  href='#' class='d' ><span class='glyphicon glyphicon-remove-circle del'></span></a>"
                        }
                    ],
                    "order": [[1, 'desc']]
                });
                      }

                       
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });
        $('#tb tbody').on('click', '.e', function () {
            var currentRow=$(this).closest("tr");
         var ID=currentRow.find("td:eq(1)").text();
         IID=ID;
         $.ajax({
                    url: uri,
                    method: 'POST',
                    datatype: 'json',
                    data:JSON.stringify({
                        "mark":2,
                        "ID" :ID
                    }),
                    success: function (data) {
                      $('#cn').val(data.RNUMBER);
                      $('#rt').val(data.RID);
                      $('#bt').val(data.BID);
                      $('#ct').val(data.CATEGORY);
                      $('#mn').val(data.PRICE);
                      $('#add').val(data.DESCRIPTION);
                      $('#file').text(data.RNUMBER);
                    },
                    error: function (jqXHR) {
                      alert(jqXHR.responseText);
                    }
                });
                var m= $('#myModal');
                m.modal('show');
        });
        $('#tb tbody').on('click', '.d', function () {
            var currentRow=$(this).closest("tr");
         var ID=currentRow.find("td:eq(1)").text();
         if(confirm("Do you want to delete it ?"))  
        {
          $.post(uri,JSON.stringify({
          "mark":5,
          "ID":ID
         }),function(data,status){
          location.reload();
         });
        }
        });
        $('#tb tbody').on('click', 'td.details-control', function () {

var tr = $(this).closest('tr');
var row = table.row(tr);

if (row.child.isShown()) {
   
    row.child.hide();
    tr.removeClass('shown');
}
else {
   
    row.child(format(row.data())).show();
    tr.addClass('shown');
}
});
              });
   
    var table = null;
    function format(d) {
        var tr = $(document.createElement("table"));
      var tr1=  tr.append("<tr></tr>")
        $.ajax({
            url: uri,
            method: 'POST',
            datatype: 'json',
            data:JSON.stringify({
                        "mark":6,
                        "ID": d.ID
                    }),
                 cache: false,
                 success: function (Data) {
                     $.each(Data, function (i, j) {
                         tr1.append("<td><img height='100'  width='100' src=" + j.PATH + "></td><td>&nbsp</td>");
                     });

                 }

        });
        return tr;
    }
</script>

<?php include 'Footer.php'; ?>