Hi. In short, how can I make this javascript to refresh the page when uploading is done ? :)

function $m(theVar){
	return document.getElementById(theVar)
}
function remove(theVar){
	var theParent = theVar.parentNode;
	theParent.removeChild(theVar);
}
function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	    obj.addEventListener(evType, fn, true)
	if(obj.attachEvent)
	    obj.attachEvent("on"+evType, fn)
}
function removeEvent(obj, type, fn){
	if(obj.detachEvent){
		obj.detachEvent('on'+type, fn);
	}else{
		obj.removeEventListener(type, fn, false);
	}
}
function isWebKit(){
	return RegExp(" AppleWebKit/").test(navigator.userAgent);
}
function ajaxUpload(form,url_action,id_element,html_show_loading,html_error_http){
	var detectWebKit = isWebKit();
	form = typeof(form)=="string"?$m(form):form;
	var erro="";
	if(form==null || typeof(form)=="undefined"){
		erro += "The form of 1st parameter does not exists.\n";
	}else if(form.nodeName.toLowerCase()!="form"){
		erro += "The form of 1st parameter its not a form.\n";
	}

	if(erro.length>0){
		alert("Error in call ajaxUpload:\n" + erro);
		return;
	}
	var iframe = document.createElement("iframe");
	iframe.setAttribute("id","ajax-temp");
	iframe.setAttribute("name","ajax-temp");
	iframe.setAttribute("width","0");
	iframe.setAttribute("height","0");
	iframe.setAttribute("border","0");
	iframe.setAttribute("style","width: 0; height: 0; border: none;");
	form.parentNode.appendChild(iframe);
	window.frames['ajax-temp'].name="ajax-temp";
	var doUpload = function(){
		removeEvent($m('ajax-temp'),"load", doUpload);
		var cross = "javascript: ";
		cross += "window.parent.$m('"+id_element+"').innerHTML = document.body.innerHTML; void(0);";
		$m(id_element).innerHTML = html_error_http;
		$m('ajax-temp').src = cross;
		if(detectWebKit){
        	remove($m('ajax-temp'));
        }else{
        	setTimeout(function(){ remove($m('ajax-temp'))}, 250);
		}
    }
	addEvent($m('ajax-temp'),"load", doUpload);
	form.setAttribute("target","ajax-temp");
	form.setAttribute("action",url_action);
	form.setAttribute("method","post");
	form.setAttribute("enctype","multipart/form-data");
	form.setAttribute("encoding","multipart/form-data");
	if(html_show_loading.length > 0){
		$m(id_element).innerHTML = html_show_loading;
	}
	form.submit();
}

If you need the php file:

<?php
include "config.php";
@header("Content-Type: text/html; charset=windows-1251");
$fileN = $_REQUEST['pic'];
if (isset($fileN)){
    $allowed_ext = "jpg,jpeg,gif,png";
    $filesize = $_FILES['pic']['size'];
    $maxlimit = 9999999999;
    if($filesize > 0){
          $filename = strtolower($_FILES['pic']['name']);
          $filename = preg_replace('/\s/', '_', $filename);
		   	if($filesize < 1){
				$errorList[] = "Empty file!";
                echo "Empty file!";
			}
			if($filesize > $maxlimit){
				$errorList[] = "File too big!";
                 echo "File too big! (1MB max)";
			}
              if(count($errorList)<1){
                $file_ext = preg_split("/\./",$filename);
				$allowed_ext = preg_split("/\,/",$allowed_ext);
                $rand = rand(100,999).rand(10,99).rand(100,500);
                $front_name = substr($file_ext[0], 0, 15);
                $newfilename = $front_name."_".$rand.".".end($file_ext);
                foreach($allowed_ext as $ext){
                  if($ext==end($file_ext)){
                  $data = date("d.m.Y");
                  $zapis = mysqlCountR("mmvet_obqvi", "date = '$data' AND userip = '$ip' AND active = 0");
                    if($zapis > 0){
                      $picsB = mysqlGet("mmvet_obqvi", "*", 0, "date = '$data' AND userip = '$ip' AND active = 0");
                      $allpics = $picsB['pics'];
                      $picsEx = explode(",", $allpics);
                        if(sizeof($picsEx) == 5){
                            echo "You can't upload more than 5 pictures!";
                        }else{
                            $plusPic = $allpics.",".$newfilename;
                            mysqlSet("mmvet_obqvi", "pics", "$plusPic", "date = '$data' AND userip = '$ip' AND active = 0", "~ ");
                        }
                    }else{
                        mysqlAdd("mmvet_obqvi", "null,null,null,null,null,null,$data,null,null,null,null,null,null,null,null,$newfilename,$ip,0");
                    }
                        if(sizeof($picsEx) <= 5 ){
                            copy($_FILES['pic']['tmp_name'], "_data/uploads/".$newfilename);
                            saveThumb("_data/uploads/".$newfilename, 283, 212, "_data/uploads/thumbbig_".$newfilename, end($file_ext));
                            saveThumb("_data/uploads/".$newfilename, 108, 81, "_data/uploads/thumbsmall_".$newfilename, end($file_ext));
                            unlink("_data/uploads/".$newfilename);
                            $imgUploaded = true;;
                        }
                  }
                }

              }else{
                $imgUploaded = false;
              }
    }else{
      echo "No file chosen!";
      $imgUploaded = false;
    }
}else{
  echo "No file!";
}
?>

Dani AI

Generated

The existing routine uses a hidden iframe to perform the multipart upload and then tries to inject HTML back into the parent via a javascript: URL. That can be brittle (and is the kind of thing that started failing for some people in modern Chrome builds — see ). Two robust, cross‑browser approaches:

  1. Use postMessage from the iframe to tell the parent the upload finished (best if the upload target and parent are same origin or you check origins). Parent listens for the message and calls reload + cleans up the iframe.
// parent page: listen for completion and reload
window.addEventListener('message', function(e) {
  if (e.origin !== window.location.origin) return; // strict check for security
  if (e.data === 'upload:done') {
    var f = document.getElementById('ajax-temp');
    if (f && f.parentNode) f.parentNode.removeChild(f);
    window.location.reload();
  }
}, false);

Have the upload response (the small HTML returned into the hidden iframe) post that message:

<!doctype html>
<html><body>
<script>
  try { window.parent.postMessage('upload:done', '*'); } catch(e) {}
</script>
</body></html>

(Use a specific origin instead of '*' when you can, and keep the parent check above.)

  1. If you can rely on modern browsers, avoid the iframe entirely and use XHR2 + FormData. Submit the form with FormData and in the XHR onload/onreadystatechange handler call window.location.reload() when the status is successful. This follows @anish.anick’s idea but uses FormData for file uploads.

Troubleshooting tips: verify same‑origin rules, check the browser console for cross‑frame script/CSP errors, ensure the server returns a minimal HTML response (and not plain text) if you use the iframe/postMessage route, and always remove the temporary iframe to avoid DOM clutter. As noted, if your goal is to stay AJAX‑y, prefer XHR/FormData; use the iframe/postMessage trick only for older browser fallbacks.

Recommended Answers

All 4 Replies

Catch the ajax on complete state when the readyState property becomes 4, after that execute the javascript code window.location.reload() to refresh/reloading the page

Regards
Anish

Yeah. But here I don't have an XMLHTTP Object :-/ And I don't know how the javascript understands when the uploading is done :-O

I believe the whole point of this code is to avoid refreshing the page by loading the image in the hidden iframe, as you cannot really use Ajax to upload an image.

So, if you are going to refresh the page, I would use a simpler method, like sending the results of your upload form back to the top of the page and process it.

Hay trevata,

This script stopped working on the chrome update in version 73, which is the most current version at that time.

Any idea what that might be?

I use this script in all my projects but after this chrome actualization it stopped working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.