Here’s an example of how you can update a profile picture on a webpage using HTML, CSS, JavaScript, and PHP:
HTML:
CSS:
#profile-picture {
text-align: center;
}
#current- picture {
width: 200px;
height: 200px;
border-radius: 100px;
}
#form {
margin-top: 20px;
}
input[type="file"] {
display: none;
}
JavaScript:
const fileInput = document.getElementById("file-input");
const currentPicture = document.getElementById("current-picture");
fileInput.addEventListener("change", (event) => {
const file = event.target.files[0];
const reader = new FileReader();
reader.onloadend = function () {
currentPicture.src = reader.result;
};
reader.readAsDataURL(file);
});
document.getElementById("form").addEventListener("submit", (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("picture", fileInput.files[0]);
fetch("upload.php", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
});
PHP:
"Success"));
} else {
echo json_encode(array("message" => "File is too big"));
}
} else {
echo json_encode(array("message" => "There was an error uploading your file"));
}
} else {
echo json_encode(array("message" => "Invalid file type"));
}
}
?>
This code creates a form that allows users to select an image file and submit it to the server for uploading. The JavaScript code listens for a change in the file input and updates the src attribute of the current profile picture `img` element. It also listens for a submit event on the form and makes a POST request to the server using fetch to upload the image. The PHP code on the server processes the uploaded image and returns a JSON response indicating whether the upload was successful or not.