使用ajax将变量传递回页面

时间:2016-03-08 18:47:34

标签: javascript php jquery ajax

我有一个页面(form.php),它使用ajax将一些表单数据发布到页面(insert.php),然后将其插入到mysql数据库中。

我现在希望能够在insert.php上做一个简单的等式,并将结果作为变量返回给form.php。任何人都可以告诉我如何将$ variable返回到form.php作为我可以使用的变量吗?

form.php的

//Stripped down for ease of reading
<script>
    $(document).ready(function(){
        $("#message").hide();
        $("#submitButtonId").on("click",function(e){
            e.preventDefault();

            var formdata = $(this.form).serialize();
            $.post('insert.php', formdata,
                function(data){
                    $("#message").html(data);
                    $("#message").fadeIn(500);
                    return false;
                });
        });
</script>


//The Form
<form class="form-inline" action="" id="myform" form="" method="post">

    <!-- Text input-->
    <div class="form-group">
        <label class="col-md-4 control-label" for="bill_cost"></label>
        <div class="col-md-8">
            <input id="bill_cost" name="bill_cost" type="text"
                   placeholder="Bill Cost" class="form-control input-lg" required>
        </div>
    </div>

    <!-- Button -->
    <div class="form-group">
        <label class="col-md-4 control-label" for="submit1"></label>
        <div class="col-md-4">
            <button id="submitButtonId" name="submit1"
                    class="btn btn-primary btn-xl">Submit</button>
        </div>
    </div>

</form>

<div id="message">

insert.php

<?php
//Connection script would be here

$bill_cost=$_POST['bill_cost'];

//Insert into Database

$stmt = $db_conx->prepare('INSERT INTO mytable  set bill_cost=?);
$stmt->bind_param('s',$bill_cost);
$stmt->execute();

if($stmt){

//Count Rows
$sql="SELECT bill_cost FROM mytable";
$query = mysqli_query($db_conx, $sql);
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($query);

  //Do some maths (for example )

  $variable=$rowcount/100

  //echo message BUT how to send it as a variable?

  echo "<h1>Answer is ".$variable."</h1>";
  }

else{ echo "An error occurred!"; }
?>

0 个答案:

没有答案