So I have this problem where I want to display multiple values to multiple input boxes depending on how many the value is. I have already a code but the problem is it is only displaying the value in one input box. I will show you the code.
Here is the database:
attId attSubject attDate docId
------ ----------------- ---------- ------
1 FAAS FRONT & BACK 2018-01-25 36
2 NOA & TAX BILL 2018-09-12 36
HTML code:
<input type="text" id="attchecklist" name="attchecklist">
Javascript code:
$("#num").val(mydata.docId);
var docIdChecklist = $("#num").val();
$("#attchecklist").load('php/getAttachmentForChecklist.php',
{docIdChecklist:docIdChecklist},
function(data) {
$("#attchecklist").val(data);
}
);
PHP code:
<?php
require_once('../kclass/kconnect.php');
require_once('../common.php');
session_name(xevPRJ);
session_start();
$response= new kconnect();
$response->DB = $_SESSION['sys'];
$docIdChecklist = $_POST['docIdChecklist'];
$response->setCon();
$sqlx = "SELECT attSubject from `attachment` WHERE ((docId = '$docIdChecklist') AND (is_deleted = 0))";
$resultx=$response->kMysqli->query($sqlx);
while($row=mysqli_fetch_array($resultx, MYSQL_ASSOC)){
$attSubject = $row['attSubject'];
echo $attSubject;
}
$response->unsetCon();
?>
and here is the result:
I want the result to be separated in input boxes. How to achieve this?
Assuming your div something like this
<div id="myDiv></div>
Then you can append your form using JS
...
$("#attchecklist").load('php/getAttachmentForChecklist.php',
{docIdChecklist:docIdChecklist},
function(data) {
data = JSON.parse(data);
$.each(data, function(index, value) {
$("#myDiv").append(`<input type="text" id="attchecklist${index}" name="attchecklist${index}" value="${value}">`)
});
}
);
However, you are expected to return JSON array of data, instead of just echo the data on PHP API. Something like this:
$result = [];
while($row=mysqli_fetch_array($resultx, MYSQL_ASSOC)){
array_push($result, $row['attSubject']);
}
$response->unsetCon();
echo json_encode($result);
Related
i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>
So I've been working on this code for awhile now and I've done a lot of debugging but can't figure this out. What I want to do is: if a checkbox is checked send a request to run a query on the mySQL database FROM items WHERE .class(of the checkbox) '<' this.value(of the checkbox again) then get the filtered results and then use my javascript to format it:
index.php:
<form>
<label><input type="checkbox" class="calories "name="calories" value="300">Less than 300</label><br>
<label><input type="checkbox" class="calories" name="calories" value="500">Less than 500</label><br>
</form>
<script>
$("input.calories:checkbox").on("change",function(){
if(this.checked){
var column = $(this).attr('class'); //The class determines which column of the table is called
var value = $(this).attr('value'); //Takes the numeric value from the selected box
console.log(column);
//$.post('showItems.php', {type: column});
//$.post('showItems.php', {value: value});
//Can we call the php code above to run a query using variables column and value?
//make a php function above and call it
// function below will run showItemss.php?c=column?v=value
$.ajax({
type: "POST",
url: "showItems.php" ,
data: { c: column,
v: value},
error: function(){console.log("error")},
success: function(data) {
console.log("success");
console.log(test);
console.log(filteredList);
</script>
Here is the PHP file showItems.php I'm calling (the relevant part):
//This array holds items from database.
$itemList = array();
//Connect and Select
$con = makeConnection($dbhost, $dbuser, $dbpass, $dbname);
//Get the value and type from the javascript below
//If the type is null display the whole table
$c = $_POST['c'];
//echo $c;
//$v = mysqli_real_escape_string($con,$v);
//$type = $_POST['value'];
if($c==null){
$query = "SELECT * FROM items";
}
else{
$v = $_POST['v'];
$query = "SELECT * FROM items WHERE ".$c."< ".$v."";
}
$result = mysqli_query($con, $query);
//Collect data from all items
while($row = $result->fetch_assoc())
{
$tempItem = new Item($row['itemID'], $row['itemName'], $row['price'], $row['description'], $row['calories'], $row['protein'], $row['choles'], $row['sodi'], $row['picLink']);
$itemList[] = $tempItem;
}
echo json_encode($query);
?>
<script>
var test = <?php echo json_encode($query); ?>;
var filteredList = <?php echo json_encode($itemList); ?>;
</script>
So I want this code to be run every time I click a checkbox in my Index.php file so I can get the updated filtered items, $itemList, but I cannot figure out how to do this. Something I've done to test this is store my php values as javascript variables, Include showItems.php then console.log the variables from ShowItems.php in Index.php, and the query isn't being updated upon click which makes sense I guess. In the AJAX success function 'data' contains the entire HTML source with an updated query, but I can't figure out how use only the specific code I need in the success function. Any ideas at all would be helpful.
Try doing this:
Go from on("change",...) to on("click",...)
Also try using instead of this.checked, $(this).prop("checked") which will return you true or false depending on wether the checkbox is checked or not.
You might want to change either your selector or your checkbox classes because both are the same, and can give you undesired functionality in order to get your values when you click on a checkbox, since the selector finds you both checkboxes.
Hope this ideas can get you closer where you want to be.
Cheers
I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}
Hi I currently have 2 < select>
The first one is filled from a button action from the page before and a database query. Depending on what you choose in the first < select>, the second < select> should get filled from a database query with the value of the first < select>. (I am using PDO prepare so I only need to change the parameter to whatever value the selected has)
I already know how I can get the values into javascript but I don't know how I can then write it into the php variable and execute the mysql query. As javascript is a client-side language, I don't think it's possible to execute the query there so I would need to get it to php somehow?
Select 1:
<select name = "select1" class = "select" size = "10" onChange = "function()">
<?php
while ($result1 = $query1->fetch(PDO::FETCH_OBJ)) {
?>
<option value = "
<?php
echo $result1->id;
?>">
<?php
echo $result1->text;
?>
</option>
<?php } ?>
</select>
Select 2:
<select name = "select2" class = "select" size = "10" onChange = "function(this.options[this.selectedIndex].value)">
<?php
while ($result2 = $query2->fetch(PDO::FETCH_OBJ)) { ?>
<option value = "
<?php
echo $result2->id . ";" . $result2->text . ";" . $result2->text2 . ";" . $result2->text3;
?>">
<?php
echo $result2->text;
?>
</option>
<?php } ?>
</select>
If you are curious, function is just displaying some divs and writing the values into some textboxes:
var str = select.split(";");
document.getElementById("div1").className = "";
document.getElementById("div2").className = "div";
document.getElementById("div3").className = "div";
document.getElementById("div4").className = "div";
document.getElementById("txt1").value = str[0];
document.getElementById("txt2").value = str[1];
document.getElementById("txt3").value = str[2];
document.getElementById("txt4").value = str[3];
php database query to fill select 1:
try {
$query1 = $db->prepare('SELECT id, text FROM tbl1 INNER JOIN tbl0 USING(id) WHERE id = ?');
$query1->execute(array($_POST['id']));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 1";
}
php database query to fill select 2:
try {
$query2 = $db->prepare('SELECT id, text, text2, text3 FROM tbl1 INNER JOIN tbl2 USING(id) WHERE id = ?');
$query2->execute(array($IDFROMSELECT1));
} catch(PDOException $ex) {
log_error($ex);
$arrError[] = "Error SQL 2";
}
How can I get the id (option value) from select 1 into the $IDFROMSELECT1 variable in php mysql query 2?
Any tips are much appreciated!
You will have to use AJAX to send the value of the select box to a PHP script which will run the query and send back the result. AJAX is easiest done with the jQuery library.
The javascript to run in onchange() would be something like this:
var selectedValue = $(this).val();
$.ajax({url: "getData.php",
type: "POST",
dataType: "json",
data: {id: selectedValue},
success: function(returnedData) {
//do something here with returned data
}
});
In the PHP script (getData.php), you would execute your select like normal, put the results into an array, then return that array as JSON (Javascript Object Notation). This will put the results of the query into a format that you can work with in javascript (in this case, adding the returned results to another select box)
$json = json_encode($returnArray);
echo $json;
So I'm trying to populate a select box within my html with array objects using JSON results, I've been looking at all this code so long I don't think I'm seeing the simple solution to my problem. This is my callback function where I'm populating the select box. The JSON request has went through fine but I am stuck with a blank select box everytime.
function getArtistsCallBack()
{
if (req.readyState == 4) {
if (req.status == 200) {
// TO DO: populate artistlist select box using JSON
var response = req.responseText.parseJSON();
var artistSelect = document.getElementById("artistlist");
for (i=0;i<response.artistsarray.length;i++){
var artist_id = response.artistsarray[i].artist;
var artist = response.artistsarray[i].artist;
artistSelect.options[artistSelect.options.length] = new Option(artist, artist_id, false, true);
}
}
}
}
Here is the select box within the HTML for reference just in case;
<div id="artistscontent">
<select id="artistlist"></select>
</div>
This is artists.php where a database is queried for an array of objects, the array that is used previously;
<?php
// Include utility files
require_once 'include/config.php';
// Load the database handler
require_once BUSINESS_DIR . 'database_handler.php';
// Load Business Tier
require_once BUSINESS_DIR . 'collection.php';
$artistsarray = Collection::GetArtists();
print json_encode($artistsarray);
$jsonresponse='{"artistsarray":[';
foreach($artistsarray as $artist => $row)
{
$artist_id=$artist+1;
$artist=$row['artist'];
$jsonresponse .= '"artist_id":"' . $artist_id . '"},';
$jsonresponse .= '"artist:"' . $artist . '"},';
}
$jsonresponse .= ']}';
echo $jsonresponse;
?>
Any help would be much appreciated! Thanks!
You need to use the json length for the options array and do it outside of the for loop. Then use options.add
var json = [{key:'1', value:'value1'},{key:'2', value:'value2'}]
var artistSelect = document.getElementById("artistlist");
artistSelect.options[json.length];
$.each(json, function(key, value){
console.debug(value);
artistSelect.options.add(new Option(value.key, value.value));
});
Check out this plunker:
http://plnkr.co/edit/i3A6mo672CskXvbstWsu?p=preview
The artistSelect.options is not an array, you need to use the add method:
var opt = new Option(artist, artist_id);
artistSelect.options.add(opt);