dongmi19720408
2016-11-25 02:51 阅读 89

Ajax请求不改变HTML

I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information. Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.

This is my code:

       <script>
        $(document).ready(function(){
            $("#show-form-button").click(function(){
                $("#show-form-button").hide();
                $("#bot-form").show();
            });

            $("#distrito").on('change', function() {
                var selected = $(this).val();
                makeAjaxRequest(selected);
            });
        });

        function insertResults(json){
            alert("cenas");
            $("#teste").val(json["nome"]);
        }

        function makeAjaxRequest(placeID){
            $.ajax({
                type: "POST",
                data: {placeId: placeID},
                dataType: "json",
                url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
                success: function(json) {
                    insertResults(json);
                }
            });
        }


    </script>

And this is my PHP script:

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$placeId = $_GET["placeId"];

$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";

$result = $conn -> query($query) or die("Query failed");

if($result -> num_rows > 0)
{
    while ($row = $result -> fetch_assoc())
    {
        echo $row['nome'];
        echo json_encode($row);
    }
}

?>

Any idea what can be wrong?

I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.

Thanks for your patience and sorry for my bad english.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    douya8978 douya8978 2016-11-25 02:59

    1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called

    2) dont echo your JSON for each row like that, that's not valid either. –

    Instead do this:

    $response = [];
    while ( $row = $result->fetch_assoc() ){
        $response[] = $row;
    }
    echo json_encode($response);
    

    3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];

    Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:

            $.ajax({
                type: "POST",
                data: {placeId: placeID},
                dataType: "json",
                url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
                success: function(json) {
                    insertResults(json);
                },
                error: function(xhr, status, error){
                    console.log(xhr); 
                }
            }); 
    

    4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:

     function insertResults(json){
            alert("cenas");
            $("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
     }
    
    点赞 评论 复制链接分享
  • doujia2463 doujia2463 2016-11-25 02:59

    In your PHP do this:

     while($row = $result->fetch_assoc()){
      $arr[] = $row;
     }
    
    echo json_encode($arr);
    mysql_close($con);
    

    Also don't forget to do mysql_close($con) at the end. Hope this helps you!

    点赞 评论 复制链接分享
  • doukuang1897 doukuang1897 2016-11-25 07:32

    From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input

    function insertResults(json){
       alert("cenas");
       $("#teste").html(json["nome"]);
     }
    
    点赞 评论 复制链接分享

相关推荐