0

Consider this session:

echo '<img src = "'.$_SESSION['userpic'].'" class = "changepic">';

This is an image which displays the users image in the database with a session variable! However in my site i am changing the users picture with an upload image form, the users picture is getting updated but the old picture stays until i refresh my page... I want to avoid refreshing the page to solve this issue....

    <form action = "upload.php" id = "bildUppladdning"  method = "post" enctype = "multipart/form-data" target = "hiddenFrame">
    <input type = "file" name = "file" id = "fileToUpload" accept="image/*" style = "display:none" onchange="form.submit()">
    </form>

Notice that i target an iframe to not be redirected to my action...

if(isset($_FILES['file']) ){

move_uploaded_file($_FILES['file']['tmp_name'],'files/'.$_FILES['file']['name']);

session_start();
$username = $_SESSION['user'];
$userpic = 'files/'.$_FILES['file']['name'];
$id = $_SESSION['id'];

include ("connect.php");
$sql = $con->prepare('UPDATE users SET username=?, userpic=? WHERE id = ?');
$sql->bind_param("ssi",$username,$userpic,$id);
$sql->execute(); 
$sql->close();
$con->close();  
$_SESSION['userpic'] = $userpic;
}
else{
$_SESSION['checked'] = '<div class = "check"> NO</div>';}

And here is my upload form which you probably doesn't need but ill put it here anyways...

For example:

$("#fileToUpload").on('submit', function(response)
{
$.ajax({
url: "update.php"
});
return false;
});

Update.php example

<?php 
 $_SESSION['userpic'] = $row->userpic;
?>

So to keep it simple I would like to "update" this echo img tag when the form is submitted without refreshing or get redirected..

Any ideas how i could solve this problem?

Furious Mountain
  • 1,323
  • 3
  • 16
  • 44

3 Answers3

2

You need to use AJAX to achieve what you want.

Your HTML doesn't quite makes sense or you forgot to give us more information. There has to be a way to select the file. Your HTML code is hiding the file input button for whatever reason. So let's assume, it was not hidden:

<input type="file" id="fileToUpload" accept="image/*">

First, attach an onchange event handler to your file input button using jQuery. In the handler, we will store the selected file in a FormData object, which is needed to send files over with AJAX.

$('#fileToUpload').change(function () {
    var file = this.files[0];
    console.log('file', file);

    var formData = new FormData();
    formData.append('file', file);

    $.ajax({
        type: 'post'
        url: "upload.php",
        cache: false,
        contentType: false, // important
        processData: false, // important
        data: formData,     // important
        success: function (res) {
            console.log('response (url)', res);
            $('.changepic').attr('src', res);
        }
    });
});

Second, the response that is expected from our AJAX request is the URL, so we'll need to also alter your PHP script.

// not within the scope of the question, but you need to do additional checks
if (isset($_FILES['file'])){
    $userpic = 'files/'. $_FILES['file']['name'];
    move_uploaded_file($_FILES['file']['tmp_name'], $userpic);

    session_start();
    $username = $_SESSION['user'];
    $id = $_SESSION['id'];

    include "connect.php";
    $sql = $con->prepare('UPDATE users SET username= ?, userpic=? WHERE id = ?');
    $sql->bind_param("ssi", $username, $userpic, $id);
    $sql->execute(); 
    $sql->close();
    $con->close();

    $_SESSION['userpic'] = $userpic;

    // important: output ONLY (and i mean ONLY) the path of your newly uploaded pic
    // the output of your script is the AJAX response that will be returned back in your JavaScript
    echo $userpic;
} else {
    $_SESSION['checked'] = '<div class = "check"> NO</div>';
}

If something goes wrong, look at the console logs to see where it fails.

Mikey
  • 6,728
  • 4
  • 22
  • 45
  • its possible to select the file don't worry;) And the additional checks will be there soon aswell just wanted this to work first. Thanks for your answer worked like a charm and exactly how i wanted it to work! – Furious Mountain Mar 06 '17 at 21:06
0

actually... the problem is not as trivial as you might think. You want to upload a file, and then once the upload is done, trigger a callback. This is not as straight forward as one might think.

You should try using this plugin:

https://github.com/blueimp/jQuery-File-Upload

there is a link to the wiki as well

https://github.com/blueimp/jQuery-File-Upload/wiki

Community
  • 1
  • 1
Toskan
  • 13,911
  • 14
  • 95
  • 185
  • I changed my question into your answer however it didn't work and the console.log is not writing out error either @Toskan – Furious Mountain Mar 06 '17 at 16:31
  • try checking out the links, might get you started – Toskan Mar 06 '17 at 16:43
  • actually it does seem trivial... add the file as data parameter to the ajax call and on response, e.g. on success, make sure your update.php just outputs and only outputs the url – Toskan Mar 06 '17 at 16:48
  • but i dont want to upload with ajax i only want to update this session when a new file is uploaded – Furious Mountain Mar 06 '17 at 19:43
  • well then don't use ajax... if you stop using ajax, and after successful upload redirect back to the same page, you will see the new picture as well – Toskan Mar 06 '17 at 20:21
  • so remove 'return false;' removing that, will make that the form actually submits and then displays the answer from the server. Whatever is put out in update.php (via echo for example) will then show on the screen. If your update.php does not output the same form again, then you should redirect to the page that was showing the image. Or please formulate your question again. I might misunderstand. – Toskan Mar 06 '17 at 20:24
  • Good point but i want to achieve this upload without getting redirected, because then my content on my site (an youtube video) will start over again – Furious Mountain Mar 06 '17 at 20:28
  • but then you need to use ajax to upload the file, and use the `success` callback function to read the answer from the server. Start easy: enable error reporting in `update.php` with ` ini_set('display_errors', 1); error_reporting(E_ALL ^ E_NOTICE);` and try to get something on success or error out at all. You can display the page, then add a `die('hello world');` to the top of the update.php to get started and figure out if your ajax call works – Toskan Mar 06 '17 at 20:32
-1

If you want to change your current pic which is coming from session variable without using page refresh. You need to change the attributes via javascript or jquery method.

Here is the sample code

$("#fileToUpload").submit(function(response)
{
    $.ajax({url: "update.php",});
    document.getElementsByClassName("changepic").src= response.fullImagePath;
    return false;
});