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