-1

I have these 2 files index.php and uploadcover.inc.php and submitting the form of index.php with the input field as file, it lets us upload an image to set as the cover picture. The code works fine as it is, but I want to modify this index.php file to use AJAX for implementing this without the page being refreshed and the redirected from uploadcover.inc.php back to index.php using the header function.Please help me out.

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 =>

<?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");
  }

Help, me out with the AJAX code for the index.php file to implement the same without the need for headers in uploadcover.inc.php.

3 Answers3

0

If you are using jQuery, it has a function $.ajax() already implemented. you can use that function

Styx
  • 9,863
  • 8
  • 43
  • 53
cosmin_popescu
  • 186
  • 4
  • 16
0

If you are using jquery, it has a function $. ajax() already implemented.

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

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

cosmin_popescu
  • 186
  • 4
  • 16
0

You cannot redirect in your PHP using ajax, you'll need to return the url from PHP and use window.location.href to redirect to the desired url. Now that you are using ajax, you don't need error urls (index.php?upload=error, upload=size_exceeded_3M and index.php?upload=typeerror), you need to add <p> to display the error messages to the user.

  1. Let's modify the form by changing onchange to call our ajax function

    <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. add <p> to display errors to the user

    <p id="display-error" style="color: red"></p>
    
  3. create the ajax function.

    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. remove header function from PHP and return response to Javascript and redirect from there.

    <?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);
    
Junius L
  • 15,881
  • 6
  • 52
  • 96