user2687618
user2687618

Reputation: 59

display Javascript alert() upon successful upload of a file

I have a small upload system to upload profile picture . I want to show an alert box with 1 button (uploaded successfully). here is my php upload function :

function change_profile_image($user_id, $file_temp, $file_extn){
    $file_path = substr(md5(time()), 0, 10) . '.' . $file_extn;
    move_uploaded_file($file_temp, 'images/profile/'.$file_path);
    Thumbnail('images/profile/', $file_path, 'images/thumbs/');
    mysql_query("UPDATE `users` SET `profile` = 'images/profile/" . mysql_real_escape_string($file_path) . "' WHERE `user_id` = " . (int)$user_id);
}

and here is how i call the function:

if (in_array($file_extn, $allowed) === true) {
                        change_profile_image($session_user_id, $file_temp, $file_extn);
                        header('Location: ' . $current_file);
                        exit();
                    }

Upvotes: 0

Views: 1673

Answers (1)

LSerni
LSerni

Reputation: 57408

This might be a job for jQuery. Actually, it probably is.

But a maybe close second (and simpler) option might be to pass along a GET parameter as confirmation:

header("Location: {$current_file}?loaded=ok");

and then check for it in the "current file", maybe at the end of the body:

if (isset($_GET['loaded'])) {
    if ('ok' == $_GET['loaded'])
        $msg = "Loaded OK!";
    else
        $msg = "Oh noes! Error {$_GET['loaded']} while updating picture";
    // Remember, keep $msg without 'quote' "signs", or \"escape\" them properly
    print <<<DISPLAY_ALERT
<script>
    alert('$msg');
</script>
DISPLAY_ALERT;
}

Note: the above code uses PHP "here documents". They work like this: the string is introduced by <<<SOMESEQUENCE where you mustn't have anything after SOMESEQUENCE. And is terminated by a single line containing only SOMESEQUENCE;, without extra whitespaces anywhere. The presence of even a single space will cause malfunctions that may be sometimes difficult to diagnose. Also, YOUR_SEQUENCE must be unique within the PHP code. You can't have two heredocs with the same sequence (in a pinch, number them: SEQUENCE1, SEQUENCE2).

Inside a heredoc, you can use unquoted strings, and carriage returns, so it's my favourite way of including HTML snippets whenever I can't use proper templates.

Upvotes: 1

Related Questions