显示MySQL结果而不重新加载... AJAX失败

时间:2015-03-08 12:31:25

标签: javascript php jquery mysql ajax

我在尝试获取MySQL查询结果而不重新加载页面时遇到了大麻烦。 我有2个文件:index.phpaction.php

我的查询工作正常,但AJAX无法正常工作,我在尝试将数据加载到.success div而无需重新加载时,会变得疯狂。

非常感谢你的帮助!

的index.php

//query SQL here then 

<form method="POST" name="form" id="form1">

    <select  name="province"> 
        <option>PROVINCE</option>
        <?php while($data = mysql_fetch_array($result)) { ?> 
            <option value="<?php echo $data['id_province']; ?>">
            <?php echo $data['province']; ?></option>
        <?php } ?>
    </select>

    <select name="candidat">
        <option>CANDIDAT</option>
        <?php 
            $result = mysql_query($query);
            while($data = mysql_fetch_array($result)) { ?>
                <option value="<?php echo $data['id_candidat']; ?>">
                <?php echo $data['pren1']; ?> <?php echo $data['nom_candidat']; ?></option>

                <?php
                    $id = $data['id_candidat'];
                    if ($id === $id) {
                        break;
                    }       
                } ?>
    </select>

    <br/>
    <input type="submit" class="submit" name="submit" value="ok" />

</form> 

然后显示结果(在同一页面中)

<div id="success">
    <?php include("action.php"); ?> 
</div>

action.php的

<?php
if(isset($_POST['submit'])) {
    $province = $_POST['province']; 
    $candidat = $_POST['candidat']; 

    $link = mysql_connect("localhost", "root", "")or die ('Erreur : '.mysql_error() );;
    mysql_select_db("election");

    $query = "SELECT DISTINCT * FROM resultat r, candidat c, province p, election e, prenom_cand t WHERE r.id_candidat = c.id_candidat AND t.id_prenom = c.id_prenom AND r.id_province = p.id_province  AND r.id_election = e.id_election AND e.id_election = 'PRES10'";

    $sql = "SET NAMES 'utf8'";
    mysql_query($sql);
    $result = mysql_query($query) or die('Erreur SQL !<br />'.$sql.'<br />'.mysql_error()); 

    while($row = mysql_fetch_object($result)) 
    { 
        $score = $row->nbre_voix;
        $prenom = $row->pren1;
        $nom = $row->nom_candidat;
        $prov =  $row->province;
        $votes = $row->nbre_votants;
        $pourcent = ($score/$votes)*100;
        $nombre = number_format($pourcent, 2, ',', ' ');
        $nombre2 = number_format($pourcent, 0, ',', ' ');
        $id =  $row->id_province;
        $idc =  $row->id_candidat;              

        if ($province===$id && $candidat===$idc)
        {
            echo $prenom;
            echo " ";
            echo $nom;
            echo " a obtenu ";
            echo  $score; 
            echo " voix dans la province de ";
            echo $prov;
            echo ", soit une moyenne de ";
            echo $nombre;
            echo "%. <br/><br/>";   
            ?>

            <div style="width:<?php echo $nombre2 ?>%;background:#CCCCCC;height:40px;">
                <div style="padding:8px;">
                    <?php echo $nombre ?>%
                </div>
            </div>
    <?php
        }
    }
}

最后,可怜的Ajax位于index.php的head标签之间,但它不起作用。

$(document).ready(function(){
$.ajax({
    url: "action.php",
    cache: false
  }).done(function( response ) {
    alert( response );
    $(".success").html(response); 
  });
});    

2 个答案:

答案 0 :(得分:1)

我看错的第一件事是

$(".success").html(response); 

应该是

$("#success").html(response); 

其次你的action.php正在寻找$_POST变量,但你没有在你的AJAX调用中发送任何变量。由于if(isset($_POST['submit']))一切都会被跳过,你需要做类似的事情:

$('.submit').on('click', function(e) { 
    e.preventDefault(); // Prevents the form being submitted
    var province = $('#province').val(); // Don't forget to add the "province' id to your input 
    var candidate = $('#candidate').val(); // Don't forget to add "candidate' id to your input 
    $.ajax({
        url: "action.php",
        type: "POST",
        cache: false,
        data: {submit: 1, province: province, candidate: candidate},
        beforeSend: function(){
           alert('Sending');
        },
        error: function(){
           alert('Error !');
        }, 
        success: function(){
           alert('Success !');
        } 
      }).done(function( response ) {
        alert( response );
        $("#success").html(response); 
      });

    }); 
});

答案 1 :(得分:0)

使用输入类型button或使用提交阻止其属性提交表单,重新加载,所以使用

$(document).ready(function(){
  $(".submit").click(function(e){
   e.preventDefault();
   $.ajax({
      url: "action.php",
      data:$("#form1").serialize()
   }).done(function( response ) {
       alert( response );
   $("#success").html(response); 
  });
 });    
});

此处序列化表单,以便您在data部分中填写数据时是否正确填充了您的头痛等。