Hi Guys I am stuck with my coding. I hope someone can help me with my problem
So I have this class (updateProgress.php) that pulls the value from the DB and process it thru ajax on the other page called data2.php and display the query when user press the show button to the in (updateProgress.php).
What i have in the data2.php is,
<?php
// IF SHOW KEY HAS BEEN PRESSED
if($_POST['action'] == 'show')
{
$sql = "SELECT * FROM SUB_MASTER_DRAWING
WHERE SUB_MASTER_DRAWING.HEAD_MARK = '{$_POST["hm"]}'";
$query = oci_parse($conn, $sql);
$query_exec = oci_execute($query);
echo "<table border='1'>";
while($row = oci_fetch_assoc($query)){
echo '<div id="content">';
echo '<table cellspacing = "0"';
echo '<tr><th>Head Mark</th>
<th>Cutting</th>
<th>Assembly</th>
<th>Welding</th>
<th>Drilling</th>
<th>Finishing</th>
</tr>';
echo "<tr><td><b>$row[HEAD_MARK]/$row[ID]</b></td>";
if ($row['CUTTING'] == 'Y'){
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' checked='checked' disabled='disabled'/></td>";
} else {
echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' onClick='checkboxCheck()' /></td>";
}
?>
So my problem is when user check the checkbox, it should make a query to the database and update the corresponding value. I tried making the javascript function just to check if the checkbox action works on the outside the php tag but it just doesnt do anything.
is it because i pass all the table query to the so that it wont process the javascript ?
please help me
You already have checkbox with onClick='checkboxCheck()' assigned. Just make an ajax call from that javascript function and update whatever value you want from that call. You can create another php file to handle this ajax call.
function checkboxCheck() {
var checkbox1 = document.getElementById("cuttingCheckbox");
if (checkbox1.checked) {
alert('CHECKBOX CHECKED');
} else {
alert('CHECKBOX NOT CHECKED');
}
// Make Ajax call here, to call a php file
// which will update the db table
// You will have to pass other relevant variables like row id etc
}
That code is ready for a SQL Injection.
I'd suggest just using jQuery for handling the clicking of the checkbox:
$('#cuttingCheckbox').click(function() { /* function goes here */ });
(or use mousedown instead of click)
And then just have a simple AJAX call to a PHP file. AJAX is really simple and quick with jQuery.
Related
I need to get the value of the selected item on the drop down selection populated from sql database. Then that value is needed in the sql statement to get the specific record.
I already populated the drop down selection. Code below
<select name="year" id="year">
<?php
$query = mysql_query("SELECT distinct Year(fromdate) FROM emp WHERE empcode='$emp' order by Year(fromdate) desc");
while ($row = mysql_fetch_array($query)){
$year = $row[0];
echo "<option value=\"".$year."\">".$year."</option>";
}
?>
</select>
This is the php code for me to get the record using the value from the drop down.
<?php
$sql = mysql_query("SELECT salary FROM emp WHERE empcode='$emp' and Year(fromdate) = '$year'");
$row = mysql_fetch_array($sql);
$salary=$row[0];
?>
Then after that I need to pass the result to a textbox
<input id="salary" name="salary" value="<?php echo $salary; ?>">
What is the code needed for me to pass the selected item value from drop down "year" to PHP variable $year for sql statement? I already looked here in Stack Overflow for the answers but there is no question that look like mine.
What is wrong with people it needs sql why vote down
Do an ajax call to your php file, listening to your select onchange event, like so:
$('#year').on('change', function() {
$.post( "path/file.php", {
year: $(this).val()
})
.done(function( data, status ) {
console.log('data: '+data+' status: '+status);
if(status == 'success'){
//pass to your input ?
//data is what your php file will echo/output
$('#salary').val(data);
}else{
//how do you want to handle http error ?
}
});
});
If you want to get select box value without refreshing page then you need to do code with AJAX.
http://api.jquery.com/jquery.ajax/
On change please pass the year value to AJAX and then in AJAX file write down query for salary getting and after success full result put this value in salary filed using jQuery function
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 have a jQuery drop down list that uses first CARS then secondly, the models from that car. Then, when the second choice is made - hit a submit button and search for the tire that the car uses. It works great the first time, but the second time, it stops and I have to reload the page to get it to work again. Any ideas of why this is happening would be helpful. My code example is here:
Accessing a variable from inside a jquery drop down list?
Here is the code that searches:
function findtire() {
global $db;
if (isset($_POST['car'])) {
$_SESSION['car'] = $_POST['car'];
$car = $_SESSION['car'];
}
if (isset($car)) {
$query = $db->prepare("SELECT idtires FROM vehicle WHERE idcarmodel = '$car'");
$query->execute();
$tire = $query->fetchAll();
}
if (isset($tire)) {
echo "<ul>";
foreach ($tire as $name) {
echo "<li id='tiresearch'>";
echo "Tire Size is Available: " . $name['idtires'];
echo "</li>";
}
echo "</ul>";
}
else {
}
}
Sorry to add another JavaScript object to the mix. I'm just having a little trouble wrapping my head around this as it is a little more complex than i have ever dealt with.
Like the title states, i'm trying to create a JavaScript Object or perhaps a multidimensional array of a MySQL Database. For testing purposes i'm only using three tables from my database even though eventually it will store tens of tables. These tables are called "Interfaces", "IPAM", and "DNSF".
The reason i would like to complete this task is that, i am trying to create a heavy ajax page which dynamically knows when tables are added, updated, deleted etc, and automatically reflects this without having to add more code. I am doing this by writing javascript with php in addition to various other ajax callbacks spitting out html and variables.
Let me start out with my hardcoded HTML. All other html is created dynamically. This too will soon be created dynamically to add buttons to my website without adding code.
<body>
<div class = "form">
<button type="button" class = "formbutton" value = "Interfaces" onclick="inputChoice('Interfaces')">Interfaces</button>
<button type="button" class = "formbutton" value = "IPAM" onclick="inputChoice('IPAM')">IPAM</button>
<button type="button" class = "formbutton" value = "DNSR" onclick="inputChoice('DNSR')">DNSR</button>
</div>
<div class = "tableDiv" id="myTableDiv" style="height:1000px;width:1000px;border:1px solid #ccc; overflow: scroll;"><table id = "myTable"></table></div>
</body>
Before any buttons or events are executed, the first thign my page does is issue ajax requests within a $( document ).ready(function() { function. My issue is that i have to code a seperate ajax request for every single table. I'll show an example here where i fetch interface table data:
$.ajax({
url:"/ryan/nonEmber/ajax.php?table=Interfaces",
beforeSend: function(XMLHttpRequest){},
success: function(data, textStatus) {
InterfacesCols = data.split(" ");
InterfacesCols.pop();
$.getJSON("/ryan/nonEmber/getJson.php?table=Interfaces", function( data ){
var items = [];
$.each(data.post, function(key, val){
items.push(val);
});
for(i = 0; i < items.length; i++){
var myString = '<tr id = "visibleRow">';
for(j = 0; j < InterfacesCols.length; j++){
if(InterfacesCols[j] != null){
myString = myString + '<td id = "visibleDef">' + items[i][InterfacesCols[j]] +'</td>';
}
}
myString = myString + '</tr>';
Interfaces.push(myString);
}
});
}
});
This ajax request ultimately creates an array of html strings that are used to create the table. Interfaces[] contains each html row. InterfacesCols contains the names of each column. I have to write this block of code for every single table.
What i want to do is put my "Interfaces[]" like arrays and "InterfacesCols[]" like arrays within a master array so that i can create a template and not have tons of the same code.
Lets call this master array tables. This would allow me to put my ajax in a for loop and loop through every table array rather than hardcode it.
tables[0] would be interfaces[], tables[1] would be ipam etc.
In addition to my ajax request blocks where i initially gather my data from the database. I also have my function "inputChoice(string)", where i actually generate a table from this data. I do so by changing inner html of my table. I dont wan't to have to redirect my page. This works fine, but once again i have to create a new block of code for every single table. These blocks of code are massive right now because they include garbage collection for the DOM and also the code for handling massive data sets(>10,000) without browser slow down. I will refrain from posting that block unless necessary. The ajax calls require the same thing.
Here is the php where i originally create the empty array variables by generating javascript:
<?php
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
echo '<script>';
try{
$stmt->execute();
echo 'var tables = [];';
while($row = $stmt->fetch()){
echo 'var '.$row['TABLE_NAME'].' =[];';
echo 'tables += '.$row['TABLE_NAME'].';';
echo 'var '.$row['TABLE_NAME'].'Cols =[];';
}
echo 'console.log(tables[1]);';
}catch(PDOException $e){
echo $e;
}
echo '</script>';
?>
The above php is only called by using an statement on my index. No Ajax.
The link my ajax calls is this:
<?
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
//$stmt2->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
foreach($colnames as $value){
print $value ." ";
}
?>
The above ajax servers only the purpose of fetching column names and returning the names in a space delimeted string to be parsed and turned into an array via javascript, which you can see in my ajax call.
My getJson ajax code is here:
<?php
include "connect.php";
$sql = "DESCRIBE ".$_GET['table'];
$stmt = $DBH->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$colnames;
try{
$stmt->execute();
$colnames = $stmt->fetchAll(PDO::FETCH_COLUMN);
}
catch(PDOException $e){
echo $e;
}
$sql = "SELECT * FROM ".$_GET['table']." LIMIT 17000";
$stmt2 = $DBH->prepare($sql);
$stmt2->setFetchMode(PDO::FETCH_ASSOC);
try{
$stmt2->execute();
while($row = $stmt2->fetch()){
foreach($colnames as $value){
if($row[$value] == null){
$row[$value] = "";
}
}
$row = array('id' => $i) + $row;
$items['post'][]=($row);
$i++;
}
}
catch(PDOExcetipn $e){
echo $e;
}
print json_encode($items);
?>
The above php seems slightly redundant to me as i fetch the column names again. However this time i also include the actual data. Line by line.
This is basically all of my code i have written for this project. The only code i did not include was my javascript inputChoice() function. Which as i stated above is very bulky and really doesnt do anything the ajax doesnt do when it comes to utilizing the arrays. This is a massive post, so i apologize for the wall of text. I am not sure exactly what the next step is for me to code this better in the way i described. Any input would be very much appreciated!
If I'm correct you want to automate the table generating.
Your index php block retrieves all tables from the DB.
$sql= "SELECT
TABLE_NAME
FROM information_schema.TABLES
WHERE
TABLE_TYPE='BASE TABLE'
AND TABLE_SCHEMA='NJVCtestDB'";
So we need to add those to a master table pseudo code:
tables = [];
for (table in tableSQL)
{
tables[table] = tableSQL[table];
tables[table]['cols'] = [];
}
Now you have a master table array containing all your tables.
Let's loop through these. pseudo code:
for (table in tables)
{
retrieveColsWithData(table);
}
function retrieveColsWithData(tableKey)
{
//table = key = table name in DB
$.ajax({url:"/ryan/nonEmber/ajax.php?table="+table, etc.
//rest of the ajax call you're doing. Pass the key var to the JSON function
});
}
The function above loops through all the tables and retrieves the colls. When the JSON request returns you simply add the colls to table[key]['cols'].
Now you can simply iterate over the tables master with a for in or Object.keys and draw the HTML containing the data.
You can reuse retrieveColsWithData connected to your inputChoice to reload the data.
Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out