将表单变量传递给php。防止页面刷新

时间:2014-03-11 09:41:04

标签: javascript php jquery ajax forms

我正在开发一个网站,显示一些使用php从数据库中检索到的数据。现在,还有其他chekcbox,它们包含在表单中。根据这些复选框上的用户输入,我希望div显示重新加载的数据。例如,在用户选中其中一个框并单击“应用”后,div显示应重新计算结果。我意识到表单数据必须传递给ajax函数。哪个会将此表单数据转换为json对象并将其发送到php文件。然后php文件可以使用$ _POST ['var']访问表单变量。我希望我的理论是正确的。不过,我在执行过程中遇到了一些问题。

首先,PHP代码处理与表单在同一页面上的表单变量。我想知道如何将表单数据从ajax函数定向到此代码。

其次,ajax函数正在执行,表单正在提交,页面没有重新加载(根据需要),但是,我无法访问php代码中提交的变量。

这是我的代码:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {
        $('#filter_form').on('submit', function (e) {
          $.ajax({
            type:   'post',
            url:    'index.php',
            data:   $('#filter_form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });
          e.preventDefault();
        });
      });
    </script>
<div style="float: left;margin-left: -175px;" class="box2">
        <h2>Filter by :</h2>
        <form id="filter_form" name="filter_form" href="#">
        <!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
        <h3>Location</h3>
        <?php
            //Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
            //store them in arrays and use the arrays to display on screen.
            $query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
            $result = mysqli_query($con,$query);
            $filter_array = array(5);
            for($i=0; $i<5; $i++){
                $filter_array[$i] = array();
            }
            while($row = mysqli_fetch_array($result)){
                array_push($filter_array[0],$row['LOCATION']);
                array_push($filter_array[1],$row['PARTY_TYPE']);
                array_push($filter_array[2],$row['GENRE']);
                array_push($filter_array[3],$row['HAPPY_HOURS']);
                array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
            }
            for($i=0; $i<5; $i++){
                $filter_array[$i] = array_unique($filter_array[$i]);
            }   
            ?>
            <ul>
            <?php
                foreach($filter_array[0] as $location){
                ?>
                <li>
                    <input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
                    <label for="f1"><?php echo $location?></label>
                </li>
                <?php
                }
            ?>
            </ul>
        <br>
        <h3>Party Type</h3>
            <ul>
            <?php
                foreach($filter_array[1] as $party_type){
                ?>
                <li>
                    <input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
                    <label for="f2"><?php echo $party_type?></label>
                </li>
                <?php
                }
            ?>
            </ul>
        <br><h3>Genre</h3>
            <ul>
            <?php
                foreach($filter_array[2] as $genre){
                ?>
                <li>
                    <input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
                    <label for="f3"><?php echo $genre?></label>
                </li>
                <?php
                }
            ?>
            </ul>
        <br>
        <h3>Happy Hours</h3>
            <ul>
            <?php
                foreach($filter_array[3] as $happy_hours){
                ?>
                <li>
                    <input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
                    <label for="f4"><?php echo $happy_hours?></label>
                </li>
                <?php
                }
            ?>
            </ul>
        <br>
        <h3>Outdoor/Rooftop</h3>
            <ul>
            <?php
                foreach($filter_array[4] as $outdoor_rooftop){
                ?>
                <li>
                    <input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
                    <label for="f5"><?php echo $outdoor_rooftop?></label>
                </li>
                <?php
                $i=$i+1;
                }
            ?>
            </ul>
            <br><br><br>
            <div id="ContactForm" action="#">
                <input name="filter_button" type="submit"  value="Apply"  id="filter_button"  class="button"/>
            </div>
    <!--
        <h2>Sort by :</h2>
        <input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
        <label for="f1"><?php echo 'Name'?></label>
        <input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
        <label for="f1"><?php echo 'Location'?></label>
        <br><br><br>
        <input name="filter_button" type="submit"  value="Apply"  id="filter_button"  class="button"/>
    -->
        </form>
    </div>
<div class="wrapper">
            <h2>Venues</h2>
            <br>
            <div class="clist" id="clublist" href="#">
                <?php
                    ?>
                    <table id = "venue_list">
                    <tbody>
                    <?php

                    //Functions
                    //This function builds the query as every filter attribute is passed onto it.
                    function query_builder($var_name){
                        $append = strtoupper($var_name)." in (";
                        $i=0;
                        foreach($_POST[$var_name] as $array){
                            $append = $append."'{$array}'";
                            $i=$i+1;
                            if($i < count($_POST[$var_name])){
                                $append = $append.",";
                            }
                            else{
                                $append=$append.")";
                            }
                        }
                        return $append;
                    }

                    //We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
                    //We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
                    //The below 2 variables do the same.
                    $filter_set = 0;
                    $filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
                    $map_array = array();

                    if(isset($_POST['location'])){
                        $filter_set = 1;
                    }
                    if(isset($_POST['party_type'])){
                        $filter_set = 1;
                    }
                    if(isset($_POST['genre'])){
                        $filter_set = 1;
                    }
                    if(isset($_POST['happy_hours'])){
                        $filter_set = 1;
                    }
                    if(isset($_POST['outdoor_rooftop'])){
                        $filter_set = 1;
                    }

                    if($filter_set == 1){
                        $query = "Select * from venue_list where ";
                        $append_query=array(5);
                        $j=0;

                        foreach($filter_variables as $var){
                            if(isset($_POST[$var])){
                                $append_query[$j] = query_builder($var);
                                $j=$j+1;
                            }
                        }

                        $h=0;
                        //Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
                        //sequentially accessed.
                        foreach($append_query as $append){
                            $query=$query.$append;
                            $h=$h+1;
                            if($h < $j){
                                $query=$query." AND ";
                            }
                        }
                    }
                    else{
                        $query = "Select * from venue_list";
                    }

                    $result = mysqli_query($con,$query);
                    while($row = mysqli_fetch_array($result))
                    {
                        $name = $row['NAME'];
                        $img = $row['IMAGE_SRC'];
                        $addr = $row['ADDRESS'];
                        $location = $row['LOCATION'];

                        echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
                    ?>
                        <tr>
                            <td>
                                    <img src="<?php echo $img.".jpg"?>" height="100" width="100">
                            </td>
                            <td>
                                    <?php echo $name?>
                            </td>
                            <td style="display:none;">
                                    <?php echo $location?>
                            </td>
                        </tr>                       
                    <?php
                    }
                ?>
                    </tbody>
                    </table>
            </div>
          <br>
       </div>

所有3个组件都是index.php的一部分。如果代码不可读或不方便,请通知我,我会编辑它。等待解决方案。谢谢。

1 个答案:

答案 0 :(得分:0)

在这种情况下,将您的javascript代码更改为

var submiting = false;

    function submitmyforum()
    {

        if ( submiting == false )
       {

          submiting  = true;

           $.ajax({
                type:   'post',
                url:    'index.php',
                data:   $('#filter_form').serialize(),
                success: function () {
                  alert('form was submitted');
                  submiting  = false;
                }
              });
      }else
       {
       alert("Still working ..");
       }
     }

并将表单提交按钮更改为

 <input name="filter_button" type="button" onclick="submitmyforum();"  value="Apply"  id="filter_button"  class="button"/> 

不要忘记将提交按钮type="submit"更改为type="button"