duanchuang1935 2018-07-30 22:11
浏览 73

尝试从AJAX调用返回数据时出现意外结果

I have the following script that sends an image, directory name, and possible alternative filename to an action url in a php file.

    $(document).ready(function() {
    $(".layout-save").click(function(e) {
        e.preventDefault();     
        var form = $(".image_define");
        var params = form.serializeArray();
        var formData = new FormData();
        formData.append('default_image', $('#default_image')[0].files[0]);
        $(params).each(function (index, element) {
            formData.append(element.name, element.value);
        });
        $.ajax({
            url: form.attr('action'),
            method: "post",
            data: formData,
            contentType: false,
            processData: false
            })
        .done(function(data) {
            var obj = JSON.parse(data);
            $('.tooltip-imageHandler-<?php echo $products_filter; ?>').tooltipster('close');
            var elem = $('.image-<?php echo $products_filter; ?>');
            elem.fadeOut('slow', function() {
                elem.html(obj.asHtml).fadeIn('slow', function() {
                    elem.delay(1200).fadeOut('slow', function() {
                        elem.html(obj.products_image).fadeIn('slow');
                    });
                });
            });
        })
        .fail(function(){
            alert('Ajax Submit for New Image Save Failed ...'); 
        });
    });
});

What I was trying to achieve was to send back a success message that I can display in the class image-xxx, where xxx is a product id, thus giving unique class names when there are multiple instances on the page.

File upload is working ok, and the tooltip closes correctly. I added the following line of code inside my "save" case, just after the final sql query that updates the database:

echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));

I was expecting to be able to use this to display the success message, and then update the div with the newly uploaded image.

However, when testing I am getting the following in the console "VM3150:2 Uncaught SyntaxError: Unexpected token < in JSON at position 162" and if I console.log(data) I am seeing the parsed php for the page rather than just "products_image" and "asHtml".

Can anyone offer some pointers as to what I've done wrong here?

Note: Whilst I know I could take the data that was submitted via the form, I really need the information after it has been processed because it makes decisions on the file path and image naming etc depending on if it is a first, or additional image before it writes to the database.

Added the php from the file where if ($action == 'save') is located. The json_encode is approx 12 lines before the end, right after the original (pre ajax modification)success message would be displayed.

if ($action == 'save') {
// -----
// Log the input values on entry, if debug is enabled.
//
$ih_admin->debugLog(
    'ih_manager/save, on entry.' . PHP_EOL . 
    '$_GET:' . PHP_EOL . var_export($_GET, true) . PHP_EOL . 
    '$_POST:' . PHP_EOL . var_export($_POST, true) . PHP_EOL . 
    '$_FILES:' . PHP_EOL . var_export($_FILES, true)
);

// -----
// Set some processing flags, based on the type of upload being performed.
//
$editing = (isset($_GET['imgEdit']) && $_GET['imgEdit'] == '1');
$new_image = (isset($_GET['newImg']) && $_GET['newImg'] == '1');
$main_image = (!isset($_GET['imgSuffix']) || $_GET['imgSuffix'] == '');
$keep_name = (isset($_POST['imgNaming']) && $_POST['imgNaming'] == 'keep_name');

$data = array();
$data_ok = true;

// -----
// Determine the extension required for any uploaded images.
//
// 1) A new main-image (and any medium/large) use the extension from the (required) default image suppied.
// 2) A new additional image's files use the extension from the pre-existing main-image.
// 3) Editing an image uses the pre-existing file extension.
//
if ($new_image) {
    if ($_FILES['default_image']['name'] == '') {
        $messageStack->add(TEXT_MSG_NO_DEFAULT, 'error');
        $data_ok = false;
    } else {
        $data['imgExtension'] = '.' . pathinfo($_FILES['default_image']['name'], PATHINFO_EXTENSION);
    }
} else {
    $data['imgExtension'] = $_GET['imgExtension'];
}

// -----
// If the file-upload is in support of a new main image or the main image is being edited ...
//
if ($new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
    // New Image Name and Base Dir
    if (isset($_POST['imgBase']) && $_POST['imgBase'] != '') {
        $data['imgBase'] = $_POST['imgBase'];
    } else {
        // Extract the name from the default file
        if ($_FILES['default_image']['name'] != '') {
            $data['imgBase'] = pathinfo($_FILES['default_image']['name'], PATHINFO_FILENAME);
        } else {
            $messageStack->add(TEXT_MSG_AUTO_BASE_ERROR, 'error');
            $data_ok = false;
        }
    }

    // catch nasty characters
    if (strpos($data['imgBase'], '+') !== false) {
        $data['imgBase'] = str_replace('+', '-', $data['imgBase']);
        $messageStack->add(TEXT_MSG_AUTO_REPLACE . $data['imgBase'], 'warning');
    }

    if (isset($_POST['imgNewBaseDir']) && $_POST['imgNewBaseDir'] != '') {
        $data['imgBaseDir'] = $_POST['imgNewBaseDir'];
    } elseif (isset($_POST['imgBaseDir'])) {
        $data['imgBaseDir'] = $_POST['imgBaseDir'];
    } else {
        $data['imgBaseDir'] = $_GET['imgBaseDir'];
    }

    $data['imgSuffix'] = '';

// -----
// Otherwise, if we're editing an additional product image ...
//
} elseif ($editing) {
    $data['imgBaseDir'] = $_GET['imgBaseDir'];
    $data['imgBase'] = $_GET['imgBase'];
    $data['imgSuffix'] = $_GET['imgSuffix'];
// -----
// Otherwise, we're adding an additional product image ...
//
} else {
    // An additional image is being added
    $data['imgBaseDir'] = $_GET['imgBaseDir'];
    $data['imgBase'] = $_GET['imgBase'];

    // Image Suffix (if set)
    if ($_POST['imgSuffix'] != '') {
        $data['imgSuffix'] = '_' . $_POST['imgSuffix'];
    } else {
        // -----
        // Get additional images' list; the class function takes care of sorting the files
        //
        $matching_files = array();
        $ih_admin->findAdditionalImages($matching_files, $data['imgBaseDir'], $data['imgExtension'], $data['imgBase']);

        // -----
        // If no additional images exist, use the _01 suffix.
        //
        $file_count = count($matching_files);
        if ($file_count == 1) {
            $data['imgSuffix'] = '_01';
        } else {
            // -----
            // Otherwise, find the first unused suffix in the range _01 to _99.  Note that the first
            // (ignored) element of the find-array "should be" the main image's name!
            //
            for ($suffix = 1, $found = false; $suffix < 99; $suffix++) {
                $suffix_string = sprintf('_%02u', $suffix);
                if (!in_array($data['imgBase'] . $suffix_string . $data['imgExtension'], $matching_files)) {
                    $found = true;
                    $data['imgSuffix'] = $suffix_string;
                    break;
                }
            }
            if (!$found) {
                $messageStack->add('Could not find an unused additional-image suffix in the range _01 to _99.', 'error');
                $data_ok = false;
            }
        }
    }
}

// determine the filenames 
if ($data_ok) {
    // add slash to base dir
    if ($data['imgBaseDir'] != '') {
        if (substr($data['imgBaseDir'], -1) != '/' && substr($data['imgBaseDir'], -1) != '\\') {
            $data['imgBaseDir'] .= '/';
        }
    }
    $data['defaultFileName'] = $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . $data['imgExtension'];

    // Check if the file already exists
    if ($editing && file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . $data['defaultFileName'])) {
        $messageStack->add(TEXT_MSG_FILE_EXISTS, 'error' );
        $data_ok = false;
    }
}

// -----
// If no previous errors and we're either (a) creating a new main-image or (b) editing the main-image and a new name
// is requested ...
//
if ($data_ok && $new_image || ($editing && $main_image && !$keep_name && $_FILES['default_image']['name'] != '')) {
    // -----
    // ... first, check to see that the image's name is going to fit into the database field.
    //
    if (strlen($data['defaultFileName']) > zen_field_length(TABLE_PRODUCTS, 'products_image')) {
        $messageStack->add(sprintf(TEXT_MSG_NAME_TOO_LONG_ERROR, $data['defaultFileName'], zen_field_length(TABLE_PRODUCTS, 'products_image')), 'error');
        $data_ok = false;
    } else {
        // update the database
        $sql = 
            "UPDATE " . TABLE_PRODUCTS . " 
                SET products_image = '" . $data['defaultFileName'] . "' 
              WHERE products_id = " . (int)$products_filter . "
              LIMIT 1";
        if (!$db->Execute($sql)) {
            $messageStack->add(TEXT_MSG_INVALID_SQL, "error");
            $data_ok = false;
        }
    }
}

if ($data_ok) {
    // check for destination directory and create, if they don't exist!
    // Then move uploaded file to its new destination

    // default image
    if ($_FILES['default_image']['name'] != '') {
        io_makeFileDir(DIR_FS_CATALOG_IMAGES . $data['defaultFileName']);
        $source_name = $_FILES['default_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add(TEXT_MSG_NOUPLOAD_DEFAULT, "error" );
            $data_ok = false;
        }
    } elseif ($_FILES['default_image']['name'] == '' && !$editing) {
        // Nigel Hack for special idiots  
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['defaultFileName']);
        $source_name = $_FILES['default_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['defaultFileName'];
        if (!move_uploaded_file($source_name, $destination_name) ) {
            $messageStack->add( 'you must select a default image', "error" );
            $data_ok = false;
            $_FILES['medium_image']['name'] = $_FILES['large_image']['name'] = '';
        }
    }  // End special idiots hack
    // medium image
    if ($_FILES['medium_image']['name'] != '') {
        $data['mediumImgExtension'] = substr( $_FILES['medium_image']['name'], strrpos($_FILES['medium_image']['name'], '.'));
        $data['mediumFileName'] ='medium/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_MEDIUM . $data['mediumImgExtension'];
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['mediumFileName']);
        $source_name = $_FILES['medium_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['mediumFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add( TEXT_MSG_NOUPLOAD_MEDIUM, "error" );
            $data_ok = false;
        }
    }
    // large image
    if ($_FILES['large_image']['name'] != '') {
        $data['largeImgExtension'] = substr( $_FILES['large_image']['name'], strrpos($_FILES['large_image']['name'], '.'));
        $data['largeFileName'] = 'large/' . $data['imgBaseDir'] . $data['imgBase'] . $data['imgSuffix'] . IMAGE_SUFFIX_LARGE . $data['largeImgExtension'];
        io_makeFileDir(DIR_FS_CATALOG_IMAGES.$data['largeFileName']);
        $source_name = $_FILES['large_image']['tmp_name'];
        $destination_name = DIR_FS_CATALOG_IMAGES . $data['largeFileName'];
        if (!move_uploaded_file($source_name, $destination_name)) {
            $messageStack->add( TEXT_MSG_NOUPLOAD_LARGE, "error" );
            $data_ok = false;
        }
    }  
}

if (!$data_ok) {
    if ($editing) {
        $action = "layout_edit";
    } else {
        $action = "layout_new";
    }
} else {
    // Data has been saved
    // show the new image information
    $messageStack->add(TEXT_MSG_IMAGE_SAVED, 'success');
    echo json_encode(array("products_image"=>$data['defaultFileName'], "asHtml" => '<div class="alert alert-info update-notice update-'.$products_filter.'"><strong>Product image updated</strong></div>'));
    // we might need to clear the cache if filenames are kept
    if ($editing) {
        $error = bmz_clear_cache();
        if (!$error) {
            $messageStack->add(IH_CACHE_CLEARED, 'success');
        }
    }
    $_GET['imgName'] = $data['imgBase'] . $data['imgSuffix'];
    $action = "layout_info";
}

}

One point I would make is that when looking at console log in dev tools, it is highlighting the first character of the file the form resides in, which IS NOT the file that the json_encode is in. Code structure has the form in file A, which is actioned in file B. File B contains the json_encode response I want to send, but the error is showing the html content of file A, as well as the son data. A snippet of it is here.

{"products_image":"Teal-Shirt-min_01.jpg","asHtml":"<div class=\"alert alert-info update-notice update-310\"><strong>Product image updated<\/strong><\/div>"}
<div class="container-fluid">
    <div id="ih-head">
        <h1>Image Handler<sup>5</sup></h1>
    </div>


    <div id="defaultContent">
        <div class="row">
            <div class="col-md-6 col-sm-12 no-padding">
                <div class="ih-heading pull-left">Product</div>
                <div class="ih-info pull-left">&nbsp;#310 &mdash; Teal T-Shrt</div>
            </div>
            <div class="col-md-6 col-sm-12 no-padding">
                <div class="ih-heading pull-left">Image Directory</div>
                <div class="ih-info pull-left">&nbsp;images/</div>  
            </div>
        </div>
        <hr>
  • 写回答

1条回答 默认 最新

  • dtb81443 2018-07-31 12:52
    关注

    Given you are getting back the contents of the current page, my guess is that your ajax request is NOT setup right.

    "url" should be set to the url of the script that you want to process the data and return the response. If "url" is not set it defaults to the "CURRENT URL".

    So I am thinking you want something like below for your URL...

    .ajax({
          url: "/myapp/myJsonResponseScript.php",
       ....
    

    Pass your action value in a data option for the ajax call.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题