0

I have created a php form that accepts few values through textbox and 1 HTML input type FILE but my textbox data is stored to the database whereas my Filename is not. Am uploading image to server directory and storing its name to database.

Index.html

<!DOCTYPE HTML>
<html>
    <head>
        <script language="javascript" type="text/javascript" src="js/TabActions.js"></script>
    </head>
    <body>
 <form>             
 <table width="100%" border="0" align="center" >
  <input type="hidden" name="ExCategory" id="ExCategory" value="Meal">
  <tr>
    <td>Description:<br><textarea rows="4" cols="30" name= "Descr" maxlength="100"></textarea></td>
  </tr></table>
   <table width="100%" border="0" align="center" >
 <tr>
    <td> Date:</td>
    <td><input type="DATE"required name="ClaimDate" id="ClaimDate"/></td>
    <td colspan = 3><input type=file name="ClaimReceipt" id="ClaimReceipt" accept="image/jpeg,image/jpg,image/png/image/gif"></td>
  </tr>
  <tr>
   <td>Amount:</td>
    <td> <input type="number" size="5" name="ClaimAmt" id="ClaimAmt" required Placeholder="<?php echo "In ".$Currency; ?>" ></td>
</tr>
  <tr>
    <td colspan="6"  >
    <table border="0" Width="30%" height=40px >
        <tr>
            <td><input type="Button" value="Add" onclick="addFunction(ExCategory.value,Descr.value,ClaimDate.value,ClaimAmt.value,ClaimReceipt.value)"></td>
            </tr></table></td>
        </tr>        
</table>
            </div>
        </form>
    </body>
</html>

Action.js

function addFunction(ExCategory,Descr,ClaimDate,ClaimAmt,ClaimReceipt)
{
    var ajaxRequest;  // The variable that makes Ajax possible! 
    try
    {
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer Browsers
        try
        {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e)
            {
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function()
    {
        if(ajaxRequest.readyState==4 && ajaxRequest.status==200)
        {
            document.getElementById('Res').innerHTML = ajaxRequest.responseText;
        }
    }
    ajaxRequest.open("POST","insert.php", true);
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxRequest.send("Add=102&ExCategory="+ExCategory+"&Descr="+Descr+"&ClaimDate="+ClaimDate+"&ClaimAmt="+ClaimAmt+"&ClaimReceipt="+ClaimReceipt);
}

insert.php

<?php
session_start();
//error_reporting(E_ERROR);
$User = 'User'; 
if (isset($_POST['ClaimDate'])) 
{
    $ClaimDate = $_POST['ClaimDate'];
}
else
{
    $ClaimDate = $_POST['ClaimTo'];
}
    $ExCategory = $_POST['ExCategory'];
    if(isset($_POST['Descr']))
    {
        $ClaimClass = stripslashes($_POST['Descr']);
    }
    else
    {
        $ClaimClass = 'No description';
    }

    If(isset($_POST['ClaimFrom']) && isset($_POST['ClaimFrom']))
    {
        $ClaimFrom = $_POST['ClaimFrom'];   
        $ClaimTo = $_POST['ClaimTo'];
    }
    else
    {
        $ClaimFrom = 'Null';                 
        $ClaimTo = 'Null';
    }                   
  $ClaimAmt = $_POST['ClaimAmt'];         
if (isset($_POST['Add'])) 
{
        if (isset($_FILES['ClaimReceipt']))
        {
            if(isset($_SESSION['counter']))
            {
                $Counter = $_SESSION['counter'];
            }
            else
            {
                $Counter = 0;
            }
            $Receipt = $_FILES['ClaimReceipt'];
            $file_type= $Receipt['type'];           
            $file_path=$_FILES["ClaimReceipt"]["tmp_name"];
            $file_name = $UserID."(".$Counter.").jpeg";         
            if($file_type!= '' && ($file_type="image/jpeg" || $file_type="image/png") && $file_size < 50000)
            {
                move_uploaded_file($file_path,"uploads/".$file_name);
                $ClaimReceipt = $file_name;
                $warning = '';
                $Counter++;
                $_SESSION['counter'] = $Counter;
            }
            else
            {
                $_SESSION['counter'] = $Counter;
                $warning = "Please check format '.jpeg or .png' for attachments and its size < 500 kb";
            }
        }
        Else
        {   
            $_SESSION['counter'] = $Counter;
            $ClaimReceipt = '';                 
        }
        include('dbcon.php');
        $stmt = $dbh->prepare("CALL sp_AddExpensesEntry(?,?,?,?,?,?)"); 
        $stmt ->execute(array($User,$ExCategory,$ClaimDate,$ClaimAmt,$ClaimClass,$ClaimReceipt));
        $dbh->connection = null;
}
?>

Database Table

CREATE TABLE `MyExp` (
  `UserName` varchar(45) NOT NULL,
  `ExCategory` varchar(15) NOT NULL,
  `ClaimDate` varchar(10) NOT NULL,
  `ClaimAmt` int(11) NOT NULL,
  `ClaimDesc` varchar(100) DEFAULT NULL,
  `ClaimReceipt` varchar(20) DEFAULT NULL,
  `ClaimRowid` int(7) NOT NULL AUTO_INCREMENT,
  UNIQUE KEY `ClaimRowid_UNIQUE` (`ClaimRowid`)
)

sp_AddExpensesEntry Stored procedure

CREATE DEFINER=`root`@`localhost` PROCEDURE `sp_AddExpensesEntry`(
    In UserName Varchar(45),
    In Category varchar(15),
    In Claimdate varchar(10),
    In Amt int,
    In Descr varchar(100),
    In ImgURL VARCHAR(20)
)
proc_main:BEGIN

    Declare RowId int;
    If Exists(Select ClaimRowid from MyExp) then
        Set RowId = (Select ClaimRowid from MyExp Order by ClaimRowid desc limit 1) + 1;
    Else
        Set RowId = 1;
    End If;
    INSERT INTO `MyExp`
    VALUES
    (
    UserName,
    category,
    Claimdate,
    Amt,
    Descr,
    ImgURL,
    RowId
    );
    commit;
END

Please help me with this. The File storage mechanism worked well when data was stored into DB without AJAX and but to avoid page reloads I have tried to do this. Thanks in advance.

  • 1
    Just skimmed through your post. You may be giving a little too much code and not enough detailed description of what you tried and what you think is or isn't working. – kemicofa ghost Feb 27 '15 at 15:48
  • I tried ajaxRequest.open("POST","insert.php", true) in js code but still same issue. – Paritosh S. Feb 27 '15 at 15:50
  • @Grimbode: Please read the first line..I am trying to store the Image to Server directory "uploads" and image's name to database into ImgUrl column. But its not working when I use AJAx. – Paritosh S. Feb 27 '15 at 15:52

1 Answers1

1

To post a file you need to use multipart/form-data not application/x-www-form-urlencoded. You're not actually passing the file with the ajax request, that's why it's not storing anywhere.

Mateusz Majewski
  • 280
  • 1
  • 10