2

I am trying to upload pictures without the page refreshing. I used event.preventDefault() in order to stop the page from refreshing. However, the PHP code that is inside of my jQuery code is not being executed (I think, at least the pictures are not being uploaded to mySQL) when I write event.preventDefault() into my jQuery code. Here is my code:

<?php
    $target_file = ($_FILES["fileToUpload"]["name"]);
    $uploadOk = 1;
    $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

    if(isset($_POST["submit"])) {
        $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
        if($check !== false) {
            echo "File is an image - " . $check["mime"] . ".";
            $uploadOk = 1;
        } else {
            echo "File is not an image.";
            $uploadOk = 0;
        }
        else {
            $link = mysqli_connect(); // Connects successfully
            $image = addslashes(file_get_contents($_FILES['fileToUpload']['tmp_name']));
            $image_name = addslashes($_FILES['fileToUpload']['name']);
            $query = "INSERT INTO `pictures` (`name`, `image`) VALUES ('{$image_name}', '{$image}')";

            if (!mysqli_query($link, $query)) { // Error handling
                echo "Something went wrong! :("; 
            }
            else {
                $storeArray = Array();
                $query = "SELECT image FROM pictures"; 
                if($result = mysqli_query($link, $query)) {
                    while($row = mysqli_fetch_array($result)) {
                        $storeArray[] =  $row['image'];  
                    }
                }
                else {
                    echo "something is wrong!"; 
                }
            }
            for ($x = 0; $x <= 10; $x++) {
                echo '<img src="data:image/jpeg;base64,'.base64_encode($storeArray[$x]).'"/>';
            }
        }
    }
    else {

    }

?>
event.preventDefault(); 
    });
});

Anybody know how to stop the page from refreshing AND my PHP code being executed?

Jae Kim
  • 625
  • 3
  • 12
  • 23

1 Answers1

0

Perform an asynchronous HTTP (Ajax) request. jQuery AJAX

turbopipp
  • 1,245
  • 2
  • 14
  • 27