修改代码以实现AJAX

时间:2017-11-07 06:42:48

标签: php ajax

我有这两个文件index.php和uploadcover.inc.php,并以输入字段作为文件提交index.php的形式,它让我们上传一个图像设置为封面图片。代码工作正常,但我想修改这个index.php文件,使用AJAX实现这一点,而不刷新页面,并使用header函数从uploadcover.inc.php重定向回index.php。请帮助我出去了。

index.php =>

<?php session_start(); ?>
<!DOCTYPE html>
<html>
<body>
    <form action="include/uploadcover.inc.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file" id="cover-upload" style="display:none" onchange="this.form.submit();">
    <label for="cover-upload" class="fa fa-camera fa-2x" aria-hidden="true"></label>
    </form>
</body>
</html>

uploadcover.inc.php =&gt;

<?php
session_start();
include_once 'dbh.inc.php';
$sessionid = $_SESSION['u_id'];
  $file= $_FILES['file'];
  $fileName= $file['name'];
  $fileTmpName= $file['tmp_name'];
  $fileSize= $file['size'];
  $fileError= $file['error'];
  $fileType= $file['type'];

  $fileExt = explode('.',$fileName);
  $fileActualExt = strtolower(end($fileExt));

  $allowed = array('jpg','jpeg','png','gif');

  if(in_array($fileActualExt,$allowed)){
    if($fileError=== 0){
      if($fileSize<3145728){
        $fileNameNew = "cover".$sessionid.".".$fileActualExt;
        $fileDestination = '../profile/'.$fileNameNew;
        move_uploaded_file($fileTmpName,$fileDestination);
        $sql = "UPDATE coverimg SET status=0 WHERE user_id='$sessionid'";
        mysqli_query($conn,$sql);
        header("Location: ../index.php?upload=success");
      } else {
        $_SESSION['errors']['size'] = 1;
        session_write_close();
        header("Location: ../index.php?upload=size_exceeded_3MB");
      }
    } else {
      $_SESSION['errors']['upload'] = 1;
      session_write_close();
      header("Location: ../index.php?upload=error");
    }
  } else{
    $_SESSION['errors']['type'] = 1;
    session_write_close();
    header("Location: ../index.php?upload=typeerror");
  }

帮助,我使用index.php文件的AJAX代码实现相同的操作,而不需要uploadcover.inc.php中的头文件。

3 个答案:

答案 0 :(得分:0)

如果您使用的是jQuery,它已经实现了一个函数$.ajax()。 你可以使用那个功能

答案 1 :(得分:0)

如果您使用的是jquery,它有一个函数$。 ajax()已经实现。

http://api.jquery.com/jquery.ajax/

https://www.sitepoint.com/use-jquerys-ajax-function/

答案 2 :(得分:0)

您无法使用ajax在PHP中重定向,您需要从PHP返回该网址并使用window.location.href重定向到所需的网址。既然您正在使用ajax,那么您不需要错误网址(index.php?upload=errorupload=size_exceeded_3Mindex.php?upload=typeerror),您需要添加<p>来显示错误消息给用户。

  1. 让我们通过更改onchange来调整我们的ajax函数来修改表单

    <form action="include/uploadcover.inc.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file" id="cover-upload" style="display:none" onchange="submit_cover()">
        <label for="cover-upload" class="fa fa-camera fa-2x" aria-hidden="true"></label>
    </form>
    
  2. 添加<p>以向用户显示错误

    <p id="display-error" style="color: red"></p>
    
  3. 创建ajax函数。

    function submit_cover() {
        var formData = new FormData($('form')[0]); // Create an arbitrary FormData instance
    
        $.ajax('include/uploadcover.inc.php', {
            type        : 'POST',
            processData : false,
            contentType : false,
            data        : formData,
            success     : function (data) {
                var response = JSON.parse(data);
                if (response.redirect) {
                    window.location.href = response.redirect;
                }else if (response.moveerror) {
                    $('#display-error').html(response.moveerror);
                }else if (response.sizeerror) {
                    $('#display-error').html(response.sizeerror);
                }else if (response.uploaderror) {
                    $('#display-error').html(response.uploaderror);
                }else if (response.typeerror) {
                    $('#display-error').html(response.typeerror);
                }
            }
        });
    }
    
  4. 从PHP中删除header函数并返回对Javascript的响应并从那里重定向。

    <?php
    session_start();
    include_once 'dbh.inc.php';
    $sessionid = $_SESSION['u_id'];
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileSize = $file['size'];
    $fileError = $file['error'];
    $fileType = $file['type'];
    
    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));
    
    $allowed = array('jpg', 'jpeg', 'png', 'gif');
    
    $response = [];
    
    if (in_array($fileActualExt, $allowed)) {
        if ($fileError === 0) {
            if ($fileSize < 3145728) {
                $fileNameNew = "cover" . $sessionid . "." . $fileActualExt;
                $fileDestination = '../profile/' . $fileNameNew;
                if (move_uploaded_file($fileTmpName, $fileDestination)) {
                    // if file was moved update database with the new data
                    $sql = "UPDATE coverimg SET status=0 WHERE user_id='$sessionid'";
                    mysqli_query($conn, $sql);
                    $response['redirect'] = '../index.php?upload=success';
                } else {
                    $response['moveerror'] = 'Unable to move the file';
                }
            } else {
                $_SESSION['errors']['size'] = 1;
                session_write_close();
                $response['sizeerror'] = 'Upload size exceeded';
            }
        } else {
            $_SESSION['errors']['upload'] = 1;
            session_write_close();
            $response['uploaderror'] = 'Upload error';
        }
    } else {
        $_SESSION['errors']['type'] = 1;
        session_write_close();
        $response['typeerror'] = 'Allowed types: jpg, jpeg, png and gif';
    }
    
    echo json_encode($response);