2017-08-30 113 views
0

我使用jQuery將表單從側邊欄加載到主頁面。現在我想用jQuery來提交這個表單,但是我很難做到這一點。我使用相同的jQuery代碼來提交未加載jQuery的表單。希望有人能看到我做錯了什麼。jQuery無法提交使用jQuery加載的表單

如何修改以下代碼以便提交表單?

LINK裝入的FORM:

<a href="#" id="link1">Exam1</a> 

JQUERY裝入的FORM:

$(document).ready(function(){ 
    $('#link1').click(function(){ 
     $('#show').load('exam.php'); 

    });  
}); 

FORM:

<form action="form.php" id="exam" method="post" > 
    <input type="text" name="new_exam"/> 
    <button id="sub" name="" style="color:#e75618; padding:5px 66px" class="btn btn-default" ><b>Add Exam</b></button> 
</form> 

jQuery來提交表單:

$("#sub").click(function() { 
    $.post($("#exam").attr("action"), $("#exam").serialize(), function(info){ $("#result").html(info); }); 
    clearInput(); 
    $("html, body").animate({ scrollTop: 0 }, "slow"); 
    }); 

    $("#exam").submit(function() { 
     return false; 
}); 

function clearInput() { 

    $("#exam")[0].reset(); 

PHP:

$new_exam = $_POST['new_exam']; 

$insert_exam = "insert into examination (exam_title) values ('$new_exam')"; 

$run_exam = mysqli_query($con, $insert_exam); 
if($run_exam){ 
    echo "New Exam inserted"; 
} 
+1

你會得到什麼錯誤? – hallleron

+0

我沒有得到任何錯誤。 – Oponjous

+0

Exam.php只包含您提供的表單嗎?還是有更多? – hallleron

回答

1

要綁定的,你必須綁定在元素的父事件動態創建元素的事件:

$('body').on('click', '#sub', function(){ 
    $.post($("#exam").attr("action"), $("#exam").serialize(), function(info){ $("#result").html(info); }); 
    clearInput(); 
    $("html, body").animate({ scrollTop: 0 }, "slow"); 
}); 

$('body').on('submit', '#exam', function(event){ 
    event.preventDefault(); 
    return false; 
}); 
+0

我使用你的代碼來包裝我的所有jQuery代碼,但它對我無效。 – Oponjous

+0

@Oponjous看看我的更新。你是這樣做的嗎? –

+0

工作。謝謝@Chin Leung – Oponjous