Partage
  • Partager sur Facebook
  • Partager sur Twitter

Upload Ajax JS Pur

Golmote si tu es là...

Sujet résolu
    29 novembre 2011 à 22:07:16

    Bonjour à toutes et à tous,

    Voilà j'ai commencé à utiliser le plugin Jcrop et maintenant que je sais m'en servir correctement il m'interesse vraiment... pour que mes membres puissent uploader leur avatar et le découper.

    Upload + Découpage + Enregistrement sans recharger la page.... je ne eux pas d'Iframe donc je vise l'Ajax...

    Je cherche donc un plugin d'upload d'images en Ajax... j'en trouve plusieurs mais un seul me convient... très simple d'utilisation... trop même... pas 36 000 fichiers pour le faire fonctionner.

    Ce serais même plus ce qu'on appelle un 'script' qu'un 'plugin'...

    Donc l'upload marche niquel... mais maintenant je veux coupler l'upload à Jcrop.

    Quand j'upload l'image, elle s'enregistre sur le FTP normalement et est affiché sur la page.

    J'ai donc ouvert le fichier .js pour modifier le code pour ajouter des éléments html et lancer le plugin Jcrop sur ces éléments pour que l'image uploadé s'affiche directement avec Jcrop et non... normalement.

    Seul problème... je ne comprend absolument rien au code.

    Je connais vaguement le JS mais la je n'arrive pas à trouver QUAND il récupère l'image créer avec la librairie GD depuis un fichier PHP (censé être appellé en Ajax) ni QUAND il l'affiche....

    Voilà le code du fichier .js :

    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($m(id_element)==null){
    		erro += "The element of 3rd parameter does not exists.\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();
    }
    


    Voilà le code du fichier PHP qui est fournis avec le script :

    <?php
    	function uploadImage($fileName, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH = null){
    		$folder = $relPath;
    		$maxlimit = $maxSize;
    		$allowed_ext = "jpg,jpeg,gif,png,bmp";
    		$match = "";
    		$filesize = $_FILES[$fileName]['size'];
    		if($filesize > 0){	
    			$filename = strtolower($_FILES[$fileName]['name']);
    			$filename = preg_replace('/\s/', '_', $filename);
    		   	if($filesize < 1){ 
    				$errorList[] = "File size is empty.";
    			}
    			if($filesize > $maxlimit){ 
    				$errorList[] = "File size is too big.";
    			}
    			if(count($errorList)<1){
    				$file_ext = preg_split("/\./",$filename);
    				$allowed_ext = preg_split("/\,/",$allowed_ext);
    				foreach($allowed_ext as $ext){
    					if($ext==end($file_ext)){
    						$match = "1"; // File is allowed
    						$NUM = time();
    						$front_name = substr($file_ext[0], 0, 15);
    						$newfilename = $front_name."_".$NUM.".".end($file_ext);
    						$filetype = end($file_ext);
    						$save = $folder.$newfilename;
    						if(!file_exists($save)){
    							list($width_orig, $height_orig) = getimagesize($_FILES[$fileName]['tmp_name']);
    							if($maxH == null){
    								if($width_orig < $maxW){
    									$fwidth = $width_orig;
    								}else{
    									$fwidth = $maxW;
    								}
    								$ratio_orig = $width_orig/$height_orig;
    								$fheight = $fwidth/$ratio_orig;
    								
    								$blank_height = $fheight;
    								$top_offset = 0;
    									
    							}else{
    								if($width_orig <= $maxW && $height_orig <= $maxH){
    									$fheight = $height_orig;
    									$fwidth = $width_orig;
    								}else{
    									if($width_orig > $maxW){
    										$ratio = ($width_orig / $maxW);
    										$fwidth = $maxW;
    										$fheight = ($height_orig / $ratio);
    										if($fheight > $maxH){
    											$ratio = ($fheight / $maxH);
    											$fheight = $maxH;
    											$fwidth = ($fwidth / $ratio);
    										}
    									}
    									if($height_orig > $maxH){
    										$ratio = ($height_orig / $maxH);
    										$fheight = $maxH;
    										$fwidth = ($width_orig / $ratio);
    										if($fwidth > $maxW){
    											$ratio = ($fwidth / $maxW);
    											$fwidth = $maxW;
    											$fheight = ($fheight / $ratio);
    										}
    									}
    								}
    								if($fheight == 0 || $fwidth == 0 || $height_orig == 0 || $width_orig == 0){
    									die("FATAL ERROR REPORT ERROR CODE [add-pic-line-67-orig] to <a href='http://www.atwebresults.com'>AT WEB RESULTS</a>");
    								}
    								if($fheight < 45){
    									$blank_height = 45;
    									$top_offset = round(($blank_height - $fheight)/2);
    								}else{
    									$blank_height = $fheight;
    								}
    							}
    							$image_p = imagecreatetruecolor($fwidth, $blank_height);
    							$white = imagecolorallocate($image_p, $colorR, $colorG, $colorB);
    							imagefill($image_p, 0, 0, $white);
    							switch($filetype){
    								case "gif":
    									$image = @imagecreatefromgif($_FILES[$fileName]['tmp_name']);
    								break;
    								case "jpg":
    									$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
    								break;
    								case "jpeg":
    									$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
    								break;
    								case "png":
    									$image = @imagecreatefrompng($_FILES[$fileName]['tmp_name']);
    								break;
    							}
    							@imagecopyresampled($image_p, $image, 0, $top_offset, 0, 0, $fwidth, $fheight, $width_orig, $height_orig);
    							switch($filetype){
    								case "gif":
    									if(!@imagegif($image_p, $save)){
    										$errorList[]= "PERMISSION DENIED [GIF]";
    									}
    								break;
    								case "jpg":
    									if(!@imagejpeg($image_p, $save, 100)){
    										$errorList[]= "PERMISSION DENIED [JPG] : ".$image_p." | ".$save;
    									}
    								break;
    								case "jpeg":
    									if(!@imagejpeg($image_p, $save, 100)){
    										$errorList[]= "PERMISSION DENIED [JPEG]";
    									}
    								break;
    								case "png":
    									if(!@imagepng($image_p, $save, 0)){
    										$errorList[]= "PERMISSION DENIED [PNG]";
    									}
    								break;
    							}
    							@imagedestroy($filename);
    						}else{
    							$errorList[]= "CANNOT MAKE IMAGE IT ALREADY EXISTS";
    						}	
    					}
    				}		
    			}
    		}else{
    			$errorList[]= "NO FILE SELECTED";
    		}
    		if(!$match){
    		   	$errorList[]= "File type isn't allowed: $filename";
    		}
    		if(sizeof($errorList) == 0){
    			return $fullPath.$newfilename;
    		}else{
    			$eMessage = array();
    			for ($x=0; $x<sizeof($errorList); $x++){
    				$eMessage[] = $errorList[$x];
    			}
    		   	return $eMessage;
    		}
    	}
    	
    	$filename = strip_tags($_REQUEST['filename']);
    	$maxSize = strip_tags($_REQUEST['maxSize']);
    	$maxW = strip_tags($_REQUEST['maxW']);
    	$fullPath = strip_tags($_REQUEST['fullPath']);
    	$relPath = strip_tags($_REQUEST['relPath']);
    	$colorR = strip_tags($_REQUEST['colorR']);
    	$colorG = strip_tags($_REQUEST['colorG']);
    	$colorB = strip_tags($_REQUEST['colorB']);
    	$maxH = strip_tags($_REQUEST['maxH']);
    	$filesize_image = $_FILES[$filename]['size'];
    	if($filesize_image > 0){
    		$upload_image = uploadImage($filename, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH);
    		if(is_array($upload_image)){
    			foreach($upload_image as $key => $value) {
    				if($value == "-ERROR-") {
    					unset($upload_image[$key]);
    				}
    			}
    			$document = array_values($upload_image);
    			for ($x=0; $x<sizeof($document); $x++){
    				$errorList[] = $document[$x];
    			}
    			$imgUploaded = false;
    		}else{
    			$imgUploaded = true;
    		}
    	}else{
    		$imgUploaded = false;
    		$errorList[] = "File Size Empty";
    	}
    ?>
    <?php
    	if($imgUploaded){
    		echo '<img src="/php_ajax_image_upload/images/success.gif" width="16" height="16" border="0" style="marin-bottom: -4px;" /> Success!<br /><img src="'.$upload_image.'" border="0" />';
    	}else{
    		echo '<img src="/php_ajax_image_upload/images/error.gif" width="16" height="16px" border="0" style="marin-bottom: -3px;" /> Error(s) Found: ';
    		foreach($errorList as $value){
    	    		echo $value.', ';
    		}
    	}
    ?>
    


    Et voilà le code html :

    <fieldset>
    			<legend>Choisissez une image (Extensions autorisées : <em><b>JPG</b></em>)</legend>
    			<form action="Upload/scripts/ajaxupload.php" method="post" name="unobtrusive" id="unobtrusive" enctype="multipart/form-data">
    				<input type="hidden" name="maxSize" value="9999999999" />
    				<input type="hidden" name="maxW" value="1920" />
    				<input type="hidden" name="fullPath" value="http://vdmv.fr/association/maps/images/uploads/" />
    				<input type="hidden" name="relPath" value="../../images/uploads/" />
    				<input type="hidden" name="colorR" value="255" />
    				<input type="hidden" name="colorG" value="255" />
    				<input type="hidden" name="colorB" value="255" />
    				<input type="hidden" name="maxH" value="1080" />
    				<input type="hidden" name="filename" value="filename" />
    				<p>
    					<input type="file" name="filename" id="filename" value="filename" onchange="ajaxUpload(this.form,'Upload/scripts/ajaxupload.php?filename=filename&amp;maxSize=9999999999&amp;maxW=1920&amp;fullPath=http://vdmv.fr/association/maps/images/uploads/&amp;relPath=../../images/uploads/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=1080','upload_area','File Uploading Please Wait...&lt;br/&gt;&lt;img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' /&gt;','&lt;img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /&gt; Erreur lors de l\'upload, vérifiez les paramètres et les infos du chemin dans le code source.'); init_Jcrop(); return false;" />
    				</p>
    				<noscript>
    					<p>
    						<input type="submit" name="submit" value="Upload Image" />
    					</p>
    				</noscript>
    			</form>
    		</fieldset>
    		<div id="upload_area">
    			
    		</div>
    


    Je reste à disposition si besoin d'autres infos.

    Merci d'avance pour votre précieuse aide.

    Golmote si tu es là je t'en supplie aide moi ^^'
    • Partager sur Facebook
    • Partager sur Twitter
      29 novembre 2011 à 23:32:53

      Je croyais que tu ne voulais pas d'iframe (cf ligne 40) ? :-°

      • Partager sur Facebook
      • Partager sur Twitter
        30 novembre 2011 à 1:21:41

        Bah j'aime pas tellement les iframes et puis j'ai jeté un coup d'oeil sur firebug depuis l'arrivée de la page jusqu'à la fin de l'upload... je vois nulle part une Iframe arriver...

        Si tu veux jeter un coup d'oeil par toi-même : Page de test

        Je voudrais en gros arriver à ce code html :

        <div id="upload_area">
        	<form action="Jcrop.php" method="post" onsubmit="return checkCoords();">
        		<input type="hidden" id="x" name="x" />
        		<input type="hidden" id="y" name="y" />
        		<input type="hidden" id="w" name="w" />
        		<input type="hidden" id="h" name="h" />
        		
        		<!-- Ici mettre l'url vers l'image uploadée !-->
        		<img src="" alt="" id="cropbox" />
        		
        		<input type="submit" value="Valider" />
        	</form>
        </div>
        


        Une fois le code html mis en place en JS, il faut que j'éxécute ce code jQuery :

        $('#cropbox').Jcrop(
        {
        	bgColor: 'black',
        	bgOpacity: 0.5,
        	minSize: [100, 100],
        	maxSize: [800, 600],
        	boxWidth: 800,
        	boxHeight: 600,
        	onSelect: updateCoords
        });
        $('.jcrop-holder').click(function()
        {
        	if(click == 0)
        	{
        		click = 1;
        	}
        });
        


        Si tu as une idée de comment fonctionne le script déjà ce serais pas mal ^^
        Et si tu sais comment arriver au résultat que je souhaite obtenir ce serait encore mieux lol
        • Partager sur Facebook
        • Partager sur Twitter
          30 novembre 2011 à 8:04:52

          Et pourtant :

          Image utilisateur



          Bref. A la ligne 175 du PHP, t'as le code HTML de succès.

          Et je pense que c'est la ligne 53 du JS qui le fait apparaître sur la page.
          Donc tu peux appeler ton crop entre la ligne 53 et la ligne 54.
          • Partager sur Facebook
          • Partager sur Twitter
            30 novembre 2011 à 13:16:29

            EDIT : Moi je ne l'avais pas sur firebug ^^ Ou sinon j'étais pas dans le bon timing lol


            Pour le code html de succès c'est bon =D Merci =D

            Pour le code JavaScript ça se corse :s

            Voila la bout de code JS :

            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;
            	// CODE JS AU MOMENT DE L'AFFICHAGE SI SUCCES !
            	
            	$('#cropbox').Jcrop(
            	{
            		bgColor: 'black',
            		bgOpacity: 0.5,
            		// aspectRatio: 1,
            		minSize: [100, 100],
            		maxSize: [800, 600],
            		boxWidth: 800,
            		boxHeight: 600,
            		onSelect: updateCoords
            	});
            	$('.jcrop-holder').click(function()
            	{
            		if(click == 0)
            		{
            			click = 1;
            		}
            	});
            	
            	//FIN DU CODE
            	$m('ajax-temp').src = cross;
            	if(detectWebKit){
            		remove($m('ajax-temp'));
            	}
            	else
            	{
            		setTimeout(function(){ remove($m('ajax-temp'))}, 250);
            	}
            }
            


            J'upload l'image, elle apparait correctement (vérifié sur Firebug), sauf que la le plugin Jcrop ne se lance pas... enfin visiblement pas ^^

            Normalement quand je clique sur l'image je devrait pouvoir avoir un truc dans le genre (Plugin Jcrop) :

            Image utilisateur

            Seulement la rien ne se passe...
            Et aucune erreur dans FireBug...

            Par contre, dans mes tests avant de poster sur le forum, j'avais essayé d'ajouter un petit code en jQuery et Firebug m'avait retourné une erreur dans le genre : $ is undefined... en gros jQuery n'était pas "lancé" si j'puis dire.

            Là il ne me le dit pas mais je soupçonne une même erreur ^^

            Aurais-tu une solution ? :s

            JavaScript :
            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($m(id_element)==null){
            		erro += "The element of 3rd parameter does not exists.\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;
            		// CODE JS AU MOMENT DE L'AFFICHAGE SI SUCCES !
            		
            		$('#cropbox').Jcrop(
            		{
            			bgColor: 'black',
            			bgOpacity: 0.5,
            			// aspectRatio: 1,
            			minSize: [100, 100],
            			maxSize: [800, 600],
            			boxWidth: 800,
            			boxHeight: 600,
            			onSelect: updateCoords
            		});
            		$('.jcrop-holder').click(function()
            		{
            			if(click == 0)
            			{
            				click = 1;
            			}
            		});
            		
            		//FIN DU CODE
            		$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();
            }
            


            PHP :
            <?php
            	function uploadImage($fileName, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH = null){
            		$folder = $relPath;
            		$maxlimit = $maxSize;
            		$allowed_ext = "jpg,jpeg,gif,png,bmp";
            		$match = "";
            		$filesize = $_FILES[$fileName]['size'];
            		if($filesize > 0){	
            			$filename = strtolower($_FILES[$fileName]['name']);
            			$filename = preg_replace('/\s/', '_', $filename);
            		   	if($filesize < 1){ 
            				$errorList[] = "File size is empty.";
            			}
            			if($filesize > $maxlimit){ 
            				$errorList[] = "File size is too big.";
            			}
            			if(count($errorList)<1){
            				$file_ext = preg_split("/\./",$filename);
            				$allowed_ext = preg_split("/\,/",$allowed_ext);
            				foreach($allowed_ext as $ext){
            					if($ext==end($file_ext)){
            						$match = "1"; // File is allowed
            						$NUM = time();
            						$front_name = substr($file_ext[0], 0, 15);
            						$newfilename = $front_name."_".$NUM.".".end($file_ext);
            						$filetype = end($file_ext);
            						$save = $folder.$newfilename;
            						if(!file_exists($save)){
            							list($width_orig, $height_orig) = getimagesize($_FILES[$fileName]['tmp_name']);
            							if($maxH == null){
            								if($width_orig < $maxW){
            									$fwidth = $width_orig;
            								}else{
            									$fwidth = $maxW;
            								}
            								$ratio_orig = $width_orig/$height_orig;
            								$fheight = $fwidth/$ratio_orig;
            								
            								$blank_height = $fheight;
            								$top_offset = 0;
            									
            							}else{
            								if($width_orig <= $maxW && $height_orig <= $maxH){
            									$fheight = $height_orig;
            									$fwidth = $width_orig;
            								}else{
            									if($width_orig > $maxW){
            										$ratio = ($width_orig / $maxW);
            										$fwidth = $maxW;
            										$fheight = ($height_orig / $ratio);
            										if($fheight > $maxH){
            											$ratio = ($fheight / $maxH);
            											$fheight = $maxH;
            											$fwidth = ($fwidth / $ratio);
            										}
            									}
            									if($height_orig > $maxH){
            										$ratio = ($height_orig / $maxH);
            										$fheight = $maxH;
            										$fwidth = ($width_orig / $ratio);
            										if($fwidth > $maxW){
            											$ratio = ($fwidth / $maxW);
            											$fwidth = $maxW;
            											$fheight = ($fheight / $ratio);
            										}
            									}
            								}
            								if($fheight == 0 || $fwidth == 0 || $height_orig == 0 || $width_orig == 0){
            									die("FATAL ERROR REPORT ERROR CODE [add-pic-line-67-orig] to <a href='http://www.atwebresults.com'>AT WEB RESULTS</a>");
            								}
            								if($fheight < 45){
            									$blank_height = 45;
            									$top_offset = round(($blank_height - $fheight)/2);
            								}else{
            									$blank_height = $fheight;
            								}
            							}
            							$image_p = imagecreatetruecolor($fwidth, $blank_height);
            							$white = imagecolorallocate($image_p, $colorR, $colorG, $colorB);
            							imagefill($image_p, 0, 0, $white);
            							switch($filetype){
            								case "gif":
            									$image = @imagecreatefromgif($_FILES[$fileName]['tmp_name']);
            								break;
            								case "jpg":
            									$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
            								break;
            								case "jpeg":
            									$image = @imagecreatefromjpeg($_FILES[$fileName]['tmp_name']);
            								break;
            								case "png":
            									$image = @imagecreatefrompng($_FILES[$fileName]['tmp_name']);
            								break;
            							}
            							@imagecopyresampled($image_p, $image, 0, $top_offset, 0, 0, $fwidth, $fheight, $width_orig, $height_orig);
            							switch($filetype){
            								case "gif":
            									if(!@imagegif($image_p, $save)){
            										$errorList[]= "PERMISSION DENIED [GIF]";
            									}
            								break;
            								case "jpg":
            									if(!@imagejpeg($image_p, $save, 100)){
            										$errorList[]= "PERMISSION DENIED [JPG] : ".$image_p." | ".$save;
            									}
            								break;
            								case "jpeg":
            									if(!@imagejpeg($image_p, $save, 100)){
            										$errorList[]= "PERMISSION DENIED [JPEG]";
            									}
            								break;
            								case "png":
            									if(!@imagepng($image_p, $save, 0)){
            										$errorList[]= "PERMISSION DENIED [PNG]";
            									}
            								break;
            							}
            							@imagedestroy($filename);
            						}else{
            							$errorList[]= "CANNOT MAKE IMAGE IT ALREADY EXISTS";
            						}	
            					}
            				}		
            			}
            		}else{
            			$errorList[]= "NO FILE SELECTED";
            		}
            		if(!$match){
            		   	$errorList[]= "File type isn't allowed: $filename";
            		}
            		if(sizeof($errorList) == 0){
            			return $fullPath.$newfilename;
            		}else{
            			$eMessage = array();
            			for ($x=0; $x<sizeof($errorList); $x++){
            				$eMessage[] = $errorList[$x];
            			}
            		   	return $eMessage;
            		}
            	}
            	
            	$filename = strip_tags($_REQUEST['filename']);
            	$maxSize = strip_tags($_REQUEST['maxSize']);
            	$maxW = strip_tags($_REQUEST['maxW']);
            	$fullPath = strip_tags($_REQUEST['fullPath']);
            	$relPath = strip_tags($_REQUEST['relPath']);
            	$colorR = strip_tags($_REQUEST['colorR']);
            	$colorG = strip_tags($_REQUEST['colorG']);
            	$colorB = strip_tags($_REQUEST['colorB']);
            	$maxH = strip_tags($_REQUEST['maxH']);
            	$filesize_image = $_FILES[$filename]['size'];
            	if($filesize_image > 0){
            		$upload_image = uploadImage($filename, $maxSize, $maxW, $fullPath, $relPath, $colorR, $colorG, $colorB, $maxH);
            		if(is_array($upload_image)){
            			foreach($upload_image as $key => $value) {
            				if($value == "-ERROR-") {
            					unset($upload_image[$key]);
            				}
            			}
            			$document = array_values($upload_image);
            			for ($x=0; $x<sizeof($document); $x++){
            				$errorList[] = $document[$x];
            			}
            			$imgUploaded = false;
            		}else{
            			$imgUploaded = true;
            		}
            	}else{
            		$imgUploaded = false;
            		$errorList[] = "File Size Empty";
            	}
            ?>
            <?php
            	if($imgUploaded)
            	{
            		echo '<form action="Jcrop.php" method="post" onsubmit="return checkCoords();">
            			<input type="hidden" id="x" name="x" />
            			<input type="hidden" id="y" name="y" />
            			<input type="hidden" id="w" name="w" />
            			<input type="hidden" id="h" name="h" />
            			
            			<img src="'.$upload_image.'" alt="" id="cropbox" />
            			
            			<input type="submit" value="Valider" />
            		</form>';
            	}
            	else
            	{
            		echo '<img src="/php_ajax_image_upload/images/error.gif" width="16" height="16px" border="0" style="marin-bottom: -3px;" /> Error(s) Found: ';
            		foreach($errorList as $value)
            		{
            	    		echo $value.', ';
            		}
            	}
            ?>
            


            test.php :
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            	<head>
            		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            		<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
            		<script type="text/javascript" src="http://vdmv.fr/js/facebox.js"></script>
            		<script type="text/javascript" src="http://vdmv.fr/js/jquery.color.js"></script>
            		<script type="text/javascript" src="http://vdmv.fr/js/jquery.Jcrop.js"></script>
            		<script type="text/javascript" src="Upload/scripts/ajaxupload.js"></script>
            		<link rel="stylesheet" href="http://vdmv.fr/css/facebox.css" />
            		<link rel="stylesheet" href="http://vdmv.fr/css/jquery.Jcrop.css" />
            		<link href="Upload/css/styles.css" rel="stylesheet" type="text/css" media="all" />
            		<title>Avatar</title>
            		<script type="text/javascript">
            		var nombre = 0;
            		var click = 0;
            		$(document).ready(function()
            		{
            			$('#cropbox').Jcrop(
            			{
            				bgColor: 'black',
            				bgOpacity: 0.5,
            				// aspectRatio: 1,
            				minSize: [100, 100],
            				maxSize: [800, 600],
            				boxWidth: 800,
            				boxHeight: 600,
            				onSelect: updateCoords
            			});
            			$('.jcrop-holder').click(function()
            			{
            				if(click == 0)
            				{
            					click = 1;
            				}
            			});
            		});
            		
            		function updateCoords(c)
            		{
            			$('#x').val(c.x);
            			$('#y').val(c.y);
            			$('#w').val(c.w);
            			$('#h').val(c.h);
            			click = 1;
            		}
            
            		function checkCoords()
            		{
            			if(click == 1)
            			{
            				$.post("Jcrop.php", {"x": $('#x').val(), "y": $('#y').val(), "w": $('#w').val(), "h": $('#h').val()}, function(data)
            				{
            					if(data.erreur == 'ok')
            					{
            						nombre++;
            						if(nombre == 1)
            						{
            							$('body').prepend('<img src="images/uploads/raptor_jcrop.jpg" alt="" style="display: none;" id="final" />').find('img#final').show('fade');
            						}
            						else
            						{
            							var stamp = new Date().getTime();
            							$('#final').attr('src', 'images/uploads/raptor_jcrop.jpg?'+stamp);
            						}
            					}
            					else
            					{
            						alert('none');
            					}
            				}, "json");
            				return false;
            			}
            			else
            			{
            				alert('Vous devez séléctionner la zone à découper en cliquant sur l\'image avant de valider.');
            				return false;
            			}
            		}
            		</script>
            	</head>
            	<body>
            		<fieldset>
            			<legend>Choisissez une image (Extensions autorisées : <em><b>JPG</b></em>)</legend>
            			<form action="Upload/scripts/ajaxupload.php" method="post" name="unobtrusive" id="unobtrusive" enctype="multipart/form-data">
            				<input type="hidden" name="maxSize" value="9999999999" />
            				<input type="hidden" name="maxW" value="1920" />
            				<input type="hidden" name="fullPath" value="http://vdmv.fr/association/maps/images/uploads/" />
            				<input type="hidden" name="relPath" value="../../images/uploads/" />
            				<input type="hidden" name="colorR" value="255" />
            				<input type="hidden" name="colorG" value="255" />
            				<input type="hidden" name="colorB" value="255" />
            				<input type="hidden" name="maxH" value="1080" />
            				<input type="hidden" name="filename" value="filename" />
            				<p>
            					<input type="file" name="filename" id="filename" value="filename" onchange="ajaxUpload(this.form,'Upload/scripts/ajaxupload.php?filename=filename&amp;maxSize=9999999999&amp;maxW=1920&amp;fullPath=http://vdmv.fr/association/maps/images/uploads/&amp;relPath=../../images/uploads/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=1080','upload_area','File Uploading Please Wait...&lt;br/&gt;&lt;img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' /&gt;','&lt;img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /&gt; Erreur lors de l\'upload, vérifiez les paramètres et les infos du chemin dans le code source.'); init_Jcrop(); return false;" />
            				</p>
            				<noscript>
            					<p>
            						<input type="submit" name="submit" value="Upload Image" />
            					</p>
            				</noscript>
            			</form>
            		</fieldset>
            		<div id="upload_area"></div>
            	</body>
            </html>
            
            • Partager sur Facebook
            • Partager sur Twitter
              30 novembre 2011 à 20:14:37

              Où est définie updateCoords ?
              • Partager sur Facebook
              • Partager sur Twitter
                30 novembre 2011 à 21:29:47

                Fichier test.php ligne 39...
                • Partager sur Facebook
                • Partager sur Twitter
                  30 novembre 2011 à 21:33:17

                  Ok.

                  Si tu fais un... alert($('#cropbox').length), avant le code de cropbox, ça t'affiche quoi ?
                  • Partager sur Facebook
                  • Partager sur Twitter
                    30 novembre 2011 à 21:37:39

                    ça m'affiche :

                    0

                    Je crois que le code n'est pas pris en compte par le DOM je me trompe ?
                    • Partager sur Facebook
                    • Partager sur Twitter
                      30 novembre 2011 à 21:45:52

                      On dirait, en effet.

                      Et si tu mets...

                      setTimeout(function() {
                          alert($('#cropbox').length);
                      },100);
                      


                      ?
                      • Partager sur Facebook
                      • Partager sur Twitter
                        30 novembre 2011 à 21:52:48

                        Ah... je l'ai mis à 1000 pour être sur ^^

                        Il me retourn maintenant 1 donc c'est bon... je crois que je viens de comprendre...

                        if(detectWebKit)
                        {
                        	remove($m('ajax-temp'));
                        }
                        else
                        {
                        	setTimeout(function(){ remove($m('ajax-temp'))}, 250);
                        }
                        


                        Si j'ai bien compris le code, il vire l'iframe et met son contenu dans le DOM au bout de 0.25 secondes si WebKit n'est pas présent c'est bien sa ?

                        Donc en gros je met mon code qui lance le plugin en setTimeout ?
                        • Partager sur Facebook
                        • Partager sur Twitter
                          30 novembre 2011 à 22:01:22

                          Le problème n'a, selon moi, pas de rapport avec le code que tu cites.

                          Mais il est de notoriété public que lors d'un innerHTML, le navigateur attend parfois de "récupérer la main" avant de faire la modification dans le DOM.
                          Donc en délayant légèrement ton appel aux actions du crop, tu dois pouvoir lui laisser le temps de faire cette mise à jour.
                          • Partager sur Facebook
                          • Partager sur Twitter
                            30 novembre 2011 à 22:38:02

                            Ah d'accord =)

                            Et bien j'ai une bonne nouvelle, ça fonctionne parfaitement =D

                            Merci encore à toi Golmote.
                            Encore une fois tu m'as prouvé que tu es le meilleur pro en JS pur que j'connaisse =D (C'est surement du au fait que je n'soit pas terrible dans ce domaine x'D)

                            Merci encore en tout cas, sujet résolu =)
                            • Partager sur Facebook
                            • Partager sur Twitter
                              1 décembre 2011 à 6:58:19

                              Merci du compliment.

                              Néanmoins à l'avenir, tu peux t'abstenir de me mentionner dans ton titre ou ton premier message. Ce n'est nullement la présence de mon pseudo qui va m'inciter à lire un topic.

                              Bonne continuation ;)
                              • Partager sur Facebook
                              • Partager sur Twitter

                              Upload Ajax JS Pur

                              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
                              × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
                              • Editeur
                              • Markdown