1

Please note this is not a duplicate question. This question involves submitting a form and refreshing a div on a change event - not a click event. FYI.

I have a form to allow users to upload an image. I have removed the submit button and added a javascript on change event to submit the form automatically when the user inputs an image.

This works fine and the image is uploaded.

However, I am also pulling through the image to display this to the user. At the moment, the user does not see the image change until they refresh the page or sometimes not even until they clear their cache.

The div containing the images should refresh upon the form being submitted, and the page itself should not refresh. At the moment the div is not refreshing and I think the form is submitting and refreshing the page.

Please can someone show me where I am going wrong? Thanks

Code:

<!-- Commence Photo Upload A -->
<?php
if(isset($_FILES['image6'])){
      $dir = $image .'/F/';
      $file_name = $_FILES['image6']['name'];
      $file_name = $dir. 'sub_img.jpg';
      $file_size = $_FILES['image6']['size'];
      $file_tmp = $_FILES['image6']['tmp_name'];
      $file_type = $_FILES['image6']['type'];
      $tmp = explode('.',$_FILES['image6']['name']);
      $file_ext=strtolower(end($tmp));
      $extensions= array("jpeg","jpg","png","gif");

      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a GIF, JPEG or PNG file.";
      }

      if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
      }

      if(empty($errors)==true) {
         move_uploaded_file($file_tmp, $file_name);
      }else{
      }} ?>


  <script> 
$('#uploads6').submit(function(){
        var data = $(this).serialize();

        $.ajax({
            url: "upload_6.php",
            type: "POST",
            data: data,
            success: function( data )
            {
               //here is the code I want to refresh the div(#container)
               $('.image6').html(data);

            },
            error: function(){
                alert('ERROR');
            }
        });

        return false;
    });
</script> 


      <form id="uploads6" action = "" method = "POST" enctype = "multipart/form-data">
      <label class="profile_gallery_image_in"><input type="file" name="image6" id="image6" onchange="form.submit()"/><p class="label"></p><img class="myImg" src="<?php echo $image.'/F/sub_img.jpg'; ?>"  height="100%" width="100%" /></label>

      </form>
  • @Roshan - not a duplicate. The other question asks about submitting a form and refreshing on a click event. This question is targeted around an on change event. They are entirely different functions. – jake tanner Mar 12 '19 at 01:17
  • is the URL to the image the same? or how/what are your returning as data. If it's a URL you can put the micro time in a query string when changing it `?cachebuster=12345673232` which will look like a unique request to the server so it wont be cached. I've used this when doing image edits through a UI, because of caching issues etc. ( It was a image crop, rotate resize type tool ) same problem though and its pretty trivial to try. – ArtisticPhoenix Mar 12 '19 at 01:26
  • @ArtisticPhoenix The image upload path and the image url is the same yes. I have no idea how to do what you just said ref, a micro time in a query string. :/ – jake tanner Mar 12 '19 at 01:29
  • if you get the url from the sever just do `$url = "www.example.com/image.jpg?cachebuster=".microtime(true);` – ArtisticPhoenix Mar 12 '19 at 01:31

3 Answers3

0

To prevant default form submission try:

e.preventDefault();

To stop event bubling try:

e.stopPropagation();

Also try to add a ‚#‘ or ‚javascript:void(0)‘ in your HTML action-attribute.

PaTy
  • 21
  • 2
  • thanks for the suggestions. I've added both your lines of code and these don't stop the page refresh. Plus i added Javascrip:void(0) in my form action attribute and whilst the page doesn't referesh this just stops the image upload/form submitting all together. – jake tanner Mar 12 '19 at 02:01
  • Did you pass the ‚e‘ parameter through your submit-function like ‚submit(function(e)‘? – PaTy Mar 12 '19 at 02:08
  • Added this in a small codepen and its working for me: https://codepen.io/anon/pen/xBXXbN. Maybe it will help you to find out where your problem is. ;-) – PaTy Mar 12 '19 at 02:36
0

For image caching you can try the age old "cachebuster" method.

All it is is put something unique into the url query.

 www.example.com/image.jpg?cachebuster=somethingunique

The browser will see this as a new request because it doesn't know what the query string does, it could be a search form for all it cares. So it will not pull it from the cache.

Good choices for the something unque is any time based component, as you know its never been used before. Ive used filesize($file) before when doing image edits.

$url = "www.example.com/image.jpg?cachebuster=".microtime(true); //as a float
$url = "www.example.com/image.jpg?cachebuster=".time(); // only 1 second granularity
$url = "www.example.com/image.jpg?cachebuster=".filesize($file); // based on the size of the file
$url = "www.example.com/image.jpg?cachebuster=".hash_file($file);  //based on file contents

And so on. You can even do it in JavaScript if you want to.

For the form

    $('#uploads6').submit(function(e){
          e.preventDefault();

          //.. other code

          return false;
    });

One note is using $.post how you are will probably prevent the file from being uploaded.

Here is another SO question on that:

jQuery Ajax File Upload

If you want a non-javascript way to upload without refreshing page, you can also do it though an iframe but the onLoad even may not work in Chrome for that, so it can be hard to tell when the file is uploaded from the client side.

Here is a SO question I answered on that back in 2014

How can I upload files asynchronously?

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • thank you. I managed to get the image to refresh fine using your recommended code. However, the page is still refreshing on submit despite me using prevent default. Any ideas how to fix this? – jake tanner Mar 12 '19 at 01:39
  • @jaketanner - I updated the answer with the most common way, typically `event.preventDefault()` is enough to make the form not sumbit. Dont forget to to add event to the event handler as the first argument `funtion(event)` or `e` if your lazy, but you can also use `return false` at the end of the event handler, so... why not use both. Return false is good if your doing form validation before the submit for example as it both prevents the form and exits the event handler. – ArtisticPhoenix Mar 12 '19 at 02:13
0

You need to use

$('#uploads6').submit(function(e) {
e.preventDefault();
// your code
}

to prevent the submit event from directing to the page that is given in the action value. This is right now the same page since the value of the action attribute is an empty string and therefor the page is refreshed.

Olafant
  • 829
  • 1
  • 7
  • 16
  • thanks but this doesn't seem to stop the page refereshing in my case. – jake tanner Mar 12 '19 at 01:46
  • Don't forget to pass e as parameter to the function that you call on submit. – Olafant Mar 12 '19 at 01:48
  • eh? i'm really sorry I have no idea what that means. I'm only a newbie to Javascript/Jquery. Any chance you could please demonstrate? – jake tanner Mar 12 '19 at 01:53
  • See the update please, especially the function parameter e. – Olafant Mar 12 '19 at 01:58
  • thanks i tried this and e.stopPropagation(); as PaTy suggested and am setting both as parameters. Neither seem to stop the page refresh. Also if i use Javascript:void(0) in between my form action atribute this just stops the form working all together and no image is uploaded. – jake tanner Mar 12 '19 at 02:03
  • I'm talking about the e in `function(e)`. – Olafant Mar 12 '19 at 02:06
  • Try to put the php code in a different file and call that file in your ajax request. – Olafant Mar 12 '19 at 02:20