2013-11-04 22 views
4

如何在不刷新頁面的情況下在同一頁面上提交表單。我知道ajax是可能的,但我並不完美,它使用我的本地編程語言PHP。在同一頁面上發帖而不刷新

HTML

<input type="submit" class="topopup1" value="Preview" onclick="capture();" > 
<form method="POST" enctype="multipart/form-data" id="myForm"> 
<input type="hidden" name="img_val" id="img_val" value="" /> 
</form> 

的Javascript

function capture() { 
$('.showcase').html2canvas({ 
    onrendered: function (canvas) { 
     //Set hidden field's value to image data (base-64 string) 
     $('#img_val').val(canvas.toDataURL("image/png")); 
     //Submit the form manually 
     document.getElementById("myForm").submit();} 
    }); 
    } 

PHP

<?php 


    //Show the image 
    if(isset($_POST['img_val'])){ 
    echo '<img src="'.$_POST['img_val'].'" />'; 


    //Get the base-64 string from data 
    $filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1); 
    //Decode the string 
    $unencodedData=base64_decode($filteredData); 

    //Save the image 
    file_put_contents('img.png', $unencodedData); 
    } 
    ?> 
+2

你不能沒有Ajax做。 –

+0

@PatsyIssa他沒有說他正在尋找另一種解決方案,他只是指出,他的主要技能是PHP。 – DannyThunder

+0

在這裏你可以找到一個準備使用的jquery插件的一些例子也http://malsup.com/jquery/form/ – Petra

回答

2

亞我發現它answer.In我的情況我的PHP響應是image.Now我沙提交表單與AJAX函數.submit與設置target結果show.and現在我不需要在同一頁上的表單動作所以我已經改變了對save.php的行動。

$("#myForm").ajaxForm 
    ({ 
    target: '#preview' 
    }) 
    .submit(); 

HTML

<input type="submit" value="Preview" onclick="capture();" > 
<form method="POST" action="save.php" enctype="multipart/form-data" id="myForm"> 
<input type="hidden" name="img_val" id="img_val" value="" /> 
</form> 
2

使用$.post

// When submitting form below is run 
$("#myForm").submit(function(e) { 
    // prevent form from sending like normal 
    e.preventDefault(); 
    // Send post with ajax, with the postdata of the html form, whatever your page returns you can catch with .done(function(data)); 
    $.post("", $("#myForm").serialize()).done(function(data) { 
     console.log("return data: " + data); 
    }); 
} 
+0

我測試你的代碼,但error.Uncaught TypeError:對象[對象對象]沒有方法'ajaxForm' –

+0

或者表單的ID不匹配,或者使用衝突或損壞的jquery庫。確保僅使用'',並且沒有其他衝突的js庫。 – Timmetje

1

(使用jQuery AJAX並不難!這僅僅是演示,而不是你的代碼的解決方案:

的jQuery/JavaScript的

var myId = "this_is_my_id"; 

var myAjax = $.ajax({ 
    url: "script.php", //The url to your .php script 
    type: "POST", //Method av sending data (POST/GET) 
    data: {id : myid}, //variables to send (if GET it looks like this script.php?id=this_is_my_id) 
    dataType: "json" //The expected datatype of the answer 
}); 

myAjax.done(function(the_data) { 
    // 
    // Place magic code that transform the json data (the_data = javascript object) you got from the script 
    // 
    $("#mydiv").html(your_magic_code); 
}); 

myAjax.fail(function(jqXHR, message) { 
    alert("Failed: " + message); 
}); 

PHP(的script.php):

$id = $_POST['id']; 

//MAGIC PHP CODE 

echo json_encode(MAGIC_CODE_TO_RETURN); //I.e converting an array to json