AJAX:如何从PHP返回错误

时间:2016-02-18 16:16:03

标签: php jquery ajax

我有一个表单供用户上传个人资料图片并在不刷新的情况下显示他们的实时验证。我正在尝试使用AJAX但它似乎没有到达PHP文件。即使我在提交表单后使用的是preventDefault,它也会重新加载页面并打开第一个没有表单的选项卡。

FORM

$avatar_form = '<div class="bhoechie-tab-content" id="uploadphoto">';
$avatar_form .= '<center>';
$avatar_form .= '<form id="avatar_form" method="post" enctype="multipart/form-data">';
$avatar_form .= '<h1>Change avatar</h1>';
$avatar_form .= '<input type="file" name="avatar" required>';
$avatar_form .= '<p><input type="submit" value="Upload"></p>';
$avatar_form .= '<p id="status"></p>';
$avatar_form .= '</form>';
$avatar_form .= '</center></div>';

PHP代码段

if (isset($_FILES["avatar"]["name"]) && $_FILES["avatar"]["tmp_name"] != ""){
    $fileName = $_FILES["avatar"]["name"];
    $fileTmpLoc = $_FILES["avatar"]["tmp_name"];
    $fileType = $_FILES["avatar"]["type"];
    $fileSize = $_FILES["avatar"]["size"];
    $fileErrorMsg = $_FILES["avatar"]["error"];
    $kaboom = explode(".", $fileName);
    $fileExt = end($kaboom);
    list($width, $height) = getimagesize($fileTmpLoc);
    if($width < 10 || $height < 10){
        $result = "That image has no dimensions";

        exit();
    }
    $db_file_name = rand(100000000000,999999999999).".".$fileExt;
    if($fileSize > 1048576) {
        $result = "Your image file was larger than 1mb";
        echo $result;

    } else if (!preg_match("/\.(gif|jpg|png)$/i", $fileName) ) {
        $result = "Please only JPG, GIF or PNG images";
        echo $result;

    } else if ($fileErrorMsg == 1) {
        $result = "An unknown error occurred";
        echo $result;

    }

AJAX

$('#avatar_form').submit(function(event) {
  event.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'photo_system.php',
    data: $(this).serialize(),
    dataType: 'json',
    success: function (result) {
            console.log(result);
            $('#status').html(result);
    }
  });
});

2 个答案:

答案 0 :(得分:0)

我以前做过类似的事情,作为已经编写的插件的一部分,处理图像数据的代码和ajax如下:

var form_data = new FormData();
form_data.append($(_file).attr('name'), _file.files[0]);
var _this = this;
$.ajax({
   type: "POST",
   url: <<URL>>,
   data: form_data,
   cache: false,
   contentType: false,
   processData: false
})

这会将“文件”对话框中加载的图像提交给服务器,并使其符合$ _FILES超全局的预期格式。

另请注意,这只是该插件的一小部分。

答案 1 :(得分:0)

只需使用此Jquery parseJSON函数和json_encode:

保持这个PHP代码原样:

$Stuff = 'Hello world';

$Success = true;
$Content = $Stuff;

$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);

对于JS:

$.ajax({  
    type: "GET",
    url: "../pgs/UpdateEditAStudent.php",
    data: "FirstName="+ $('#student_first_name').val(),

    success: function(data){
        // Here is the tip
        var data = $.parseJSON(data);

        alert(data.Content);
    }
});