0

I have an HTML form in which I have to upload 3 files. I have to call a create.js script after form submission which uses getElementById to format the input in desired way. Then it uses a xmlHTTPRequest to call create.php which inserts the form data into mysql database, and in the mean time fetches some data that it sends back to create.js using json_encode.
So I don't use the form action attribute but instead use the onClick attribute on my Submit button to call create.js.
But I have to upload my 3 files also on clicking Submit. I tried using $_FILE['file1']['name'] and other $_FILE[][] variables, where I use <input type="file" name="file1" id="file1"> to uplaod my first file but it gave the following error: Undefined index: file1 in C:\xampp\htdocs\mywebsite\sites\all\themes\danland\create.php on line 77

So how can I incorporate my code for storing uploaded files on my server in the same php that returns xmlhttp.responseText to my .js file ?

I also tried putting my code of uploading in upload.php and called it using <form action="the/correct/path/upload.php"> besides using onClick = "my_create.js_function()" in my submit button but it did not work

Note that I have read html upload using ajax and php and know that I cannot upload my file using xmlhttprequest, but I am not trying to do that. I want my xmlhttprequest to fetch data after submit is clicked and my submit button to also store my files.

My HTML form is:

<script src="http://localhost/mywebsite/sites/all/themes/danland/src/create.js">
</script>       
<script type="text/javascript" src="http://localhost/mywebsite/sites/all/themes/danland/src/datepickr.js"></script>

<script>
window.onload = create_new_project_getoptions(); 
</script>

<div class="searchinterfacecontainer">
<p id="my_first_para"></p>
<p id="this_is_my_new_para"></p>
<h2>Enter Details</h2>

<form id="create_projectform1" name="create_projectform1" method="POST" enctype="multipart/form-data" action="http://localhost/mywebsite/sites/all/themes/danland/create_new_project_upload.php">

<input type="text" name="project_id" id="project_id" required/>

<input type="text" name="project_name" id="project_name" required/>

<input id="project_start_date" onClick="new datepickr('project_start_date')" required/>

<select id="project_geography" name="project_geography">
<option value="">Select Country </option>
</select><br/>

<input type="file" name="file1" id="file1">

<input type="file" name="file2" id="file2">

<input type="file" name="file3" id="file3">

    <div class="searchinterfacebuttons"><input type="submit" class="searchinterfaceform1go" value="Search" onClick="create_new_project()"/>     <button class="searchinterfaceform1go" type="reset" value="Reset"> Reset  </button></div>
</form>
</div>

My create.js:

function create_new_project( )
{
    alert("entered");
    var project_id = document.getElementById("project_id").value;
    var project_name = document.getElementById("project_name").value;
    var project_start_date = document.getElementById("project_start_date").value;
// some more getElementByID
    var error_para = document.getElementById("my_first_para");
    var my_error = "";
    error_para.innerHTML =  my_error;

    // some string manipulation with the above defined variables

    project_start_date = date_fixer(project_start_date);
    project_completion_date = date_fixer(project_completion_date);

    if (window.XMLHttpRequest)
    {   
        xmlhttp = new XMLHttpRequest(); 
    }
    else
    { 
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    }

    var params = "project_id=" + project_id + "&project_name=" + project_name ; // + some more parameters

    var url = "http://localhost/mywebsite/sites/all/themes/danland/create.php";
    xmlhttp.open("POST",url,true);

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");

    xmlhttp.onreadystatechange=function()
    {        
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            var val = xmlhttp.responseText;
            //alert(val);
                    var jsonData = JSON.parse(val);
                    // some manipulation with json data
            var answer = document.getElementById("this_is_my_new_para");
            answer.innerHTML = jsonData;
        }
    }
    xmlhttp.send(params);
}

function date_fixer(my_date)
{
    // code here that works fine
}

My create.php:

<?php

    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'this_user');
    define('DB_PASSWORD', 'this_password');
    define('DB_DATABASE', 'mywebsite');

    $project_id = $_POST["project_id"];
    $project_name = $_POST["project_name"];
    $project_start_date = $_POST["project_start_date"];
        // some more $_POST[]

    $date_status1 = date_fixer($project_start_date);
    $date_status2 = date_fixer($project_completion_date);
    //echo "date status 1 is $date_status1 and date_status2 is $date_status2";
    if ( $date_status1 == -1 || $date_status2 == -1 )  // not a valid date
    {
        echo "The date was not in correct format. Please use the date picker";
    }
    else
    {
        try 
        {
            $db = new PDO('mysql:host=' .DB_SERVER . ';dbname=' . DB_DATABASE . ';charset=utf8', DB_USERNAME,  DB_PASSWORD);
            $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $query_geography = "INSERT into " . DB_TABLE . "( projectID, project_name, start_date) values ( (:pid), (:pname), (:sdate))";
            $parameters1 = array(':pid'=>$project_id, ':pname'=>$project_name, ':sdate'=>$project_start_date);
            $statement1 = $db->prepare($query_geography);
            $statement1->execute($parameters1);
        }
        catch(Exception $e) 
        {
            echo 'Exception -> ';
            var_dump($e->getMessage());
        }
    }

    function date_fixer($my_date)
    {
        // valid function that works fine
    }

    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file1"]["name"]);
    $extension = end($temp);
    print_r($temp);
    print_r($extension);


    if ( ( ($_FILES["file1"]["type"] == "image/gif") || ($_FILES["file1"]["type"] == "image/jpeg") || ($_FILES["file1"]["type"] == "image/jpg") || ($_FILES["file1"]["type"] == "image/pjpeg") || ($_FILES["file1"]["type"] == "image/x-png") || ($_FILES["file1"]["type"] == "image/png") ) && ($_FILES["file1"]["size"] < 20000) && in_array($extension, $allowedExts) ) 
    {
        if ($_FILES["file1"]["error"] > 0) 
        {
            echo "Return Code: " . $_FILES["file1"]["error"] . "<br>";
        } 
        else 
        {
            echo "Upload: " . $_FILES["file1"]["name"] . "<br>";
            echo "Type: " . $_FILES["file1"]["type"] . "<br>";
            echo "Size: " . ($_FILES["file1"]["size"] / 1024) . " kB<br>";
            echo "Temp file: " . $_FILES["file1"]["tmp_name"] . "<br>";
            if (file_exists("upload/" . $_FILES["file1"]["name"])) 
            {
                echo $_FILES["file1"]["name"] . " already exists. ";
            } 
            else 
            {
                move_uploaded_file($_FILES["file1"]["tmp_name"], "upload/" . $_FILES["project_file1"]["name"]);
                echo "Stored in: " . "upload/" . $_FILES["project_file1"]["name"];
            }
        }
    } 
    else 
    {
        echo "Invalid file";
    }

?>
4
  • 2
    Please! do not use xmlHTTPRequest anymore. Use jQuery ajax or some other js frameworks who support you there. Commented May 27, 2014 at 11:17
  • 1
    Provide some REAL code of what you have. I don't think anybody is with you here. Commented May 27, 2014 at 11:17
  • In your create.php file do a var_dump($_FILES); that should highlight the structure of the $_FILES array for you, then you can identify the structure, and how to select each file. Commented May 27, 2014 at 11:46
  • @diggersworld I tried var_dump($_FILES); but it gave "array(0){}" Commented May 27, 2014 at 12:10

1 Answer 1

0

to get values from $_FILE you have to set form enctype to multipart/form-data. if you want to read the value of file field then in jQuery simply write $('#id_filefield').val();

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.