I'm having some trouble adding form data to a database. The form is dynamically changing depending on previous values selected but during the insert into database, the values are blank but I can't work out where I'm going wrong. They appear to get past a validation check that verifies that values are not blank.
Any help would be appreciated.
Cheers
HTML form
<form class="form-horizontal" action="php_action/create.php" method="POST" id="createHostForm">
<div class="modal-body">
<div class="messages"></div>
<div class="form-group">
<label for="crm" class="col-sm-2 control-label">CRM No.</label>
<div class="col-sm-10">
<select class="form-control form-control-md" id="crm">
<option selected disabled>Select </option>
<?php foreach($customers as $customer): ?>
<option value="<?php echo $customer['crm']; ?>"><?php echo $customer['crm']; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="package_ref" class="col-sm-2 control-label">Package</label>
<div class="col-sm-10">
<select class="form-control form-control-md" id="package_ref">
<option>Select </option>
</select>
</div>
</div>
<div class="form-group">
<label for="hostname" class="col-sm-2 control-label">Hostname</label>
<div class="col-sm-10">
<select class="form-control form-control-md" id="hostname">
<option>Select </option>
</select>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
</form>
<script>
$(document).ready(function() {
// ------------------ [ Customer dropdown Change Event ] --------------
$("#crm").change(function() {
var customerId = $(this).val();
$("#package_ref").fadeIn('slow');
$.ajax({
url: 'process-controller.php',
type: 'POST',
data: {
custId: customerId
},
dataType: "JSON",
success: function(result) {
var items = "";
$("#package_ref").empty();
$("#hostname").empty();
$("#package_ref").append(
"<option selected disabled> Select </option>");
$("#hostname").append(
"<option selected disabled> Select </option>");
$.each(result, function(i, item) {
$("#package_ref").append("<option value='" + item
.package_ref + "'>" + item.package_ref +
"</option>");
});
}
});
});
// ------------- [ Package Dropdown Change ] ---------------
$("#package_ref").change(function() {
var packageId = $(this).val();
$(this).fadeIn();
$.ajax({
url: './process-controller.php',
type: 'POST',
data: {
packId: packageId
},
dataType: 'JSON',
success: function(result) {
var item = "";
$("#hostname").empty();
$.each(result, function(i, item) {
$("#hostname").append("<option value='" + item
.hostname + "'>" + item.hostname +
"</option>");
});
}
});
});
});
</script>
process-controller.php
<?php
require_once './data-controller.php';
if(isset($_POST['custId'])) {
$custId = $_POST['custId'];
$dController = new DataController();
$customers = $dController->packageListing($custId);
echo json_encode($customers);
}
elseif(isset($_POST['packId'])) {
$packId = $_POST['packId'];
$dController = new DataController();
$hostnames = $dController->hostnameListing($packId);
echo json_encode($hostnames);
}
?>
data-controller.php
<?php
include_once './db-config.php';
class DataController {
// ------------ [ Customer Listing ] ------------------------
public function getCustomers() {
$data = array();
$db = new DBController();
$conn = $db->connect();
$sql = "SELECT DISTINCT crm FROM assets";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
$db->close($conn);
return $data;
}
// ------------- [ Package Listing ] -----------------------
public function packageListing($customerId) {
$data = array();
$db = new DBController();
$conn = $db->connect();
$sql = "SELECT DISTINCT package_ref FROM assets WHERE crm = '$customerId'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
$db->close($conn);
return $data;
}
// --------------- [ Hostname Listing ] -------------------------
public function hostnameListing($packageId) {
$data = array();
$db = new DBController();
$conn = $db->connect();
$sql = "SELECT hostname FROM assets WHERE package_ref = '$packageId'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
}
$db->close($conn);
return $data;
}
}
?>
php_action/create.php
<?php
require_once 'db_connect.php';
//if form is submitted
if($_POST) {
$validator = array('success' => false, 'messages' => array());
$crm = $_POST['crm'];
$package_ref = $_POST['package_ref'];
$hostname = $_POST['hostname'];
$sql = "INSERT INTO hosts (crm, package_ref, hostname) VALUES ('$crm', '$package_ref', '$hostname')";
$query = $connect->query($sql);
if($query === TRUE) {
$validator['success'] = true;
$validator['messages'] = "Successfully Added";
} else {
$validator['success'] = false;
$validator['messages'] = "Error while adding the host information";
}
// close the database connection
$connect->close();
echo json_encode($validator);
}
javascript
var manageHostTable;
$(document).ready(function() {
manageHostTable = $("#manageHostTable").DataTable({
"ajax": "php_action/retrieve.php",
"order": [],
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"oSearch": {"sSearch": $.urlParam('search') }
});
$("#addHostModalBtn").on('click', function() {
// reset the form
$("#createHostForm")[0].reset();
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
$(".text-danger").remove();
// empty the message div
$(".messages").html("");
// submit form
$("#createHostForm").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
var form = $(this);
// validation
var crm = $("#crm").val();
var package_ref = $("#package_ref").val();
var hostname = $("#hostname").val();
if(crm == "") {
$("#crm").closest('.form-group').addClass('has-error');
$("#crm").after('<p class="text-danger">The CRM field is required</p>');
} else {
$("#crm").closest('.form-group').removeClass('has-error');
$("#crm").closest('.form-group').addClass('has-success');
}
if(package_ref == "") {
$("#package_ref").closest('.form-group').addClass('has-error');
$("#package_ref").after('<p class="text-danger">The Package Reference field is required</p>');
} else {
$("#package_ref").closest('.form-group').removeClass('has-error');
$("#package_ref").closest('.form-group').addClass('has-success');
}
if(hostname == "") {
$("#hostname").closest('.form-group').addClass('has-error');
$("#hostname").after('<p class="text-danger">The Hostname field is required</p>');
} else {
$("#hostname").closest('.form-group').removeClass('has-error');
$("#hostname").closest('.form-group').addClass('has-success');
}
if(crm && package_ref && hostname ) {
//submit the form to server
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(),
dataType : 'json',
success:function(response) {
// remove the error
$(".form-group").removeClass('has-error').removeClass('has-success');
if(response.success == true) {
$(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// reset the form
$("#createHostForm")[0].reset();
// reload the datatables
manageHostTable.ajax.reload(null, false);
// this function is built in function of datatables;
} else {
$(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
} // /else
} // success
}); // ajax subit
} /// if
return false;
}); // /submit form for create host
}); // /add modal
});
Found out my issue. I hadn't given a name for each select.
Before
<select class="form-control form-control-md" id="crm">
After
<select class="form-control form-control-md" name="crm" id="crm">
i just don't seem to get it right, i have tried all the methods and yet i can't get the form to submit after confirmation
It's basically a quiz system, am outputting the response whether the answer is correct or not before submitting, its showing the response but when i click on ok, its not submitting the form to take me to another question
<form id="form" method="post" action="javascript:void(0)">
<ul class="choices">
<?php while($row=$choices->fetch_assoc()): ?>
<li><input name="choice" type="radio" value="<?php echo $row['id']; ?>"/>
<?php echo $row['choice']; ?>
</li>
<?php endwhile; ?>
<input type="submit" id="submit" name="submit1" value="Gönder"/>
<input type="hidden" name="number" value="<?php echo $number; ?>"/>
</form>
and the Bootbox.js code
<script src="../../css/bootbox.min.js"></script>
<script src="../../css/bootbox.locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootbox/4.4.0/bootbox.min.js"></script>
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({ url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: [$("input[name='choice']:checked").serialize()],
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
process.php
<?php include 'database.php'; ?>
<?php session_start();
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];?>
<?php
//Check to see if score is set_error_handler
if (!isset($_SESSION['score'])){
$_SESSION['score'] = 0;
$_SESSION['question']=array();
$_SESSION['answer']=array();
}
//Check if form was submitted
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
$lesson = (int) $_GET['l'];
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}
}
?>
firstly do this copy this script
<script>
<?php
$lesson = (int) $_GET['l'];
$number = (int) $_GET['n'];
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
?>
$('form').on('click', "input[type='submit']", function(e){
var radioValue = $("input[name='choice']:checked").val();
var number = $("input[name='number']");
var lesson = <?=$lesson; ?>
if(radioValue){
if(radioValue==<?php echo $correct_choice;?> ){
e.preventDefault();
var currentTarget = event.target;
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-check" style="font-size:48px;color:green"></i></center>',
callback: function (result) {
if (result === null) {
} else {
$.ajax({
url: "process3.php?l=<?php echo $lesson; ?>",
type: "post",
data: 'choice='+radioValue+'&number='+number+'&lesson='+lesson,
success: function(data){ alert('success'); } });
}
},
});
setTimeout(function(){
box.modal('hide');
}, 3000);
}
else {
e.preventDefault();
bootbox.alert({
closeButton: false,
message: '<center><i class="fa fa-times" style="font-size:48px;color:red"></i></center><br /> Maalesef yanlış. Doğru cevap: <?php echo $ChoiceFull; ?> <br /> <?php echo $questionac['explanation'] ?>',
callback: function (result) {
}
});
}
}
});
</script>
then now time is your php
if($_POST){
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next=$number+1;
// you didn't send any get request remove this
//$lesson = (int) $_GET['l'];
$lesson = $_POST['lesson'];
// I found mistake till here and other code it depends on your code
//Get total number of questions
$query = "select * from questions_tr where lesson_number = $lesson";
$results = $mysqli->query($query) or die($mysqli->error.__LINE__);
$total=$results->num_rows;
//Get correct choice
$q = "select * from `choices_tr` where question_number = $number and is_correct=1 and lesson_number=$lesson";
$result = $mysqli->query($q) or die($mysqli->error.__LINE__);
$row = $result->fetch_assoc();
$correct_choice=$row['id'];
$ChoiceFull=$row['choice'];
$fullquestionq = "select * from `questions_tr` where question_number = $number and lesson_number=$lesson";
$resultful = $mysqli->query($fullquestionq) or die($mysqli->error.__LINE__);
$resultrow = $resultful->fetch_assoc();
$QuestionFull=$resultrow['question'];
//compare answer with result
if($correct_choice == $selected_choice){
$_SESSION['score']++;
}else{
$_SESSION['question'][$next-1] = $QuestionFull;
$_SESSION['answer'][$next-1] = $ChoiceFull;
}
if($number == $total){
header("Location: final3.php");
exit();
} else {
header("Location: Bolum3.php?n=".$next."&l=$lesson&score=".$_SESSION['score']);
}
I mixed an "ajax select" and "while scrolling load data" script, and this is working, but I don't know how to print "not found data" in div.status when the output variable (on animals.php) is empty.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Animals</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="search">
<div class="filter category">
<select name="category" id="category">
<option value="">All</option>
<option value="free">Free</option>
<option value="lost">Lost</option>
<option value="found">Found</option>
</select>
</div>
<div class="filter chipnumber">
<input type="text" name="chipnumber" id="chipnumber"></div>
</div>
<div class="send">
<button type="submit" id="submit">Search</button>
</div>
</div>
<script>
$(document).ready(function() {
var animal_limit = 6;
var animal_start = 0;
var animal_action = 'inactive';
function load_animal_data() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
$.ajax({
url: "animals.php",
method: "POST",
data: {animal_limit:animal_limit, animal_start:animal_start, animal_action:animal_action, category:category, chipnumber:chipnumber},
success:function(data) {
$('div.animals').append(data);
if (data == '') {
animal_action = 'active';
} else {
animal_action = 'inactive';
}
}
});
}
load_animal_data();
function search() {
var category = $('#category').val();
var chipnumber = $('#chipnumber').val();
animal_start = 0;
load_animal_data();
}
$('#search').on('click', function() {
search();
});
$(window).scroll(function () {
if ($(window).scrollTop() + $(window).height() > $('div.animals').height() && animal_action == 'inactive') {
animal_action = 'active';
animal_start = animal_start + animal_limit;
setTimeout(function() {
load_animal_data();
}, 1000);
}
});
});
</script>
<div class="animals"></div>
<div class="status"></div>
</body>
</html>
animals.php
<?php
$connect = mysqli_connect("localhost", "root", "", "petsdata");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($connect,"utf8");
$output = '';
$animal_start = $connect->real_escape_string($_POST["animal_start"]);
$animal_limit = $connect->real_escape_string($_POST["animal_limit"]);
$category = $connect->real_escape_string($_POST["category"]);
$chipnumber = $connect->real_escape_string($_POST["chipnumber"]);
if (isset($animal_start, $animal_limit, $category, $chipnumber)) {
if (!empty($category) && !empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($category)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE category = '".$category."' ORDER BY id LIMIT ".$animal_start.", ".$animal_limit."");
}
else if (!empty($chipnumber)) {
$query = mysqli_query($connect, "SELECT * FROM animals WHERE chipnumber LIKE '%".$chipnumber."%' AND status = '1' ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
else {
$query = mysqli_query($connect, "SELECT * FROM animals ORDER BY id DESC LIMIT ".$animal_start.", ".$animal_limit."");
}
while ($row = mysqli_fetch_array($query)) {
$output .= '<div class="animal">';
$output .= '<span>Category: ' . $row["category"] . '</span>';
$output .= '<span>Chipnumber: ' . $row["chipnumber"] . '</span>';
$output .= '</div>';
}
}
echo $output;
?>
if($query->num_rows > 0){
//Proceed as normally
}else{
$output = 'No data Found';
}
I am a beginner in programming and i have a java script function that sends the variables of a form to a php script.
In the form i have two tables that hold two dropdowns each.
I can click the plus button to clone the first table row and i can click delete to remove the clones.
The max amount that can be generated is limited to 3 for nativelang and to 6 for practlang.
I have set all the variables that can be generated in the php and the javascript already and if i generate the max amount then it all works fine.
But if i don't generate any or just a few then the ajax.send is not doing anything, actually the form button stops working.
I suspect it is because of the expected data from the already declared variables that are empty because i didn't generate the drop downs.
This is the code that might cause the problem:
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
and this error is returned:
Uncaught TypeError: Cannot read property 'value' of nullsignup.php:954 signupsignup.php:893 onclick
How can i make it send the field even if its empty? or is it the php code?
I assumed the php would just save the fields that hold data and if a variable has no data then it is just saved as empty into the database right?
So thats why i thought it must be the javascript.
Would be super great if someone could help me to make this work :)
Sign up script:
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass1").value;
var p2 = _("pass2").value;
var c = _("country").value;
var g = _("gender").value;
var ct = _("city").value;
var nl = _("nativelang").value;
var nll = _("nlanglevel").value;
var nl0 = _("nativelang0").value;
var nll0 = _("nlanglevel0").value;
var nl1 = _("nativelang1").value;
var nll1 = _("nlanglevel1").value;
var nl2 = _("nativelang2").value;
var nll2 = _("nlanglevel2").value;
var pl = _("practlang").value;
var pll = _("planglevel").value;
var pl0 = _("practlang0").value;
var pll0 = _("planglevel0").value;
var pl1 = _("practlang1").value;
var pll1 = _("planglevel1").value;
var pl2 = _("practlang2").value;
var pll2 = _("planglevel2").value;
var pl3 = _("practlang3").value;
var pll3 = _("planglevel3").value;
var pl4 = _("practlang4").value;
var pll4 = _("planglevel4").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == "" || c == "" || g == "" || ct == "" || nl == "" || pl == ""){
status.innerHTML = "Fill out all of the form fields marked with a star";
} else if(p1 != p2){
status.innerHTML = "Your passwords do not match";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'Email has been sent!';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText.trim()!= "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "<div id=\"status\">OK "+u+", <h2>check your email</h2> inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully <h2>activate your account!</h2></div>";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1+"&c="+c+"&g="+g+"&ct="+ct+"&nl="+nl+"&nll="+nll+"&nl0="+nl0+"&nll0="+nll0+"&nl1="+nl1+"&nll1="+nll1+"&nl2="+nl2+"&nll2="+nll2+"&pl="+pl+"&pll="+pll+"&pl0="+pl0+"&pll0="+pll0+"&pl1="+pl1+"&pll1="+pll1+"&pl2="+pl2+"&pll2="+pll2+"&pl3="+pl3+"&pll3="+pll3+"&pl4="+pl4+"&pll4="+pll4);
}
}
Script for the buttons that add or delete rows in the table(table holds dropdowns):
var ncount = -1;
$(document).ready(function(){
$('#addBtnNative').on('click', function(e){
if($('.nativelangdrop').length < 4) {
ncount++;
var initialn_row = $('tr.initialn').first().clone();
var nativelang_name = initialn_row.find('td:eq(0) select').attr('name'); // first td select
var nlanglevel_name = initialn_row.find('td:eq(1) select').attr('name'); // second td select
initialn_row.find('td:eq(0) select').attr('name', nativelang_name + ncount);
initialn_row.find('td:eq(1) select').attr('name', nlanglevel_name + ncount);
var nativelang_id = initialn_row.find('td:eq(0) select').attr('id'); // first td select
var nlanglevel_id = initialn_row.find('td:eq(1) select').attr('id'); // second td select
initialn_row.find('td:eq(0) select').attr('id', nativelang_id + ncount);
initialn_row.find('td:eq(1) select').attr('id', nlanglevel_id + ncount);
$('table.nativelanguages').append(initialn_row);
}
});
});
$(document).ready(function(){
$('#remBtnNative').on('click', function(e){
if($('.nativelangdrop').length > 1) {
ncount--;
var initialn_row = $('tr.initialn').last().remove();
}
});
});
var pcount = -1;
$(document).ready(function(){
$('#addBtnPract').on('click', function(e){
if($('.practlangdrop').length < 6) {
pcount++;
var initialp_row = $('tr.initialp').first().clone();
var practlang_name = initialp_row.find('td:eq(0) select').attr('name'); // first td select
var planglevel_name = initialp_row.find('td:eq(1) select').attr('name'); // second td select
initialp_row.find('td:eq(0) select').attr('name', practlang_name + pcount);
initialp_row.find('td:eq(1) select').attr('name', planglevel_name + pcount);
var practlang_id = initialp_row.find('td:eq(0) select').attr('id'); // first td select
var planglevel_id = initialp_row.find('td:eq(1) select').attr('id'); // second td select
initialp_row.find('td:eq(0) select').attr('id', practlang_id + pcount);
initialp_row.find('td:eq(1) select').attr('id', planglevel_id + pcount);
$('table.practlanguages').append(initialp_row);
}
});
});
$(document).ready(function(){
$('#remBtnPract').on('click', function(e){
if($('.practlangdrop').length > 1) {
pcount--;
var initialp_row = $('tr.initialp').last().remove();
}
});
});
PHP:
if(isset($_POST["u"])){
include_once("php_includes/db_conx.php");
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($db_conx, $_POST['e']);
$p = $_POST['p'];
$g = preg_replace('#[^a-z]#', '', $_POST['g']);
$c = preg_replace('#[^a-z ]#i', '', $_POST['c']);
$ct = $_POST['ct'];
$nl = preg_replace('#[^a-z]#', '', $_POST['nl']);
$nll = preg_replace('#[^a-z]#', '', $_POST['nll']);
$nl0 = preg_replace('#[^a-z]#', '', $_POST['nl0']);
$nll0 = preg_replace('#[^a-z]#', '', $_POST['nll0']);
$nl1 = preg_replace('#[^a-z]#', '', $_POST['nl1']);
$nll1 = preg_replace('#[^a-z]#', '', $_POST['nll1']);
$nl2 = preg_replace('#[^a-z]#', '', $_POST['nl2']);
$nll2 = preg_replace('#[^a-z]#', '', $_POST['nll2']);
$pl = preg_replace('#[^a-z]#', '', $_POST['pl']);
$pll = preg_replace('#[^a-z]#', '', $_POST['pll']);
$pl0 = preg_replace('#[^a-z]#', '', $_POST['pl0']);
$pll0 = preg_replace('#[^a-z]#', '', $_POST['pll0']);
$pl1 = preg_replace('#[^a-z]#', '', $_POST['pl1']);
$pll1 = preg_replace('#[^a-z]#', '', $_POST['pll1']);
$pl2 = preg_replace('#[^a-z]#', '', $_POST['pl2']);
$pll2 = preg_replace('#[^a-z]#', '', $_POST['pll2']);
$pl3 = preg_replace('#[^a-z]#', '', $_POST['pl3']);
$pll3 = preg_replace('#[^a-z]#', '', $_POST['pll3']);
$pl4 = preg_replace('#[^a-z]#', '', $_POST['pl4']);
$pll4 = preg_replace('#[^a-z]#', '', $_POST['pll4']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$e_check = mysqli_num_rows($query);
if($u == "" || $e == "" || $p == "" || $g == "" || $c == "" || $ct == "" || $nl == "" || $pl == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 25) {
echo "Username must be between 3 and 25 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
$p_hash = md5($p);
$sql = "INSERT INTO users (username, email, password, gender, country, city, nativelang, nlanglevel, nativelang0, nlanglevel0, nativelang1, nlanglevel1, nativelang2, nlanglevel2, practlang, planglevel, practlang0, planglevel0, practlang1, planglevel1, practlang2, planglevel2, practlang3, planglevel3, practlang4, planglevel4, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p_hash','$g','$c','$ct','$nl','$nll','$nl0','$nll0','$nl1','$nll1','$nl2','$nll2','$pl','$pll','$pl0','$pll0','$pl1','$pll1','$pl2','$pll2','$pl3','$pll3','$pl4','$pll4','$ip',now(),now(),now())";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
$to = "$e";
$from = "email#site.com";
$subject = 'blah | Account Activation';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title> Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;">Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
}
HTML:
<legend class="legend"><h3>Select your languages</h3></legend>
<ul class="list-unstyled">
<li>
<div class="lala">
<table class="nativelanguages">
<tr>
<td>Spoken language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialn">
<td>
<select class="nativelangdrop" id="nativelang" name="nativelang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select></td>
<td>
<select class="langleveldrop" id="nlanglevel" name="nlanglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnNative">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnNative">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
<div class="lala">
<table style="float:left; margin-top:20px;" id="plang" class="practlanguages">
<tr>
<td>Practicing language</td>
<td style="padding-left: 5px;">Level</td>
</tr>
<tr class="initialp">
<td>
<select class="practlangdrop" id="practlang" name="practlang" required>
<option value="none" selected disabled>Select language</option>
<?php
if ($file = #fopen('txt/languages.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
<td><select class="langleveldrop" id="planglevel" name="planglevel" required>
<option value="none" selected disabled>Select level</option>
<?php
if ($file = #fopen('txt/levels.txt', 'r')) {
while(($line = fgets($file)) !== false) {
echo "<option>{$line}</option>";
}
fclose($file);
}
?>
</select>
</td>
</tr>
</table>
<div class="pmbutton">
<button href="javascript:;" type="button" class="btn btn-default" id="addBtnPract">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
</button>
<button href="javascript:;" type="button" class="btn btn-default" id="remBtnPract">
<span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span>
</button>
</div>
</div>
</li>
</ul>
Where you get your element values, try changing them to like this:
var u = _("username").value ? _("username").value : '';
This uses a Ternary Operator to set the value of u.
The syntax is: condition ? result-if-True : result-if-False;
Basically, this says, if _("username").value returns a value, assign that value to u, if not, set the value of u to "" (an empty string)
Below is a contrived example using regular jQuery method $("#username").val() I imagine it will also work with _("username").value though Im not sure what the benefit of doing _("username").value is having never seen this before myself.
var u = $("#username").val() ? $("#username").val() : 'not found';
alert(u);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I suggest to use chrome developer tools so you can see what jquery.ajax send
https://developer.chrome.com/devtools#improving-network-performance
in php, you can see what are incoming using
print_r($_POST)
and
print_r($_GET)
Hi Guys I have this search from that takes a search term matches it with a table.field and in php it searches all matching data.
I want to add autocomplete to it, can anyone PLEASE assist?
Here is the HTML FORM
<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
<input type="text" id="searchThis" name="searchThis" placeholder="search" value="" size="14" />
<select name="searchItems" id="searchItems">
<optgroup value="Vehicles" label="Vehicles">Vehicles
<option value="vehicles.Make">Make</option>
<option value="vehicles.model">Model</option>
<option value="vehicles.RegNumber">Registration Number</option>
<option value="vehicles.licenseExpireDate">License Expire Date</option>
</optgroup>
<optgroup value="Owners" label="Owners">Clients
<option value="owners.OwnerName" label="" >Name</option>
<option value="owners.mobile">Mobile Number</option>
</optgroup>
</select>
<input type="submit" id="doSearch" name="Search" value="Search" />
</form>
<ul id="result">
</ul>
There is the JS
<script src="js/jquery-1.8.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function (){
$j("#searchThis").keyup(function()
{
var searchThis = $j('#searchThis').val();
var searchItems = $j('#searchItems').val();
var dataString = {'searchThis': searchThis,'searchItems':searchItems};
if(searchThis!='')
{
$j.ajax({
type: "POST",
url: "doAutocomplete_search.php",
data: dataString,
dataType: "html",
cache: false,
success: function(data)
{
$j("#result").html(data).show();
}
});
}return false;
});
$j("#result").live("click",function(e){
var clicked = $j(e.target);
var name = clicked.find('.name').html();
var decoded = $j("<div/>").html(name).text();
$j('#searchThis').val(decoded);
});
$j(document).live("click", function(e) {
var clicked = $j(e.target);
if (! clicked.hasClass("search")){
$j("#result").fadeOut();
}
});
$j('#searchid').click(function(){
$j("#result").fadeIn();
});
});
})($j);
And the PHP
function implement($cxn,$searchThis, $field) {
$show = "";
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
$srchData = array();
$rows = mysqli_fetch_row($selectc);
echo $rows;
//if() {, MYSQL_ASSOC
//echo var_dump($srchData);
$show .= '
<table style="border:2px solid #0000">';
//foreach($srchData as $fields=>$data) {
for($s=0; $s < $rows && $srchData = mysqli_fetch_assoc($selectc);$s++) {
if($srchStack[0] == 'vehicles' && $fields == 'RegNumber') {
$dataItem = $data;
$editTbl = 'Vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
} elseif($srchStack[0] == 'vehicles' && $fields == 'Make') {
$dataItem = $data;
$editTbl = 'vehicles';
$link = 'href="index.php?list=vehicles&&tbl='.$srchStack[0].'&&item='.$dataItem.'"';
}
$show .= '<tr><td><a '.$link.'>'.$data.'</a></td></tr>
';
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
//}
}
echo implement($cxn, $_POST['searchThis'], $_POST['searchItems']);
$cxn->close();
Hi Guys so i had to do some refactoring, realized it was more the PHP MySQL code.
Here is the refactored PHP code
//Item to be searched
$srchThis = strip_tags(trim($searchThis));
//[0]= table , [1]=field to search
$srchStack = explode('.',$field);
$gtData = "SELECT * FROM ".$srchStack[0]." WHERE ".$srchStack[1]." like '%|{$srchThis}|%'";
//or die(mysqli_error($cxn))
if($selectc = mysqli_query($cxn,"SELECT * FROM {$srchStack[0]} WHERE {$srchStack[1]} LIKE '{$srchThis}%' OR {$srchStack[1]} LIKE '%{$srchThis}%'")) {
//$srchData = array();
$rows = mysqli_num_rows(#$selectc) or die(mysqli_error($cxn).'<br>No Rows returned...');
if($rows > 0) {//, MYSQL_ASSOC
//$link = ''; $l_c = 0;
$show .= '<table style="border:2px solid #0000">';
for($c = NULL;$c != $rows && $srchData = mysqli_fetch_assoc($selectc); $c++) {
foreach($srchData as $fields=>$data) {
if($fields == $srchStack[1]) {
$dataItem = $data;
$editTbl = $srchStack[0];
$show .= '<tr><td>'.$dataItem.'</td></tr>';//$a_json_row($dataItem);
//$show .= $link[$c];$link[$c]
}
}
}
$show .= '</table>';
return $show;
} else {
$show .= "There are no entries in the database...<br>".mysqli_error($cxn);
return $show;
}
Of-course the JS code still needs some more work but this greatly improved the results...
Hope this help someone...