duanrang9348 2016-04-19 18:18
浏览 51
已采纳

无法将json从php转换为html(有时可以工作,有时不会......)

I need some help...

I have 2 files:

  • form.html that contains the html form
  • register.php- gets the post request from the form, registers the user in the database and returns json that contains all the registered users (I want to display them in form.html right after a successful registration).

my problem:

I catched the submit event and made a post request to register.php. The register file works fine and regiters users to the db. the problem is to get the json with all the registers users from register.php to form.html. You can see that I tried to alert the json by alert(json) in the callback function just to check if it came ok. But when I run the code I was surprised to see that the line alert(json) sometimes works and somtimes not with no rational reason... I just want be clear: the line alert("inserting") and the actual user registration to the DB works fine. The problem is in the callback function... Perhaps the problem is related to the end of the register file (the creation of the json).

thanks from advance!

form.html

        $( "#myForm" ).submit(function( event ) {
                        if(!validateForm()) //there is error
                        {
                            event.preventDefault();
                        }
                        else
                        {
                            alert("inserting");

                            $(function(){
                                $('#myForm[name=new_post]').submit(function(){
                                  $.post($(this).attr('action'), $(this).serialize(), function(json) {
                                    alert(json);
                                  }, 'json');
                                  return false;
                                });
                            });
                        }
        });

form definition: <form class="form-horizontal" id="myForm" role="form" method="POST" action="register.php">

register.php

<?php
    $srevernme = "localhost";
    $username = "root";
    $password = "";
    $dbname = "mydb";
    //create connection
    $conn = new mysqli($srevernme,$username,$password,$dbname);

    //check connection
    if($conn->connect_error)
        die("connection failed:". $conn->connect_error);

    if ($_SERVER['REQUEST_METHOD'] == "POST") 
    {        
        if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) && isset($_POST["zipcodeInput"]))
        {
            //add new users
            // prepare and bind
            $stmt = $conn->prepare("INSERT INTO users (first_name, last_name, address, city, zipcode) VALUES (?, ?, ?, ?, ?)");
            if ($stmt == FALSE)
                die("Connection failed:");
            $stmt->bind_param("sssss",$firstname,$lastname,$address,$city,$zipcode);
            $firstname = $_POST["fnameInput"];
            $lastname = $_POST["lnameInput"];
            $address = $_POST["addressInput"];
            $city = $_POST["cityInput"];
            $zipcode = $_POST["zipcodeInput"];
            $stmt->execute();
            $stmt->close();


            //get all registers users

            $stmt2 = $conn->prepare("SELECT last_name,first_name FROM users ORDER BY last_name");
            if ($stmt2 == FALSE)
                die("Connection failed:");
            $stmt2->execute();                   
            $result = $stmt2->get_result();

            $arrayFormat = array();
            while($row = $result ->fetch_assoc())
            { 
                $arr = array('last_name'=>$row['last_name'],'first_name'=>$row['first_name']);
                $tmp_json = json_encode($arr);
                array_push($arrayFormat,$tmp_json);  
            }
            echo json_encode($arrayFormat, JSON_FORCE_OBJECT);

            $stmt2->close();
        }
    }

    $conn->close();
?>
  • 写回答

2条回答 默认 最新

  • douping1581 2016-04-19 18:56
    关注

    For the server side, Try this:

    if($conn->connect_error):
        die("connection failed:". $conn->connect_error);
    endif;
    if ($_SERVER['REQUEST_METHOD'] == "POST"): 
       if (isset($_POST["fnameInput"]) && isset($_POST["lnameInput"]) 
           && isset($_POST["addressInput"]) && isset($_POST["cityInput"]) 
           && isset($_POST["zipcodeInput"])):
            $stmt = $conn->prepare("INSERT INTO `users` 
                    (first_name, last_name, address, city, zipcode) 
                    VALUES (?, ?, ?, ?, ?)");
            if ($stmt == FALSE):
                die("Connection failed:");
            endif;            
            $stmt->bind_param("sssss",$firstname,$lastname,$address,$city,$zipcode);
            $firstname = $_POST["fnameInput"];
            $lastname = $_POST["lnameInput"];
            $address = $_POST["addressInput"];
            $city = $_POST["cityInput"];
            $zipcode = $_POST["zipcodeInput"];
            $stmt->execute();
            $stmt->close();
            $stmt2 = $conn->prepare("SELECT last_name,first_name 
                                     FROM `users` ORDER BY last_name");
            if ($stmt2 == FALSE):
                die("Connection failed:");
            endif;
            $stmt2->execute();                   
            $result = $stmt2->get_result();
      $formatArray= array();
      while($row = $result->fetch_assoc()):
         array_push($formatArray, $row); //push result to $formatArray     
      endwhile;
      echo json_encode($formatArray, JSON_FORCE_OBJECT);
      $stmt2->close();
     endif;    
    endif;
    $conn->close();
    

    And for client side:

    var form = $("#myForm");
    $('#myForm[name=new_post]').submit(function(e){
      e.preventDefault();
     $.ajax({
            type:"POST",
            url:"register.php",
            data:form.serialize(),
            dataType:"json", 
            success: function(json){ 
            if(json){
                var len = json.length;//we calculate the length of the json
                var txt = "";//open a blank txt variable
                if(len > 0){ //if length is greater than zero
                   for(var i=0;i<len;i++){ //as long as len is greater than i variable
                     if(json[i].first_name && json[i].last_name){
                     //we start storing the json data into txt variable
                         txt += "<tr><td>"+json[i].last_name+"</td>
                                      <td>"+json[i].first_name+"</td>
                                 </tr>";
                       }
                    }
                if(txt != ""){ 
                //If data is there we remove the hidden attribute
                //and append the txt which contains the data into the table
                //The table is given an id named 'table'.
                   $("#table").append(txt).removeClass("hidden");
                }
             }
          }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
         }       
     });
    });
    

    Before submitting the form you may like to hide your table, so in your css, add .hidden{display:none;}, then below the form in form.html.

    <table id="table" class="hidden">       
        <tr>
            <th>First name</th>
            <th>Last name</th>
        </tr>
    </table>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比