简体   繁体   中英

PHP echo jQuery AJAX request

This is my jQuery request to upload an image file

$('#upload-image').change(function(e){
    var file = e.target.files[0];
    var imageType = /image.*/;
    if (!file.type.match(imageType))
        return;
    console.log(file);
    var form_data = new FormData();
    form_data.append('file', file);
    console.log(form_data);
    $.ajax({
        url: 'http://localhost/upload.php',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });
});

This is upload.php on local webserver

<?php
    header('Access-Control-Allow-Origin: *');
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        $target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
        echo $target_path;
    }
?>

When I upload the image and send request. It returns and logs for me complete code lines of upload.php , not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php . It truly does not handle anything server-side. What did I do wrong?

You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.

Based on your platform, you may try:

First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content

<?php
phpinfo();

This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM