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 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算