reset form after submittig with ajax - javascript

I have a registration form (simple html form) that inserts registered users into a database table and this form validates with jQuery validation plugin and I need to reset form after successful registration, but I can't and don't know why.
Here is a javascript (jquery) snippet that I use for ajax form submission, that is according to the jQuery validate way
submitHandler: function() {
$.ajax({
url: "registration_form.php",
type: "POST",
data: $("#form").serialize(),
success: function (result) {
console.log(result);
if(result == '') {
$('#form')[0].reset() /*this doesn't work'*/
$("#errors").empty(); /*this doesn't work'*/
}
else {
$("#errors").text(result);
}
}
});
}
And here is my registration_form.php file.
<?php
date_default_timezone_set('UTC');
$name = htmlspecialchars($_POST['name']);
$s_name = htmlspecialchars($_POST['s_name']);
$email = htmlspecialchars($_POST["email"]);
$ticket = htmlspecialchars($_POST['ticket']);
$date = date('d_m_Y');
$valid_email = filter_var($email, FILTER_VALIDATE_EMAIL);
$table_name = 'registration_' . $date;
if(!$valid_email) {
die ("Fill the correct email");
}
if((strlen($name) <= 1) || (!$s_name) || (!$email) || (!$ticket)){
die ("All the fields should be filled");
}
$connect = mysqli_connect('localhost', 'root', 'password') or die('Connection error');
$create_db = mysqli_query($connect, "CREATE DATABASE IF NOT EXISTS kultprosvet");
$connect_db = mysqli_select_db($connect, "kultprosvet");
$table = "CREATE TABLE $table_name (
id INT(10) NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL DEFAULT '',
s_name VARCHAR(100) NOT NULL DEFAULT '',
email VARCHAR(100) NOT NULL DEFAULT '',
ticket VARCHAR(100),
PRIMARY KEY (id)
)";
$result = mysqli_query($connect, "SELECT email FROM $table_name");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if($row['email'] == $email){
die('this email is already registered');
};
}
$query_table = mysqli_query($connect,$table);
$query = mysqli_query($connect,"insert into $table_name(name, s_name, email, ticket) values ('$name', '$s_name', '$email','$ticket')");
if(mysqli_errno($connect) > 0){
echo mysqli_errno($connect). ": " . mysqli_error($connect);
}
mysqli_close($connect);
?>
So, now everything works fine, except the form reset.
Can someone show my mistakes and help me to fix this?
P.S. Recently I did the same javascript, but all the data inserted into the .txt file and everything were good, I have no idea why this code doesn't work with database variant.

Add this line of code to reset all textbox, checkbox elements your values in the form
$("input[type=text], textarea").val("");
$('input:checkbox').removeAttr('checked');

Change
if(result == '') { ... }
to
if(result) { ... // show error } else { // reset }

Related

How to store JavaScript variable in the database

I wanted to store the value "totalscore" from my JavaScript code to my database. I tried using ajax call but something is not working, I have not used ajax before.
In the following JavaScript code, I display the value of score which i have found to the html element.
JavaScript code:
if (matches==8){
var totalscore = calcScore();
document.getElementById("score").innerHTML=totalscore;
}
I want to save the value of totalscore in my users database when the submit button is clicked. So i tried something like :
$("#sendscore").on("click",function(){
gamescore= document.getElementById('score').innerHTML;
$.ajax({
type:'POST',
url: 'score-processor.php',
data:{
gamescore: gamescore,
}
})
});
the php code :
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'registration');
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password_1']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
header('location: profile.php');
}
else {
array_push($errors, "Wrong username/password combination");
}
}
}
if(isset($_POST['gamescore'])){
$fetch = "SELECT id FROM users WHERE username='$username'";
$fetchid =mysqli_query($db, $fetch);
while ($row=mysqli_fetch_array($fetchid)){
$id = $row['id'];
$gamescore= $_POST['gamescore'];
$updatescore= "INSERT INTO users(id, score)VALUES('$id','$gamescore') ON DUPLICATE KEY UPDATE score='$gamescore'";
mysqli_query($db, $updatescore);
}
}
In my html :
<?php session_start();?>
<body>
<p>Your score: <span id=score></p>
<button id="sendscore" class="Go-on">Submit</button>
the database table has columns , id, username, email, password and score.
the value for columns id, username, email and password are collected during login/register.
The game runs smoothly and presents the score but when I click the submit button which on clicked should add the value to the table, but nothing happens, no errors in the log and the value is not added to the table.
Problem 1
gamescore= document.getElementById('score');
This is an HTML element, not the value of it.
You need to read the .innerHTML just like you wrote to it earlier
Problem 2
gamescore: gamescore
jQuery.ajax doesn't have a gamescore option. So this is meaningless.
You need to pass data.
data: {
gamescore: gamescore
}
Problem 3
contentType: false,
This stops jQuery overriding the content-type when you pass a FormData object to generate a multipart request (which is useful for uploading files).
You aren't doing that, so contentType: false will break the normal allocation of the correct Content-Type header.
Remove that
Problem 4
processData: false
You need the data to be processed. The object you pass to data needs encoding into the HTML request.
Remove that.
Problem 5
$updatescore= "UPDATE users SET(username='$username', score='$gamescore') WHERE (id='$id')";
You failed to define $username or $id.

Error (net::ERR_EMPTY_RESPONSE) on AJAX call

When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file

I want to get $username variable from another page using ajax

This is my ajax code:
$(document).ready (function() {
$("#send").click (function() {
var username = $(this).val();
alert (username);
$.ajax({
url : "sendpost.php",
type: 'POST',
async: false,
data: {username},
success: function(datat){}
})
});
});
This is my php code
include ('connection_socio.php');
if(isset($_POST['body']))
{
$body=mysqli_real_escape_string($db, $_POST['body']);
$date_added="123";
$added_by="123";
$username = mysqli_real_escape_string($db, $_POST['username']);
$check = "SELECT * FROM users";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$user_posted_to = $username;
echo $user_posted_to;
$query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";
mysqli_query($db, $query_post);
echo "POSTED SUUCESSFULLY";
}
This is my profile.php code:
if (isset($_GET['u']))
{
$username = mysqli_real_escape_string($db, $_GET['u']);
//checks and remove symbols like # , ' etc
if(ctype_alnum($username))
{
//check user existance
$check = "SELECT * FROM users WHERE username='$username'";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
if(mysqli_num_rows($result_profile) == 1)
{
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$username = $getusername['username'];
}
else
{
echo "User dont exist";
exit();
}
}
}
what I want is to fetch variable $username from profile.php page and assign it to $user_posted_to variable in senpost.php page and insert into database using javascript if any expert can help will really appreciate it i have tried this.attr() but thats not working also this.value is also not working I'm unable to fetch username from that page can anyone help me with this the username variable i want to fetch is the username of the user profile which I want to assign to $user_poste_to
I believe, the best way to access the value of $username is to store it to a cookie, once you are in senpost.php, all you need to do is to get the cookie you stored and assign it to $user_posted_to variable. the correct way to get the value of a textbox/form element in by using this $(input[type="text"]).val()
Update your AJax call.
data: {username:username},
here first username will be the index and 2nd username will be the variable which you got using $(this).val()

can not get json from php to html (sometimes works and sometimes not..)

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.

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

Categories