오류 목록에 대한 Ajax 응답을 확인하는 방법

알렉스 K

그래서 저는 ajax와 php를 사용하여 텍스트와 함께 이미지를 업로드 할 수있는 '게시물 만들기'를 사용하고 있습니다. 현재 게시물에 콘텐츠가 있는지, 이미지가 있는지 확인하고 모든 것을 확인하는 PHP가 있습니다. 그러나 문제는 내가 응답을 받았을 때 그것을 포스트 피드에 추가하고 있다는 것입니다. 그러나 이것은 오류가있을 때 피드에도 추가됩니다. 내가하고 싶은 것은 오류라는 별도의 div에 오류를 추가하는 것입니다. 여기 내 PHP가 있습니다. (저는 방금 PHP로 시작했으며 문제가 있거나 적은 작업으로 더 쉽게 수행 할 수있는 경우 알려주십시오.)

<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');

$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];

if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}

$postEmpty = 0;

if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}

// validate post

if( $postEmpty == 0 && !empty($body) ){

    $cleanBody = clean_input($body);

}

// validate image (if any)

if( $has_image == 1 ){

    //check if directory exist if not create it
    if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
        mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
    }
    if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
        mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
    }
    //Set file upload path
    $path = "../users/user_".$user_id."/posts/"; //with trailing slash
    //Set max file size in bytes
    $max_size = 2000000;
    //Set default file extension whitelist
    $whitelist_ext = array('jpeg','jpg','png','gif');
    //Set default file type whitelist
    $whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');

    // Create an array to hold any output
    $errors = array();

    // Get filename
    $file_info = pathinfo($_FILES[$image]['name']);
    $name = $file_info['filename'];
    $ext = $file_info['extension'];

    //Check file has the right extension           
    if (!in_array($ext, $whitelist_ext)) {
        $errors[] = "Invalid file Extension";
    }

    //Check that the file is of the right type
    if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
        $errors[] = "Invalid file Type";
    }

    //Check that the file is not too big
    if ($_FILES[$image]["size"] > $max_size) {
        $errors[] = "File is too big";
    }

    //If $check image is set as true
    if (!getimagesize($_FILES[$image]['tmp_name'])) {
        $errors[] = "Uploaded file is not a valid image";
    }

    //Create full filename including path
    if ($random_name) {
    // Generate random filename
        $tmp = str_replace(array('.',' '), array('',''), microtime());

    if (!$tmp || $tmp == '') {
        $errors[] = "File must have a name";
    }     
        $newname = $tmp.'.'.$ext;                                
    } else {
        $newname = $name.'.'.$ext;
    }

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
        $errors[] = "A file with this name already exists";
    }

    if (count($errors)>0) {
    //The file has not correctly validated
        $imageError = 1;
    }

// if no errors:

    // upload image (if any) and retrieve filename
    if( $imageError == 1 ){

        foreach($errors as $error) {
            echo '<li>'.$error.'</li>';
            die();
        }

    }else{

        //Create full filename including path
        // Generate random filename
        $tmp = str_replace(array('.',' '), array('',''), microtime());

        if (!$tmp || $tmp == '') {
            $errors[] = "File must have a name";
        }     

        $newname = $tmp.'.'.$ext;                                

        //Check if file already exists on server
        if (file_exists($path.$newname)) {
            $errors[] = "A file with this name already exists";
        }

        if (count($errors)>0) {
        //The file has not correctly validated
            $imageError = 1;
            foreach($errors as $error) {
                echo '<li>'.$error.'</li>';
                die();
            }
        } 
      if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

            $uploadSuccesfull = 1;

        }else {
            $errors[] = "Server Error!";
            foreach($errors as $error) {
                echo '<li>'.$error.'</li>';
                die();
            }
        }

    }
}


// if no errors:

// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){

$query = "INSERT INTO posts
        (user_id, body, image, has_image, date)
        VALUES
        ('$user_id', '$body', '$newname', '$has_image', now())";

}else{

    $query = "INSERT INTO posts
        (user_id, body, has_image, date)
        VALUES
        ('$user_id', '$body', '$has_image', now())";

}

$result = $db->query($query);

// send response

//check to make sure the user was added
if( $db->affected_rows == 1 ){

    $user_id = $_SESSION['user_id'];

    $post_id = $db->insert_id;

    $query = "SELECT post_id, body, image, has_image
            FROM posts
            WHERE post_id = $post_id
            LIMIT 1";
    $result = $db->query($query);

    if($result->num_rows == 1){
        $row = $result->fetch_assoc();
    }

    $queryuser = "SELECT *
                FROM users
                WHERE user_id = $user_id
                LIMIT 1";
    $resultuser = $db->query($queryuser);
    if($resultuser->num_rows == 1){
        $rowuser = $resultuser->fetch_assoc();
    }


if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }

    if($row['has_image'] == 1){

?>
<article class="post">
    <div class="post-head cf">
        <a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
        <a href="" class="username">
            <?php echo $rowuser['username']; ?>
        </a>
    </div>
    <img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
    <div class="post-body">
        <div class="post-options">
            <a class="likes" href="">156 likes</a>
        </div>
        <p>
            <a class="username" href="">
                <?php echo $rowuser['username'] ?>
            </a>
            <?php echo $row['body'] ?>
        </p>
        <hr />
        <div class="cf">
            <a class="like hide-text" href="javascript:;">Like This Post</a>
            <form action="" class="comment">
                <input type="text" placeholder="Add a comment">
            </form>
        </div>
    </div>
</article>
<?php }else{ ?>

    <article class="post no-img">
        <div class="post-head cf">
            <a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
            <a href="" class="username">
                <?php echo $rowuser['username'] ?>
            </a>
        </div>
        <div class="post-body">
            <p>
                <a class="username" href="">
                    <?php echo $rowuser['username'] ?>
                </a>
                <?php echo $row['body'] ?>
            </p>
            <div class="post-options">
                <a class="likes" href="">1 like</a>
            </div>
            <hr />
            <div class="cf">
                <a class="like hide-text" href="javascript:;">Like This Post</a>
                <form action="" class="comment">
                    <input type="text" placeholder="Add a comment">
                </form>
            </div>
        </div>
    </article>

    <?php }
    }else{

        echo 'There was a database error';

    }

die();

여기 내 아약스 전화입니다

$.ajax({
        type: "post",
        url: "includes/create-post.php",
        data: new FormData(this),
        processData: false,
        contentType: false,
        error: function (response) {
            console.log(response);
        },
        success: function (response) {

            $('section.feed').prepend(response);

            $('article.post p').each(function () {
                $(this).html(linkHashtags($(this).html()));
            });

            $('article.post p').each(function () {
                $(this).html(linkatsymbols($(this).html()));
            });
            revealPosts();

        }
    });
Ayan

를 들어 die()당신은 단순히 문을 넣을 수 있습니다 die에서 foreach이 같은 :

if( $imageError == 1 ){
    foreach($errors as $error) {
        echo '<li>'.$error.'</li>';
    }
    die();
}
.
.
.
.
.
.
if (count($errors)>0) {
    //The file has not correctly validated
    $imageError = 1;
    foreach($errors as $error) {
        echo '<li>'.$error.'</li>';
    }
    die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

    $uploadSuccesfull = 1;

}
else {
    $errors[] = "Server Error!";
    foreach($errors as $error) {
        echo '<li>'.$error.'</li>';
    }
    die();
}

그러나 다른 요소에 오류를 표시하고 싶기 때문에 수신하는 출력이 오류인지 확인하는 방법이 필요합니다. 따라서 코드를 다음으로 바꾸십시오.

// if no errors:

// upload image (if any) and retrieve filename
if( $imageError == 1 ){

    $ret_data = ['items' => $errors, 'responseCode' => 0];
    //content in $items must be in UTF-8
    echo json_encode($ret_data);

    die();
}
else{

    //Create full filename including path
    // Generate random filename
    $tmp = str_replace(array('.',' '), array('',''), microtime());

    if (!$tmp || $tmp == '') {
        $errors[] = "File must have a name";
    }     

    $newname = $tmp.'.'.$ext;                                

    //Check if file already exists on server
    if (file_exists($path.$newname)) {
        $errors[] = "A file with this name already exists";
    }

    if (count($errors)>0) {
    //The file has not correctly validated
        $imageError = 1;

        $ret_data = ['items' => $errors, 'responseCode' => 0];
        //content in $items must be in UTF-8
        echo json_encode($ret_data);

        die();
    } 
    if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

        $uploadSuccesfull = 1;

    }
    else {
        $errors[] = "Server Error!";

        $ret_data = ['items' => $errors, 'responseCode' => 0];
        //content in $items must be in UTF-8
        echo json_encode($ret_data);

        die();
    }

  }
}

그리고 AJAX 성공 호출에서 다음과 같이하십시오.

success: function (response) {
        var obj = JSON.parse(response);
        var errorCode = obj.responseCode;
        var errorSet = obj.items;
        if(errorCode == 0) {
                $.each(errorSet, function(i, v) {
                      console.log('<li>'+v+'</li>');
                }
         }
         //Your rest of the code

BTW, 디자인에서 코드를 분리하는 것이 좋습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Ajax 호출에 대한 Django의 응답을 포착하는 방법

분류에서Dev

Ajax 호출에 대한 응답을 만들고 처리하는 방법

분류에서Dev

VEX 대화 상자에 AJAX 응답을로드하는 방법

분류에서Dev

POSTMAN-값> 0에 대한 응답 본문을 확인하는 방법

분류에서Dev

Ruby에서 HTTPClient 오류에 대한 응답을 얻는 방법이 있습니까?

분류에서Dev

항목 목록을 사용하여 SOAP 응답에 대한 WSDL 복합 유형을 정의하는 방법

분류에서Dev

Ajax Codeigniter에 대한 응답 후 다른 컨트롤러 실행을 중지하는 방법

분류에서Dev

Ajax 요청에 대한 JSON 응답을 구문 분석하는 방법은 무엇입니까?

분류에서Dev

JMeter의 csv 파일에 대한 응답에서 xml 목록을 저장하는 방법

분류에서Dev

모든 Ajax 요청에 대한 응답을 위해 미들웨어를 만드는 방법

분류에서Dev

모델에 대한 응답을 저장하는 방법

분류에서Dev

중첩 된 JSON 응답에 대한 믹스 인을 매핑하는 방법

분류에서Dev

getJSON () jQuery 호출에서 오는 HTTP 요청에 대한 HTTP 응답을 형식화하는 방법

분류에서Dev

Ajax 응답에 대한 PHP 파일 오류

분류에서Dev

Ajax 호출에 대한 오류 코드 응답 보내기

분류에서Dev

ajax 응답 오류를 관리하는 방법

분류에서Dev

ajax 응답 오류를 관리하는 방법

분류에서Dev

자바에서 일반 목록의 배열을 만드는 방법에 대한 오류

분류에서Dev

MAXScript 함수에 대한 인수 목록을 가져 오는 방법

분류에서Dev

우편 배달부 클라이언트에서 기본 IP 차단 응답 오류를 해결하고 Cardstream 결제 게이트웨이에 대한 성공적인 응답을 얻는 방법은 무엇입니까?

분류에서Dev

AJAX 응답에서 파일을 다운로드하는 방법

분류에서Dev

AJAX 응답에서 DataTable을 다시 초기화하는 방법

분류에서Dev

AJAX 응답을 경고에 표시하는 방법

분류에서Dev

jquery에서 ajax의 응답 HTML을 분할하는 방법

분류에서Dev

jmeter에서 오류 응답 만 기록하는 방법

분류에서Dev

Flutter-인증 오류 링크에서 API 응답을 얻는 방법

분류에서Dev

Postman-필수 속성의 마지막 발생에 대한 JSON 응답에서 값을 가져 오는 방법

분류에서Dev

Hanami에서 404 오류 응답 형식을 JSON으로 설정하는 방법

분류에서Dev

배열 목록에 대한 문자열 값의 오름차순을 확인하는 방법은 무엇입니까?

Related 관련 기사

  1. 1

    Ajax 호출에 대한 Django의 응답을 포착하는 방법

  2. 2

    Ajax 호출에 대한 응답을 만들고 처리하는 방법

  3. 3

    VEX 대화 상자에 AJAX 응답을로드하는 방법

  4. 4

    POSTMAN-값> 0에 대한 응답 본문을 확인하는 방법

  5. 5

    Ruby에서 HTTPClient 오류에 대한 응답을 얻는 방법이 있습니까?

  6. 6

    항목 목록을 사용하여 SOAP 응답에 대한 WSDL 복합 유형을 정의하는 방법

  7. 7

    Ajax Codeigniter에 대한 응답 후 다른 컨트롤러 실행을 중지하는 방법

  8. 8

    Ajax 요청에 대한 JSON 응답을 구문 분석하는 방법은 무엇입니까?

  9. 9

    JMeter의 csv 파일에 대한 응답에서 xml 목록을 저장하는 방법

  10. 10

    모든 Ajax 요청에 대한 응답을 위해 미들웨어를 만드는 방법

  11. 11

    모델에 대한 응답을 저장하는 방법

  12. 12

    중첩 된 JSON 응답에 대한 믹스 인을 매핑하는 방법

  13. 13

    getJSON () jQuery 호출에서 오는 HTTP 요청에 대한 HTTP 응답을 형식화하는 방법

  14. 14

    Ajax 응답에 대한 PHP 파일 오류

  15. 15

    Ajax 호출에 대한 오류 코드 응답 보내기

  16. 16

    ajax 응답 오류를 관리하는 방법

  17. 17

    ajax 응답 오류를 관리하는 방법

  18. 18

    자바에서 일반 목록의 배열을 만드는 방법에 대한 오류

  19. 19

    MAXScript 함수에 대한 인수 목록을 가져 오는 방법

  20. 20

    우편 배달부 클라이언트에서 기본 IP 차단 응답 오류를 해결하고 Cardstream 결제 게이트웨이에 대한 성공적인 응답을 얻는 방법은 무엇입니까?

  21. 21

    AJAX 응답에서 파일을 다운로드하는 방법

  22. 22

    AJAX 응답에서 DataTable을 다시 초기화하는 방법

  23. 23

    AJAX 응답을 경고에 표시하는 방법

  24. 24

    jquery에서 ajax의 응답 HTML을 분할하는 방법

  25. 25

    jmeter에서 오류 응답 만 기록하는 방법

  26. 26

    Flutter-인증 오류 링크에서 API 응답을 얻는 방법

  27. 27

    Postman-필수 속성의 마지막 발생에 대한 JSON 응답에서 값을 가져 오는 방법

  28. 28

    Hanami에서 404 오류 응답 형식을 JSON으로 설정하는 방법

  29. 29

    배열 목록에 대한 문자열 값의 오름차순을 확인하는 방법은 무엇입니까?

뜨겁다태그

보관