Uploading an image via AJAX form fails - Probably PHP error

Hello and welcome myself!

I’m trying to make a popup form that utilizes jQuery and PHP to upload a photo to the server and make a database entry about the photo.

What is wanted:
-User uploads a photo. Anything else other than .jpg/.jpeg is rejected.
-Photo is resized to 1000x1000 and 250x250. The original file is destroyed.
-The photo and the thumb are sent to their respective folders (uploads and uploads/thumbs).
-Mysql declares the new files in the database, including title, description, time.

It simply reloads the page instead. No console errors. Here is my code so far. Most of the PHP code is required to use (the image editing part)

HTML Form

<div class="popup popup2 flex-enable" data-popup="popup-2">
				<div class="popup-inner flex-center">
					<h2 class="small-white-title textcenter">Upload a photo</h2>
					<hr>
					<div class="flex-enable">
						<form class="flex-enable flex-column flex-center" id="uploadForm" action="" method="post" enctype="multipart/form-data">
						<div class="small-white-subtitle form-label flex-column flex-center textcenter">
							<label for="title">Τίτλος Φωτογραφίας</label>
							<input class="form-input-large small-white-title" type="text" id="phototitle" name="title" placeholder="Γράψτε εδώ τον τίτλο...">
						</div>
						<div class="small-white-subtitle form-label flex-column flex-center">
							<input type="file" name="file" id="file" class="inputfile" />
							<label id="uploadPhoto" for="file">Επιλέξτε αρχείο<br></label>
							<div id="message"></div>
						</div>
						<br>
						<div class="small-white-subtitle form-label flex-column flex-center textcenter">
							<label for="description">Περιγραφή Φωτογραφίας</label>
							<input class="form-input-large small-white-title" type="text" id="photodesc" name="photodesc" placeholder="Γράψτε εδώ μία περιγραφή...">
						</div>

						<input type="submit" value="Upload" >
						<input type="reset" value="Reset" >
						</form>
					</div>
					<a class="popup-close" data-popup-close="popup-2" href="#">×</a>
				</div>

PHP

<?php
require('connect.php');

function makeImage($imgfile, $imgname, $inputWidth, $inputHeight, $path){

	$saving_path = $path."/".$imgname;
	$source = imagecreatefromjpeg($imgfile);	
	$size= getimagesize($imgfile);
	$width = $size[0];
	$height = $size[1];
	
	$finalWidth=$inputWidth;
	$finalHeight=$inputHeight;

	if ($width>$height){
		$resizeFactor=$finalWidth/$width;
	
	}
	else{
		$resizeFactor=$finalHeight/$height;	
	}
	
	$finalWidth=$width*$resizeFactor;
	$finalHeight=$height*$resizeFactor;
	
	$thumb = imagecreatetruecolor($finalWidth, $finalHeight);	
	imagecopyresampled($thumb, $source, 0, 0, 0, 0, $finalWidth, $finalHeight, $width, $height);	
	imagejpeg($thumb, $saving_path, 90);
}

$fileName = uniqid("p_");
$title=mysqli_real_escape_string($conn, $_POST['title']);
$description=mysqli_real_escape_string($conn, $_POST['photodesc']);
$targetDir = "uploads/";
$thumbDir = "uploads/thumbs/";
$targetFile = $targetDir.$fileName;
$fileExt = pathinfo($targetFile, PATHINFO_EXTENSION);
$allowExt = array('jpg','jpeg');
	
if(in_array($fileExt, $allowExt)){
	makeImage($_FILES['file'], $filename.".jpg", 1000, 1000, $targetDir);
	makeImage($_FILES['file'], $filename.".jpg", 250, 250, $thumbsDir);
	unlink($image['tmp_name']) or die('Warning! Original file could not be deleted!');
	$insertPhotoQuery="INSERT INTO photos (filename, title, description, timestamp) VALUES ('$fileName', '$title', '$description', now())";
	$insertPhotoStatement = mysqli_prepare($conn, $insertPhotoQuery);
	if(mysqli_stmt_execute($insertPhotoStatement)){
		$response['status'] = 'ok';
	}
	else{
		$response['status'] = 'err';
	}
}
else{
	$response['status'] = 'type_err';
}
echo json_encode($response);

?>

jQuery

$(function(){
	$(document).on('drop dragover',function(e){
		e.preventDefault();
	});
	$('input[type=file]').on('change',anevase);
});

function anevase(event){
	event.preventDefault();
	$sanitizedFilename = event.target.value.replace("C:\\fakepath\\","");
	$("#uploadPhoto").html($sanitizedFilename);
	file = event.target.files[0];
	var data = new FormData();
	if (!file.type.match('image/jpg') || !file.type.match('image/jpeg')){
		$("uploadPhoto").html("Please select a jpg file");
	}
	else if(file.size>5000000){
		$("uploadPhoto").html("Please select a smaller file (<5 MB)");
	}
	else{
		data.append('file', file, file.name);
		data.append('title',$("#title"));
		data.append('photodesc',$("#photodesc"));
		var xhr = new XMLHttpRequest();
		xhr.open('POST', 'upload.php', true);
		xhr.send(data);
		xhr.onload = function(){
			var response = JSON.parse(xhr.responseText);
			if(response.status == 'ok'){
				$("#uploadPhoto").html("File has been uploaded successfully.")
			}
			else if(response.status == 'type_err'){
				$("#uploadPhoto").html("Please choose an image file.");
			}
			else{
				$("#uploadPhoto").html("Unspecified error, please try again.");
			}
		};
	}
}

Hi @kouraf16 and a warm welcome to the forums.

It is possible that the JavaScript encounters an error before it reaches the bit where it prevents the default’s form submission event.preventDefault(), and so there might be an error displaying in the console very quickly before it disappears upon page reload. I know these situations are a bit tricky to trace but if I remember correctly Firefox at least now persists those errors in the console after a page reload.

Hope this tip helps,

Andres

Hey Andres, thanks for your suggestion. I tried Firefox with persist logs ticked, but I only get this:

Navigated to http://localhost/prog2/
Navigated to http://localhost/prog2/index.php

If I go to extra verbose mode (all logs enabled) I only get a CSS error and nothing else.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.