How can JavaScript be integrated with PHP to automatically update a page after an image upload?

To automatically update a page after an image upload, you can use JavaScript to make an AJAX request to a PHP script that handles the image upload. Once the upload is complete, the PHP script can return a response containing the URL of the newly uploaded image. The JavaScript can then update the page by displaying the new image using the returned URL.

<?php
// Handle image upload
if(isset($_FILES['image'])){
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["image"]["name"]);
    move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);
    
    // Return the URL of the uploaded image
    echo json_encode(array("image_url" => $target_file));
}
?>