javascript - can not get json from php to html (sometimes works and sometimes not..) -
i need help...
i have 2 files:
- form.html contains html form
- register.php- gets post request form, registers user in database , returns json contains registered users (i want display them in form.html right after successful registration).
my problem:
i catched submit event , made post request register.php. register file works fine , regiters users db. problem json registers users register.php form.html. can see tried alert json alert(json)
in callback function check if came ok. when run code surprised see line alert(json)
works , somtimes not no rational reason... want clear: line alert("inserting")
, actual user registration db works fine. problem in callback function... perhaps problem related end of register file (the creation of json).
thanks advance!
form.html
$( "#myform" ).submit(function( event ) { if(!validateform()) //there 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 , bind $stmt = $conn->prepare("insert 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 registers users $stmt2 = $conn->prepare("select last_name,first_name users order 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 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 `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 `users` order 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 $formatarray endwhile; echo json_encode($formatarray, json_force_object); $stmt2->close(); endif; endif; $conn->close();
and 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 length of json var txt = "";//open blank txt variable if(len > 0){ //if length greater 0 for(var i=0;i<len;i++){ //as long len greater variable if(json[i].first_name && json[i].last_name){ //we start storing json data txt variable txt += "<tr><td>"+json[i].last_name+"</td> <td>"+json[i].first_name+"</td> </tr>"; } } if(txt != ""){ //if data there remove hidden attribute //and append txt contains data table //the table given id named 'table'. $("#table").append(txt).removeclass("hidden"); } } } }, error: function(jqxhr, textstatus, errorthrown){ alert('error: ' + textstatus + ': ' + errorthrown); } }); });
before submitting form may hide table, in css, add .hidden{display:none;}
, below form in form.html.
<table id="table" class="hidden"> <tr> <th>first name</th> <th>last name</th> </tr> </table>
Comments
Post a Comment