无法将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();
?>

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>

I recomend you use the promise interface like so:

var jqXHR = $.post(url, data);
jqXHR.done(function(){
    console.log(jqXHR.responseText); //check php notices...
    console.info(jqXHR.responseJSON); //all ok
})
.fail(function(){
    console.error(jqXHR.responseText); // here you will likely find your problem
});

most likely you have some warning or error in your php side and it will show up on the fail callback. Also check your Network tab on chrome for http statuses other than 2XX.