Ajax isn't working properly with my PHP script - javascript

I am programming in HTML5, PHP and JavaScript. I am trying to use Ajax to do this: when I select one option on #productoSeleccionado appear the sizes of this products that is #tallaSeleccionada but I think that this code it's no fine. I believe that the code of function and call to data base it's fine.
I have imported the library jQuery-ajax. productoSeleccionado works good but when I select one of the options don't appear nothing in the select of tallaSeleccionada. I don't know how to put it.
<p>
<h3>Seleccione producto:</h3>
<select id="productoSeleccionado" name="producto">
<?php foreach ($productos as $producto) { ?>
<option value="<?php echo $producto["OID_P"]; ?>">
<?php echo $producto["CODIGO"] . "- " . $producto["CONCEPTO"]; ?>
</option><?php } ?>
</select>
</p>
<script type="text/javascript">
$("#productoSeleccionado").on("option", function () {
$.get("gestionar_Selects.php", {
productoSeleccionado: $('#productoSeleccionado').val()
},
function (data) {
$("#tallaSeleccionada").empty();
$("#tallaSeleccionada").append(data);
}
);
});
</script>
<p>
<h3>Seleccione talla:</h3>
<select id="tallaSeleccionada" name="talla"></select>
</p>
This code I think that is good is gestionar_Selects.php
<?php
function listarTallas($conexion, $productoSeleccionado)
{
try {
//Puedo poner en vez de * NOMBRE_TALLA probado
$stmt = $conexion->prepare('SELECT * FROM ASOC_LOCAL_PRODUCTO LEFT JOIN PRODUCTOS ON (ASOC_LOCAL_PRODUCTO.OID_P = PRODUCTOS.OID_P)'
. 'LEFT JOIN TALLAS ON (ASOC_LOCAL_PRODUCTO.OID_T = TALLAS.OID_T) LEFT JOIN LOCALIZACIONES ON (ASOC_LOCAL_PRODUCTO.OID_L = LOCALIZACIONES.OID_L) '
. ' WHERE PRODUCTO.OID_P =:W_OID_P ORDER BY STOCK_MINIMO');
$stmt->bindParam(':W_OID_P', $productoSeleccionado);
$stmt->execute();
return "";
} catch (PDOException $e) {
return $e->getMessage();
}
}
if (isset($_GET["producto"])) {
$conexion = crear_conexionBD()();
$resultado = listarTallas($conexion, $_GET["producto"]);
if ($resultado != NULL) {
foreach ($resultado as $talla) {
echo "<option value= "$talla["OID_T"]" > $talla["NOMBRE_TALLA"]</option>";
}
}
cerrar_conexionBD()($conexion);
unset($_GET["producto"]);
}
?>

Change your Javascript to use on('change').
<script type="text/javascript">
$("#productoSeleccionado").on('change', function () {
$.get("gestionar_Selects.php", {productoSeleccionado: $('#productoSeleccionado').val()}, function (data) {
$("#tallaSeleccionada").empty();
$("#tallaSeleccionada").append(data);
}
);
});
</script>
In your PHP
<?php
function listarTallas($conexion, $productoSeleccionado)
{
try {
//Puedo poner en vez de * NOMBRE_TALLA probado
$stmt = $conexion->prepare('SELECT * FROM ASOC_LOCAL_PRODUCTO LEFT JOIN PRODUCTOS ON (ASOC_LOCAL_PRODUCTO.OID_P = PRODUCTOS.OID_P)'
. 'LEFT JOIN TALLAS ON (ASOC_LOCAL_PRODUCTO.OID_T = TALLAS.OID_T) LEFT JOIN LOCALIZACIONES ON (ASOC_LOCAL_PRODUCTO.OID_L = LOCALIZACIONES.OID_L) '
. ' WHERE PRODUCTO.OID_P =:W_OID_P ORDER BY STOCK_MINIMO');
$stmt->bindParam(':W_OID_P', $productoSeleccionado);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // get rows from DB
return $rows;
} catch (PDOException $e) {
return $e->getMessage();
}
}
if (isset($_GET["productoSeleccionado"])) {
$conexion = crear_conexionBD()();
$resultado = listarTallas($conexion, $_GET["productoSeleccionado"]);
if ($resultado != NULL) {
foreach ($resultado as $talla) {
echo '<option value="' . $talla["OID_T"] . '" > ' . $talla['NOMBRE_TALLA'] . '</option>';
}
}
cerrar_conexionBD()($conexion);
unset($_GET["productoSeleccionado"]);
}
?>

Related

Dependent dropdown not working correctly

this is my first time on this site so I'll cut to chase.
I've been working on a fixed assets control web system using PHP, AJAX, jquery and MySQL as database (the project structure was made by following the tutorial from this website: https://www.itechempires.com/2016/07/pdo-crud-operations-using-php-bootstrap/ ), where such items are registered along with the categories to which each asset belongs, the transactions made by the users within the company and the reports generated by each transaction.
Currently I'm stuck with the dropdowns since I tried anything I could to make them work but without the results I've been looking for, which is:
in a modal there's a form where an asset is going to be added with its related information, two of those details are categories and subcategories which are handled by dependent dropdowns, the dropdown regarding to subcategories will be displayed once a category is selected.
The code snippets will be up for review which will be focused on the ones related to the dropdowns:
Tables
grupo (group or category)
id_grp (group id,autoincremented, not visible by the user)
codigo_grp (code)
nombre_grp (name)
subgeupo (subgroup or subcategory)
id_sgrp (subgroup id, autoincremented, not visible by the user)
codigo_sgrp (code)
nombre_sgrp (name)
vidaUtil_sgrp (useful life)
id_grp (group id, foreign key)
libAF.php: Contains all queries for crud operations
/*
* Get group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelGrp()
{
$query = $this->db->prepare("SELECT id_grp, nombre_grp FROM grupo");
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
/*
* Get sub-group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelSgrp($id_grp)
{
$query = $this->db->prepare("SELECT * FROM subgrupo WHERE id_grp = :id_grp");
$query->bindParam("id_grp", $id_grp, PDO::PARAM_STR);
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
populateSelGrp.php: loads the categories on to the parent dropdown
<?php
require 'libAF.php';
$data = "";
$object = new CRUD();
$grupos = $object->populateSelGrp();
$data .= '<select id="select_grp" class="form-control" onchange="populateSelSgrp()">';
$data .= '<option value="0" disabled selected>Escoja grupo</option>';
if (count($grupos) > 0) {
foreach ($grupos as $grupo) {
$data .= '<option id="selected_grp" value="' . $grupo['id_grp'] . '"> ' . $grupo['nombre_grp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
?>
populateSelSgrp.php: loads the subcategories on to the child dropdown
<?php
require 'libAF.php';
if (isset($_POST['id_grp']) && isset($_POST['id_grp']) != "") {
$id_grp = $_POST['id_grp'];
$data = "";
$object = new CRUD();
$subgrupos = $object->populateSelSgrp($id_grp);
$data .= '<label for="select_sgrp">Sub-grupo</label>';
$data .= '<select id="select_sgrp" class="form-control">';
$data .= '<option value="0" disabled selected>Escoja sub-grupo</option>';
if (count($subgrupos) > 0) {
foreach ($subgrupos as $subgrupo) {
$data .= '<option value="' . $subgrupo['id_sgrp'] . '"> ' . $subgrupo['nombre_sgrp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
}
?>
scptAF.js: Contains the scripts needed to make the inputs work
function populateSelGrp(){
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function populateSelSgrp(id_grp){
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
activos.php (assets): visible page where the user adds, removes or updates an asset.
<div class="form-group">
<label for="select_grp">Grupo</label>
<div class="option_grp"></div>
</div>
<div class="form-group">
<div class="option_sgrp"></div>
</div>
I finally found a solution for this mess, was a little code I had to add to the javaScript file to send the id to the second dropdown. Although I finally fixed my problem, I'd like to see other suggestions on how to tackle this problem.
Here's my snippet
scptAF.js
function populateSelGrp() {
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function changeGrpId(){
var id_grp = document.getElementById("select_grp").value;
populateSelSgrp(id_grp);
}
function populateSelSgrp(id_grp) {
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}

Onchange populate different dropdown based on value

I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>

Why is my angularjs multiselect interface not working?

I am an angular newbie using the multiselect directive from isteven.
I wrote a test case, which works fine from the HTML in the root folder, but when I incorporated it into my app, none of the drop-downs are visible.
There are no console.log error messages.
I bundled the HTML and controller into the same file.
The "myApp.controller('MainCtrl', function ($scope, $http)" does not get executed although the "var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);" does.
<html data-ng-app="myApp" id="myApp" lang="en">
<head>
<title>Writer's Tryst - Enablers Form</title>
<link type="text/css" href="css/enablers.css" rel="stylesheet" />
<link rel="stylesheet" href="css/isteven-multi-select.css">
</head>
<body data-ng-controller="MainCtrl">
<div class="container center_div">
<!--<form id="form-writers" class="form-horizontal well">-->
<img id="img-enablers" src="#" alt="images" />
<form id = "form-enablers" class="form-horizontal well">
<h1>Enablers</h1>
<label for="work-type" class="fixed50">Type:</label>
<p id="work-type"
data-isteven-multi-select
data-input-model="worktype"
data-output-model="outputWorktype"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<label for="form-type" class="fixed50">Form:</label>
<p id="form-type"
data-isteven-multi-select
data-input-model="formtype"
data-output-model="outputFormtype"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<p>For an explanation of the genres s hown here, see <a target="_blank" href="https://en.wikipedia.org/wiki/List_of_genres">List of genres</a><br/></p>
<label for="genres" class="fixed50">Genres:</label>
<p id="genres"
data-isteven-multi-select
data-input-model="genres"
data-output-model="outputGenres"
data-button-label="name"
data-item-label="name"
data-tick-property="ticked"
></p>
<label for="accepted-media" class="fixed50">Accepted Media:</label>
<p id="accepted-media"
data-isteven-multi-select
data-input-model="acceptedMedia"
data-output-model="outputMedia"
data-button-label="icon name"
data-item-label="icon name"
data-tick-property="ticked"
></p>
<p> <label for="special-instructions" class="fixed50">Special Instructions</label>
<textarea id ="special-instructions" name="special-instructions">
</textarea>
</p>
<p>For a limited time, enablers can use this site for <span style="color: #f00; font-weight:bold">FREE</span>. We reserve the right to change this policy without notice.</p>
<div id="recaptcha-elements"></div>
<div class="form-group">
<button type="submit" id="enablers-search" class="btn btn-default glyphicon glyphicon-search"> Search</button>
</div>
<input id="userid" name="userid" type="hidden" />
</form>
</div>
<form id="writers-list">
<p>To request a manuscript, click the checkbox beneath the thumbs-up icon.</p>
<div id="table-list"></div>
</form>
<script src="js/isteven-multi-select.js"></script>
<script src="js/enablers.js"></script>
<script src="js/recaptcha.js"></script>
<script>
var myApp = angular.module( "myApp", [ "isteven-multi-select" ]);
myApp.controller('MainCtrl', function ($scope, $http) {
alert("got here");
$scope.worktype = [
{ icon: "<img src=img/icons/smile-mask.png />", name: "Fiction", ticked: false },
{ icon: "<img src=img/icons/frown-mask.png />", name: "Non-Fiction", ticked: false }
];
$scope.formtype = [];
var data = {};
data.action = 'multiselect-forms';
ajax('post', 'php/enablers.php', data, formsSuccess, 'Error retrieving multiselect forms data: ');
function formsSuccess(data) {
console.log(data);
$scope.formtype = eval(data);
}
$scope.genres = [];
data.action = 'multiselect-genres';
ajax('post', 'php/enablers.php', data, genresSuccess, 'Error retrieving multiselect forms data: ');
function genresSuccess(data) {
console.log(data);
$scope.genres = eval(data);
}
$scope.acceptedMedia = [
{ icon: "<img src=img/icons/email.png />", name: "Mail", ticked: false },
{ icon: "<img src=img/icons/pdf.png />", name: "PDF File", ticked: false }
];
/*
$http({
method: "POST",
url: "php/enablers.php",
params: data,
contentType: 'text'
}).then(function mySucces(response) {
console.log(response.data);
// $scope.formtype = response.data;
}, function myError(response) {
$scope.FORMTYPE = response.statusText;
});
*/
})
</script>
</body> s
</html>
Notice, I resorted to using jQuery Ajax because angular kept insiting on JSON, even though the header from the PHP interace specified content-type of text/plain as well as the http call specifiing contentType = 'text'
PHP
<?php
require_once 'dbconnect.php';
function isEmpty($str) {
return strlen(trim($str)) == 0;
}
function buildInStmt($array)
{
if (is_array($array)) {
$in = implode(',', $array);
} else $in = "'" . $array . "'";
return $in;
}
function multiselectGenres()
{
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Genre FROM Genres ORDER BY Genre");
if (!$stmt->execute()) {
echo "\nPDOStatement::errorCode(): ";
print $stmt->errorCode();
print_r($dbh->errorInfo());
} else {
$select = "[";
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$genre = $row['Genre'];
$id = $row["ID"];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $genre . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
}
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
function multiselectForms() {
try {
$dbh = connect2DB();
$stmt = $dbh->prepare("SELECT ID, Form FROM Forms ORDER BY Form");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$select = "[";
foreach ($rows as $row) {
$id = $row['ID'];
$form = $row['Form'];
$select .= "{";
$select .= 'name: ';
$select .= '"' . $form . '",';
$select .= 'ticked: false},';
}
$select = substr($select, 0, -1) . "]";
header("Content-Type: text/plain");
echo $select;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General failure: ' . $e->getMessage();
}
}
function search() {
try{
/*
if (!isset($_REQUEST["work-type"]) || isEmpty($_REQUEST["work-type"]))
throw new Exception('You must select a type of work.');
else {
$worktype = filter_var(trim($_REQUEST["work-type"]), FILTER_SANITIZE_STRING);
$worktype = htmlspecialchars_decode($worktype, ENT_QUOTES);
}
*/
manageEnablerData();
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
if (!isset($_REQUEST["form-type"]) || empty($_REQUEST["form-type"])) {
throw new Exception('You must select a form type.');
}
$forms = buildInStmt($_REQUEST["form-type"]);
if (!isset($_REQUEST["genre"]) || empty($_REQUEST["genre"])) {
throw new Exception('You must select a genre.');
}
$genres = buildInStmt($_REQUEST["genre"]);
/*
if (!isset($_REQUEST["sub-genre"]) || isEmpty($_REQUEST["sub-genre"]))
throw new Exception('You must select a sub-genre.');
else {
$subgenre = filter_var(trim($_REQUEST["sub-genre"]), FILTER_SANITIZE_STRING);
$subgenre = htmlspecialchars_decode($subgenre, ENT_QUOTES);
}
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("SELECT a.ID, a.Email, a.Name, w.Title, w.Filename FROM Writers w JOIN Accounts a ON a.ID = w.fkAccounts WHERE a.ID = :userid AND FormType IN($forms) AND Genre IN($genres)");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll();
$table = '<table><tr><th>Author</th><th>Title</th><th>Synopsis</th><th><img src="img/Thumb-up-icon.png" width="32" alt="thumbs-up" </th></tr>';
foreach ($rows as $row) {
$table .= "<tr><td>" . $row['Name'] . "</td><td>" . $row['Title'] . "</td><td>" . "<a href='uploads/" . $row['Filename'] . "' target=_blank>synposis file</a>" . "</td><td><input type='checkbox' id='request-manuscript' name='request-manuscript'" . "</td><td class='hidden'>" . $row['ID'] . "</td><td class='hidden'>" . $row['Email'] . "</td></tr>";
}
$table .= "</table>";
echo $table;
} catch (PDOException $e) {
echo 'Database error: ' . $e->getMessage();
} catch (Exception $e) {
echo 'General error: ' . $e->getMessage();
}
}
function manageEnablerData()
{ $si = ""; //special-instructions
if (isset($_REQUEST["special-instructions"]) && !isEmpty($_REQUEST["special-instructions"])) {
$si = filter_var(trim($_REQUEST["special-instructions"]), FILTER_SANITIZE_STRING);
$si = htmlspecialchars_decode($si, ENT_QUOTES);
}
if (!isset($_REQUEST["userid"]) || isEmpty($_REQUEST["userid"])) {
throw new Exception('A user-id must be supplied.');
}
$userid = $_REQUEST["userid"];
/*
if (!isset($_REQUEST["accepted-media"]) || empty($_REQUEST["accepted-media"])) {
throw new Exception('An accepted media must be entered.');
}
$acceptedMedia = buildInStmt($_REQUEST["accepted-media"]);
*/
$dbh = connect2DB();
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT Enablers(fkAccounts, SpecialInstructions) VALUES(:fka, :si) ON DUPLICATE KEY UPDATE fkAccounts=VALUES(fkAccounts), SpecialInstructions=VALUES(SpecialInstructions)");
$stmt->bindParam(':fka', $userid, PDO::PARAM_INT);
$stmt->bindParam(':si', $si, PDO::PARAM_STR);
$stmt->execute();
//need to handle AcceptedMedia
}
//var_dump($_REQUEST);exit();
if (!isset($_REQUEST['action']) || isEmpty($_REQUEST['action']))
throw new Exception('Programmer error: action not posted.');
else {
$action = $_REQUEST['action'];
switch($action) {
case 'search':
search();
break;
case 'select':
select();
break;
case 'multiselect-genres':
multiselectGenres();
break;
case 'multiselect-forms':
multiselectForms();
break;
default:
throw new Exception("Unknown action: " . $action);
break;
}
}
?>
If you decide I deserve a downvote, please help me to understand what I am doing wrong so that I may learn from my mistakes.
1. Why not work:
a). In your test case, you've put <body data-ng-controller="MainCtrl"> in your html, and this will call MainCtrl function.
b). In your app, you also have a MainCtrl, but you neither call in from html nor $routeProvider.when
Solutions:
1). The easiest way: do <body data-ng-controller="MainCtrl"> in your app, the same as your test case.
2). Put codes inside of MainCtrl into enablersController.If just need this select input model in page #/enablers.
Both are guesses, try and if any problems let me know.

Passing php variable onclick gives error

Please see the scripts below. Onclick of Add gives an error when a php variable ($var)is used, however it will work with a number - i.e. if the line in index.php:
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>';
Is changed to something like:
echo '<button id="1" onclick="company_add(',57776,');">Add</button>';
What am I missing please?
Index.php:
<html>
<head>
<script type ="text/javascript">
function company_add(company_name) {
$.post('company_add.php', {company_name:company_name}, function(data) {
if (data == 'success'){
alert("Cool");
} else{
alert(data);
}
});
}
</script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<?php
include 'connect.php'; //Generic connect file
$var = 'Name';
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>
<br/>';
?>
</body>
</html>
company_add.php:
<?php
include 'connect.php';
function company_exists($company_name) {
return (mysql_result(mysql_query("SELECT COUNT(`company_name`) FROM
`company` WHERE `company_name` = $company_name"), 0) == 0 ) ? false :
true;
}
function add_company($company_name){
mysql_query("INSERT INTO `company` (`id`, `company_name`) values ('',
".$company_name.")");
}
$company_name = $_POST['company_name'];
if (company_exists($company_name) === true) {
echo 'Company already added';
} else {
add_company($company_name);
echo 'success';
}
?>
Use that line like this:
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
In case if you already have commas after and before the value of the $var you should trim it.
So use it like this:
$var = ltrim(",", $var);
$var = rtrim(", ", $var);
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
And for your information yes you can even use a String instead of a Number too.
And UPDATE the functions:
function company_exists($company_name) {
$company_name = mysql_real_escape_string($company_name);
$query = "SELECT * FROM company WHERE company_name = '{$company}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
return true;
}else{
return false;
}
}
function add_company($company_name){
$company_name = mysql_real_escape_string($company_name);
$query = "INSERT INTO company (id, company_name) VALUES ('', '{$company_name}')";
return mysql_query($query);
}
If you are using id field of that company table as AUTO_INCREMENT then you can leave the id field NAME & VALUE in the INSERT Statement.
Like This in the add_company Function:
$query = "INSERT INTO company (company_name) VALUES ('{$company_name}')"

PHP & AJAX not returning values within form element

I'm trying to use AJAX and PHP to update the options of a drop down menu based on the previous selection from another drop down menu.
I have this script in the head of my document:
<script>
function show_districts(str)
{
if (str.length==0)
{
document.getElementById("districts_dropdown").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("districts_dropdown").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_districts.php?q="+str,true);
xmlhttp.send();
}
</script>
... which, when onchange() is triggered, passes the value of this drop down:
<label for="banner" class="medium">Banner</label>
<select name="banner" id="banner" class="textbox short_field" onchange="show_districts(this.value)">
<option value=""></option>
<?php
$result = mysql_query("SELECT name FROM banners", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $banner) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
?>
</select>
... to this php file:
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
$q = $_REQUEST['q'];
if($q = 'TBOOTH') {$id = 2;}
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = '".$id."' GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo ' selected';} ;
echo '>' . $row["name"] . '</option>';
}
mysqli_close($connection);
?>
... which should return the values from the php file to this drop down menu with <span id="districts_dropdown">:
<label for="district" class="medium">District</label>
<select name="district" class="textbox short_field">
<option value=""></option>
<span id="districts_dropdown"></span>
</select>
This works nicely if <span id="districts_dropdown"> is outside of the <select> tags, but not within. Any insight as to why would be greatly appreciated.
Thanks for you help Popnoodles! I fixed part of the problem by having the php code generate the entire <select> tag like this:
<?php
$q = $_REQUEST['q'];
$id = "";
if ($q = 'TBOOTH') {
$id = "2";
} else {
if ($q = 'WIRELESS ETC') {
$id = "3";
}
}
echo '<select name="district" class="textbox short_field">
<option value=""></option>';
$query = "SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = '".$id."' GROUP BY dist.id ORDER BY dist.id ASC";
$result = mysql_query($query, $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo ' selected';} ;
echo '>' . $row["name"] . '</option>';
}
mysql_close($connection);
?>
But now the $id variable I have at the top of that code isn't updating when the onchange() is triggered.
It looks like you want to repopulate the options in a select tag. First of all you cannot put a span in there. Please adhere to the specs - <select> tags can only contain <option> and <optgroup> tags.
This is what you're changing
document.getElementById("districts_dropdown").innerHTML=xmlhttp.responseText;
So what will happen if you target this instead
<select name="banner" id="banner" class="textbox short_field" onchange="show_districts(this.value)">
with
document.getElementById("banner").innerHTML=xmlhttp.responseText;
You get options. http://jsfiddle.net/Da26e/1/

Categories

Resources