2014-01-15 23 views
0

這是我的形式 -如何通過onChange()檢查圖像文件後提交與jQuery的表單?

<form id="imgUpIcn" class="imgUpIcn" enctype="multipart/form-data" method="post" action="myfile.php"> 
<div id="upload-file-container"> 
<input type="file" name="uploadedImagefile" id="myImageFile" onchange="photoUpInit(event,this,'loadingImg','cropPhLayer')" /> 
</div> 
</form> 

這是我photoUpInit()功能 -

function photoUpInit(evt, obj, loaderID, cropLBID) { 

var ext = obj.value.split('.').pop().toLowerCase(), vStat = true; 
if (window.File && window.FileReader && window.FileList) { 
    var e = evt || window.event, files = e.target.files, fSize = Math.round((parseInt(files[0].size)/2048) * 100)/100; 
    if (fSize > 2048) 
     vStat = false; 
} 
if (ext != 'png' && ext != 'jpg' && ext != 'jpeg' && ext != 'gif') 
    vStat = false; 
if (vStat) { 
    document.getElementById('uplErr').style.display = "none"; 
    document.getElementById(loaderID).style.display = 'block'; 
      //Submitting form here 
    obj.form.submit(); 

} else { 
    document.getElementById(loaderID).style.display = 'none'; 
    document.getElementById('uplErr').style.display = "block"; 
} 
} 

現在,當執行表單動作我的文件得到上載到服務器上,但我想從一開始回調PHP文件,而不是我重定向到PHP頁面。

這裏是我的PHP文件 -

<?php 
if (isset($_FILES['uploadedImagefile']['tmp_name'])) 
{ 


$target_path = "../uploads/"; 

$target_path = $target_path . "tmp"; 

if(move_uploaded_file($_FILES['uploadedImagefile']['tmp_name'], $target_path)) { 
    echo "The file ". basename($_FILES['uploadedImagefile']['name']). 
    " has been uploaded"; 
} else{ 
    echo "There was an error uploading the file, please try again!"; 
} 
} 

我用它來獲取回調,但它不是working-

$('#imgUpIcn').on('submit', (function(e) { 
    e.preventDefault(); 
    $.ajax({ 
     type : "POST", 
     url : $(this).attr('action'), 
     data : $(this).serialize(), 
     success : function(data) { 
      $("#myModal").dialog("close"); 
     }, 
     error : function(data) { 
      console.log("error"); 
      console.log(data); 
     } 
    }); 
})); 
+0

[表單提交與AJAX傳遞表單數據到PHP沒有頁面刷新](http://stackoverflow.com/questions/16616250/form-submit-with-ajax-passing-form-data-to-php -without-page-refresh) – Ryan

+0

我沒有像這個問題那樣的提交按鈕。 – Mihir

回答

0

考慮到它是上傳文件的PHP文件已經試過了,你應該做一個php頭重定向回到表單頁面,並帶有成功或失敗的消息。事情是這樣的:

<?php 
if (isset($_FILES['uploadedImagefile']['tmp_name'])) 
{ 


$target_path = "../uploads/"; 

$target_path = $target_path . "tmp"; 

if(move_uploaded_file($_FILES['uploadedImagefile']['tmp_name'], $target_path)) { 
    $message = "The file ". basename($_FILES['uploadedImagefile']['name']). 
    " has been uploaded"; 
} else{ 
    $message = "There was an error uploading the file, please try again!"; 
} 

header('Location: back/to/your/form/file?message=' . $message); 
} 

這到底應該上傳的文件,並返回到你的表單頁面這在我oppinion也應該是一個PHP文件,這樣就可以解釋的鏈接$ _GET變量。

+0

我想在我的Ajax成功函數中獲得結果。 – Mihir

+0

然後,您需要使用另一種方法,通過ajax將圖像發送到php腳本,這稱爲ajaxupload。谷歌它,因爲我們不允許提供圖書館的答案。 –