2015-06-23 86 views
1

我在確定如何完成某個連接時遇到了一些問題。這是一個我認爲可能非常簡單的項目,無需我自己去做,但我不幸遇到了一堵牆。這是一個「練習生成器」,基本上提出了幾個基本問​​題,並根據您的答案輸出推薦的鍛鍊例程。我已經用大量的練習構建了MySQL數據庫,已經成功地連接了數據庫並製作了表單。從表單中提取值,從MySQL中提取結果並使用AJAX獲取結果

然而,我遇到麻煩的是將這些表單結果存儲到變量中,並基於這些變量(例如,如果鍛鍊日數是3,例如,將只有3組鍛鍊打印出來而不是5)輸出一個例程放入與表單相同的div中,有效地將其替換爲答案,而不是將其放在提交的表單下。

的index.php

<!DOCTYPE html> 
<html> 
<?php $page_title = "Workout Generator"; ?> 
<link rel="stylesheet" type="text/css" href="style.css"> 
<head> 
<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" ></script> 
</head> 
<body> 
    <?php include("header.php"); ?> 
    <?php include("connect.php"); ?> 
    <div id="appWindow"> 



     <h3>Please answer the following questions and click 'Submit' to generate your workout routine.</h3> 


     <form id="homeForm" method="post" > 
      <label for="name">Name: </label> 
      <input type="text" name="name"><br> 
      <label for="age">Age: </label> 
      <input type="number" name="age"><br> 
      <label for="workoutdays">How many days a week can you workout?</label> 
      <select name="workoutdays">> 
       <option value="1">3</option> 
       <option value="2">5</option> 
      </select><br> 
      <label for="workoutstyle">Do you prefer a gym, or bodyweight exercises?</label> 
      <select name="workoutstyle">> 
       <option value="1">Gym</option> 
       <option value="2">Bodyweight</option> 
      </select><br> 
      <button type="submit" name="submit">Submit</button> 
      <button type="reset" name="reset">Reset</button> 
     <div class="form_result"></div> 
    </form> 


    <?php 
     $age = $_POST['age']; 
     $workoutdays = $_POST['workoutdays']; 
     $workoutstyle = $_POST['workoutstyle']; 
    ?> 


    </div> 



<br><br><br> 
<?php include("footer.php"); ?> 
</body> 
</html> 

我不一定要一個答案給我確切的代碼進入,但希望被指出了正確的方向,以獲得這種形式從MySQL提取數據,並使用AJAX在不刷新的情況下在同一個窗口中打印。

THANK YOU

+0

google $ .post或$ .ajax jquery – Robin

回答

0

在腳本文件

$(document).ready(function(){ 
    $(document).on('click','#submit_btn',function(){ 
     var url = '/xyz.php'; //full path of the function where you have written the db queries. 
     var data = '';//any data that you would like to send to the function. 
     $.post(url,{data: data}, function(result){ 
     var arr = JSON.parse(result); 
     }); 
    }); 
}); 

在你的PHP文件一旦你的數據庫查詢被執行,你得到的結果。例如

$result = //result of your mysql query. 
echo json_encode($result); 
exit; 
0

首先,您需要發佈您的請求。用$.ajax這個

//Do this thing on page load 
$(function() { 
    //handle submit 
    $("#homeForm").submit(function(e) { 
      //customize your submit 
      e.preventDefault(); 
      $.ajax({ 
       type: "POST", 
       url: youURL, //maybe an url pointing to index.php 
       data: yourData, //attach everything you want to pass 
       success: function(response) { 
        $("#appWindow").html(response); 
       } 
      }); 
    }); 
}); 

代碼應該有幫助。您需要確保您傳遞必要的元素,並提供正確的網址。在服務器端,生成所需的html並作爲響應發回。