Dynamic form inserting blank values into database - javascript

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">

Related

Why is this AJAX call not working in IE 11?

I have a notifications system on my site, that utilizes AJAX to update in real-time. The problem is that it works on every browser except IE 11. After looking around I noticed some people advising to use cache:false in the call. However, this makes the code non-functional across all browsers. Anyone know what the solution is?
JAVASCRIPT:
<script>
$(document).ready(function(){
$('.notif_count').html('0');
function load_unseen_notification(view = '')
{
$.ajax({
url:"notif_follow.php",
method:"POST",
data:{view:view},
dataType:"json",
success:function(data)
{
$('.notif_follow').html(data.notification);
if(data.notif_count > 0)
{
$('.notif_count').html(data.notif_count);
}
}
});
}
load_unseen_notification();
$(document).on('click', '.notif', function(){
$('.notif_count').html('0');
load_unseen_notification('yes');
});
setInterval(function(){
load_unseen_notification();;
}, 5000);
});
</script>
PHP:
<?php
session_start();
require_once 'class.channel.php';
$user_notif = new USER();
$user_id = $_SESSION['userID'];
if(isset($_POST["view"]))
{
if($_POST["view"] != '')
{
$stmt = $user_notif->runQuery("UPDATE notif_follow SET status = 1 WHERE receive_id = ?");
$stmt->bindValue(1,$user_id);
$stmt->execute();
}
$stmt = $user_notif->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$user_id));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$stmt = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? ORDER BY id DESC LIMIT 5");
$stmt->bindValue(1,$user_id);
$stmt->execute();
$notifs = $stmt->fetchAll(PDO::FETCH_ASSOC);
$notification = '';
if(count($notifs) > 0)
{
foreach($notifs as $notif)
{
$send_id = $notif['send_id'];
$query2 = $user_notif->runQuery("SELECT * FROM following WHERE user1_id=:uid1 AND user2_id=:uid2");
$query2->execute(array(":uid1"=>$user_id,":uid2"=>$send_id));
$query2result = $query2->fetchAll(PDO::FETCH_ASSOC);
if(count($query2result) > 0){
$follow = '<button class="button" style="margin:2px;">Remove Channel</button>';
}
else{
$follow = '<button class="button" style="margin:2px;">Add Channel</button>';
}
$notification .= '
<li>
<div class="notifbox">
<strong style="color: #4b8ed3;">'.$notif["send_name"].'</strong><p style="color: #fff;"> has added you.</p>
'.$follow.'
<button class="button" style="margin:2px;">View Channel</button>
</div>
</li>
<div class="sectionheader3"></div>
';
}
}
else
{
$notification .= '<li><h2 style="color: #4b8ed3; padding: 10px;">No Notifications Found<h2></li>';
}
$count = $user_notif->runQuery("SELECT * FROM notif_follow WHERE receive_id= ? AND status= 0");
$count->bindValue(1,$user_id);
$count->execute();
$countresult = $count->fetchAll(PDO::FETCH_NUM);
if(count($countresult) > 0){
$notif_count = count($countresult);
}
else{
$notif_count = 0;
}
header('Content-type: application/json');
$notif_array = array('notification'=>$notification,'notif_count'=>$notif_count);
echo json_encode($notif_array);
}
?>

How can I print "not found" when the code output is empty?

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';
}

how to solve theproblem with saving the data in an appended textbox

please help me out, i use isset to check if the index is defined but instead of saving the value of the textbox it stores 0.how shoul i do it? cause if i wont check if the index is defined ,when i only fill out one textbox it will throw an error, but if i fill out all five it works fine. please take a look at y code, the variables in javascript is used for its inout name, the count is for the stop adding of input text when it reach 5
HTML and PHP
<form class="form-horizontal" method= "POST">
<div class="control-group">
<div class="inc">
<div class="controls">
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<input type="submit" class="btn btn-info" name="submit" value="submit"/>
</div>
<?php
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
if(isset($_POST['submit'])){
for($i=1; $i<=5; $i++){
if(isset($_POST["textbox$i"]) && $_POST["textbox$i"] !=""){
$sasa = $_POST["textbox$i"];
$sql="INSERT into sasa (sasa) values('$sasa')";
echo $sql."<br>";
$q=$conn->query($sql);
}
}
}
?>
javascript;
<script type="text/javascript">
jQuery(document).ready( function () {
var val = 1;
var me = 0;
var count = 0;
$("#append").click( function() {
if(count<5){
if(me==0){
val=1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
else{
val = val + 1;
me = me + 1;
count = count +1;
$(".inc").append("<div class='controls'><input class='form-control' type='text' name='textbox"+ val +"' placeholder='textbox"+ val +"'><a href='#' class='remove_this btn btn-danger'>remove</a> <br> <br> </div");
return false;
}
}
else{
}
});
jQuery(document).on('click', '.remove_this', function() {
me = me - 1;
count = count - 1;
jQuery(this).parent().remove();
return false;
});
});
both your JS and PHP are wrong. You need to post an array rather than naming each textbox. In other words, your textbox names should be something like name='textbox[]'. Redo it like this:
JS:
$(document).ready(function () {
$("#append").click(function (e) {
e.preventDefault();
var textboxes = $(".textbox").length;
if (textboxes < 5) {
$(".inc").append("<div class='controls'>\
<input class='textbox form-control' type='text' name='textbox[]' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
});
});
PHP:
if (isset($_POST['submit'])) {
if (!empty($_POST['textbox'])) {
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
$textboxes = $_POST['textbox'];
foreach ($textboxes as $value) {
$sql = "INSERT into sasa (sasa) values('$value')";
echo $sql . "<br>";
$q = $conn->query($sql);
}
}
}
Ok, it seems like your goal is to send a multidimensional array to PHP. In other words, you want PHP to be able to receive something in this format:
array (size=2)
0 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
1 =>
array (size=2)
'text' => string 'some text' (length=9)
'box' => string 'some box' (length=8)
In order for you to achieve this, you need to create a function that indexes your input textboxes when you create them and when you delete them so that you can end up with inputs with indexed name attributes like so:
<input name="data[0][text]">
<input name="data[0][box]">
<input name="data[1][text]">
<input name="data[1][box]">
With that said, this is the JS I would use:
<script>
$(document).ready(function () {
function re_index($cont) {
$cont.find(".textbox_group").each(function (i) {
$(this).find('.text').attr("name", "data[" + i + "][text]");
$(this).find('.box').attr("name", "data[" + i + "][box]");
});
}
$("#append").click(function (e) {
e.preventDefault();
var $cont = $(".inc");
if ($(".textbox_group").length < 5) {
$cont.append("<div class='controls textbox_group'>\
<input class='text form-control' type='text' >\
<input class='box form-control' type='text' >\
<a href='#' class='remove_this btn btn-danger'>remove</a>\
</div>");
re_index($cont);
}
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
var $cont = $(".inc");
re_index($cont);
});
});
</script>
Then in PHP you can capture the data and iterate to insert it with SQL:
$data = $_POST['data'];
foreach ($data as $input) {
var_dump($input['text']);
var_dump($input['box']);
}

$.post JQuery not working

I have a problem with form. After i click Dodaj button nothing happens.
I've putted alert dialog to see when it stops and it stops after
$.post('dodaj_ztoner.php', post_data, function(response){
I have made similar forms with similar code (names and number of items was different) and it worked
alert('post'); is not displaying. so looks like problem is here $.post('dodaj_ztoner.php', post_data, function(response){
html code:
<body>
<div id="dialog" title="Błąd Wprowadzania!">
<p>Proszę uzupełnić podświetlone pola.</p>
</div>
<div class="container">
<fieldset id="contact_form">
<h2>Zużycie Tonera</h2>
<div id="zresult"></div>
<label for="id"><span>ID</span></label>
<input type="text" name="zid" id="zid" value="<?php
$zapytanie = "select max(id) as id from zuzycie_toner";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo $wynik['id']+1;
}
mysql_free_result($widok);
?>" disabled />
<label for="zdata"><span>Data wydania</span></label>
<input type="text" name="zdata" id="zdata" />
<label for="ilwyd"><span>Ilość wydrukowanych</span> </label>
<input type="text" name="ilwyd" id="ilwyd" />
<label for="drukarka"><span>Drukarka</span></label>
<select type="text" name="zdrukarka" id="zdrukarka" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from drukarki order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="toner"><span>Toner</span></label>
<select type="text" name="ztonery" id="ztonery" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwa from tonery order by nazwa";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[nazwa]</option>";
}
mysql_free_result($widok);
?>
</select>
<label for="user"><span>Użytkownik</span> </label>
<select type="text" name="zuser" id="zuser" >
<option selected="selected">Wybierz</option>
<?php
$zapytanie = "select nazwisko_imie as id from uzytkownicy order by nazwisko_imie";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
echo "<option>$wynik[id]</option>";
}
mysql_free_result($widok);
?>
</select>
<label><span> </span>
<button type="submit" class=submit_btn" id="zsubmit_btn">Dodaj</button>
</label>
JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var divObj = $('#dialog');
divObj.dialog({
autoOpen: false
}
);
$( "#zdrukarka" ).selectmenu();
$( "#zuser" ).selectmenu();
$( "#ztonery" ).selectmenu();
$("#zdata").datepicker();
$( "button[type=submit]" )
.button()
$("#zsubmit_btn").click(function() {
//Pobieramy dane
var ztoner_id = $('input[name=zid]').val();
var ztoner_data = $('input[name=zdata]').val();
var ztoner_wydr = $('input[name=ilwyd]').val();
var ztoner_toner = $('select[name=ztonery]').val();
var ztoner_user = $('select[name=zuser]').val();
var ztoner_drukarka = $('select[name=zdrukarka]').val();
//Prosta walidacja (kolorujemy na czerwono pole jeśli jest puste
var proceed = true;
alert( '1');
//wszystko w porządku idziemy dalej
if(proceed)
{
//Dane do wysłania
post_data = {'ztonerID':ztoner_id, 'ztonerWydr':ztoner_wydr, 'ztonerData' :ztoner_data, 'ztonerToner' :ztoner_toner,
'ztonerUser':ztoner_user, 'ztonerDrukarka':ztoner_drukarka};
//Przesłanie danych poprzez AJAX
$.post('dodaj_ztoner.php', post_data, function(response){
alert( 'post');
//wczytanie danych zwrotnych JSON
if(response.type == 'error')
{
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
}
$("#zresult").hide().html(output).slideDown();
}, 'json');
} else divObj.dialog("open");
});
//resetujemy kolorowanie po zaczęciu pisania
});
</script>
PHP file:
<?php
include './includes/html_elements.php';
//pokaz_zmienna($_SERVER);
$db_link = connect_db();
if(!$db_link)
{
$out='<p>Brak połączenia z bazą danych</p>';
print_page($out, 'Baza książek');
exit;
}
if($_POST)
{
//Sprawdzamy czy jest to rządanie Ajax, jeśli nie..
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//Kończymy skrypt wysyłając dane JSON
$output = json_encode(
array(
'type'=>'error',
'text' => 'Rządanie musi przejść przez AJAX'
));
die($output);
}
//Sprawdzamy czy wszystkie pola zostały wysłane. kończymy skrypt jeśli nie (tutaj dodawaj więcej pól, które są wymagane)
if(!isset($_POST["ztonerID"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'POLA SĄ PUSTE!'));
die($output);
}
//Pobieramy dane z formularza
$ztoner_id = filter_var($_POST["ztonerID"], FILTER_SANITIZE_STRING);
$ztoner_data = filter_var($_POST["ztonerData"], FILTER_SANITIZE_STRING);
$ztoner_wydr = filter_var($_POST["ztonerWydr"], FILTER_SANITIZE_STRING);
$ztoner_drukarka = filter_var($_POST["ztonerDrukarka"], FILTER_SANITIZE_STRING);
$ztoner_toner = filter_var($_POST["ztonerToner"], FILTER_SANITIZE_STRING);
$ztoner_user = filter_var($_POST["ztonerUser"], FILTER_SANITIZE_STRING);
//Dodatkowa validacja PHP (tylko dla pól wymaganych)
if(!is_numeric($ztoner_id)) //sprawdzamy czy telefon jest numeryczny
{
$output = json_encode(array('type'=>'error', 'text' => 'Tylko liczby są dozwolone'));
die($output);
}
die($output);
}
$zapytanie = "select idd from drukarki where nazwa = '$ztoner_drukarka'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_drukarka = $wynik['idd'];
}
mysql_free_result($widok);
$zapytanie = "select idu from uzytkownicy where nazwisko_imie = '$ztoner_user'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_user = $wynik['idu'];
}
mysql_free_result($widok);
$zapytanie = "select idt from tonery where nazwa = '$ztoner_toner'";
$widok = mysql_query($zapytanie);
while ($wynik = mysql_fetch_array($widok))
{
$ztoner_toner = $wynik['idt'];
}
mysql_free_result($widok);
$insert = "Insert INTO zuzycie_toner Values ($ztoner_id, '$ztoner_data', $ztoner_wydr, $ztoner_drukarka, $ztoner_toner, '$ztoner_user')";
$wykonaj = mysql_query($insert);
if ($wykonaj)
{
$output = json_encode(array('type'=>'message', 'text' => 'Dodano '.$drukarki_nazwa.' do tabeli'));
die($output);
}else{
$output = json_encode(array('type'=>'error', 'text' => 'Dodawanie nie powiodło się '.$insert));
die($output);
}
}
?>
Your page doesn't conatains any form tag, so simple use
<button class=submit_btn" id="zsubmit_btn">Dodaj</button> instead of input type = submit
This will Work!!!!

autocomplete search form with multiple input php mysql

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...

Categories