HTML upload file using AJAX and PHP script - help?

為{幸葍}努か 提交于 2019-12-24 06:39:11

问题


I am trying to perform a task that may not be possible. I haven't found the same scenario yet around the internet.

I have four fields that, on a click, will call a Javascript function that does an AJAX call for data from a PHP file.

The fields will ultimately be filling a row in a database and the PHP will query the new set of data, and the user will see it. Part of the data is an image that the user can click on and expand.

The AJAX call works, the expanding image works, but adding this image via an upload does not, thus breaking the whole thing.

Here is a snippet of the HTML form:

Entry: <input type='text' id='entry' />
Stop: <input type='text' id='stop' />
Final: <input type='text' id='final' />
Chart: <input type='file' id='chart' value='Get Chart'/>
<input type='button' onclick='addResult()' value='Add' />

The addResult() processes things like this:

var entry = document.getElementById('entry').value;
var stop = document.getElementById('stop').value;
var final = document.getElementById('final').value;
var chart = document.getElementById('chart').value;
var queryString = "?entry=" + entry + "&stop=" + stop + "&final=" + final + "&chart=" + chart + "&loggedIn=true";
ajaxRequest.open("GET", "addResult.php" + queryString, true);

Nothing special, just taking the data and sending it to addResult.php for a response. Here is the process for handling the 'chart' upload data in addResult.php:

$chart = $_GET['chart'];
$chart_loc = "../img/".basename($_FILES[$chart]['name']);
move_uploaded_file($_FILES[$chart]['tmp_name'], $chart_loc);
if(($entry != "") && ($stop != "") && ($final != "") && ($chart_loc != "")){
           mysql_query("INSERT INTO resultsMod VALUES (now(),'".$entry."','".$stop."','".$final."','".$chart_loc."')") or die(mysql_error());
        }

When I click the 'Add' button, it does nothing, and before I added the upload file field, everything was working fine. So I must be doing something wrong with handling the file.

I've never worked with upload data before, so I don't know if sending that data like that is even allowed (without a form submission and just passing the file data through Javascript to a php file). I also may be doing something incorrect with the move_uploaded_file function.

The goal of course is to have a real time update of the new data from the form, including the uploaded image. (I know my code is simple and I will add to it once this is functional) Any help is appreciated, thanks!


回答1:


You are trying to upload a file using AJAX, which is not posible. The best approach would be to manage the file upload separately, maybe through swf-upload




回答2:


You cannot upload file via AJAX - only solution is iframe with form .




回答3:


Uploading file through AJAX is not possible. It is not supported by XMLHttpRequest. you can either use flash, or using iframe as target.




回答4:


Does your form have enctype="multipart/form-data"? File uploads must have attribute present in the <form> tag for the upload to work.

As well, you're not checking if the file upload succeeded on the server. At bare minimum you should have

if ($_FILES[$chart]['error'] === UPLOAD_ERR_OK) {
      ... upload worked, handle it...
}



回答5:


Do yourself a favor and use Uploadify (Requires jQuery). It will save you hours and hours of trying to figure out how to get your uploads to work in an AJAX-ish fashion.




回答6:


Something to check, is your form enctype="multipart/form-data" set? This would cause the image not uploading. Just an idea.

Also, is jQuery an option? If so, you could do something like this:

$.ajaxFileUpload({
        url:'addResult.php?type=' + queryString,
        secureuri:false,
        fileElementId: INPUTIDHERE,
        dataType: 'json',
        success: function (data, status)
        {
            // done - run some code
        },
        send: function(data)
        {
        },
        error: function (data, status, e)
        {
            console.debug(data);
        }
    }
)

Will need this library: http://jsfiddle.net/SYZqL/




回答7:


you can upload the files via ajax to php script. The following should work for that.

var file_data = $("#file_field_id").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data)
form_data.append("user_id", 123) // adding additional form field values
$.ajax({
                url: "server.php",
                dataType: 'script',
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,                         // Setting the data attribute of ajax with file_data
                type: 'post',
                success: function(data, textStatus, jqXHR){
                    if(data)
                     {
                        // some process


                },
                error:function(jqXHR, textStatus, errorThrown){
                alert("errorThrown"); 


        }
       }); 


来源:https://stackoverflow.com/questions/5043120/html-upload-file-using-ajax-and-php-script-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!