I have table received from database:
<p id="result"></p>
<?php
//$id = $_SESSION['staff_id'];
$teamResult = getQuarter($leader_id);
$count1 = 0;
if (mysqli_num_rows($teamResult) > 0)
{
?>
<table id="confirm">
<tr>
<th>1st Quarter</th>
</tr>
<?php
while($row = mysqli_fetch_array($teamResult))
{
$staff_id = $row['staff_id'];
$username = $row['username'];
$date1 = $row['date1']; $fdate1 = $row['fdate1']; $q1 = $row['q1']; $cfm1 = $row['cfm1'];
?>
<tr>
<td>
<?php if($date1 != NULL){
echo "Ev.date: ".$date1."<br/> Fb.date: ".$fdate1.""
."<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>";
}else {echo "";}
?>
</td>
</tr>
<?php
$count1++;
}
} else {
echo "<h2>No Data to Display</h2>";
}
?>
</table>
This field is checkbox but I changed it to text to see its value:
<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>
Here is what I got in table:
Then I have AJAX function:
<script>
$(function () {
$(document).on('click', '.confirm', function(){
var stid = $("#stid").val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
});
</script>
And change.php:
$info = $_POST["stid"];
list($value1,$value2) = explode('|', $info);
echo $value1;
echo "<br/>";
echo $value2;
But the problem is I dont get correct value. For first and second row i get 1| 1000302. Even for second row where is should be 1| 1000305. What it the problem and how can I solve it?
IDs have to be unique. $("#stid") will always select the first element with that ID.
You can simply use $(this) to get the value of the element you clicked on.
$(document).on('click', '.confirm', function(){
var stid = $(this).val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
Related
So i want to make my select dropdown box flexible, however i tried using AJAX which i found online, but the AJAX request is a standalone data, it does not return back the data.
Is there any convenient way to get the data and able to submit to another PHP file ?
Here is my Code
index.php
<td>
<select id="ownerID" name="OwnerID" class="id" required>
<?php
$Employee_ID='';
$sql1="SELECT Employee_ID FROM user1 WHERE Position1='QE' OR Position1='OTHER'";
$result1=odbc_exec($conn,$sql1);?>
<option value="">Choose</option>
<?php while($row1=odbc_fetch_array($result1)){
$Employee_ID=$row1['Employee_ID'];
?>
<option value ="<?php echo $Employee_ID;?>"><?php echo $Employee_ID;?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td id="response" style="margin-left:50px;">
</td>
AJAX
<script type="text/javascript">
$(document).ready(function(){
$("select.id").change(function(){
$("#response option").remove();
var selectedOwner = $(".id option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { id : selectedOwner}
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
post-requst.php
if(isset($_POST["id"])){
$id = $_POST["id"];
$Form_Tracking_ID=null;
$sql="SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID = ' '
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID = ' '";
$result=odbc_exec($conn,$sql);
if($id !== 'Choose'){
echo "<label>Tool ID:</label>";
echo "<br><select id='toolid' name='ownerid' required>"; ?>
<option value="">Choose</option>
<?php while($row=odbc_fetch_array($result)){
$search=$row['Form_Tracking_ID']; ?>
<option value="<?php echo $search ?>"><?php echo $search ?></option>
<?php }
echo "</select>";
}
}
You can use a function for get data from database, getting value of 1º select and put them on 2º select
//Get value from 1 select
$("#firstSelect").change(function () {
let firstSelectValue = $("#firstSelect").val();
$("#secondSelect").text("");
//Calling a function to get value from database
getDataForSecondSelect(firstSelectId);
})
function getDataForSecondSelect(firstSelectValue) {
$.ajax({
url: `getDataForSecondSelect.php?value=${firstSelectValue}`,
method: "GET",
dataType: "JSON",
success: function (message) {
if (message.length != 0) {
$('#secondSelect').prop('disabled', false);
for (let i = 0; i <= message.length; i++) {
$("#secondSelect").prepend(`<option value=${message[i]["id"]}>${message[i]["name"]}</option>`);
}
} else {
$("#subcategoriaProduto").text("");
$("#subcategoriaProduto").prepend("<option>There's no data</option>");
$('#subcategoriaProduto').prop('disabled', true);
}
}
});
}
I want to get the value of the id in the checkbox. but the variable in id always give the 1st value. how can send php array to jquery array. thanks
require "connection.php";
$sql = mysqli_query($con,"SELECT * FROM position ORDER BY position_align + 0 ASC");
$switch = array();
$pid = array();
while($row = mysqli_fetch_assoc($sql)){
$pcode = $row['position_code'];
$pdesc = $row['position_desc'];
$status = $row['status'];
?>
<tr>
<td><?php echo $pcode; ?></td>
<td><?php echo $pdesc; ?></td>
<td>
<div class="custom-control custom-switch">
<?php
if($status == 'active'){
?>
<div class="onoffswitch4">
<input type="checkbox" name="onoffswitch4" class="onoffswitch4-checkbox switch" onclick="change(this.value)" id="myonoffswitch" checked value="<?php echo $pcode; ?>">
<label class="onoffswitch4-label" for="pid[]">
<span class="onoffswitch4-inner"></span>
<span class="onoffswitch4-switch"></span>
</label>
</div>
<?php
}else{
?>
<div class="onoffswitch4">
<input type="checkbox" name="onoffswitch4" class="onoffswitch4-checkbox switch" onclick="change(this.value)" id="aaa[]" value="<?php echo $pcode; ?>">
<label class="onoffswitch4-label" for="myonoffswitch">
<span class="onoffswitch4-inner"></span>
<span class="onoffswitch4-switch"></span>
</label>
</div>
<?php
}
?>
$('.switch').on('change', function() {
if(this.checked) {
var id = this.value;
$.ajax({
url: "admin_change_status.php",
data: {
id:id
},
type: "POST",
success: function(result){
}
});
}else{
var id2 = this.value;
$.ajax({
url: "admin_change_status.php",
data: {
id2:id2
},
type: "POST",
success: function(result){
}
});
}
});
i expect to get the value of id in checkbox to jquery.
If you want to get all values, you can only get it by classname not by id. You have to loop though all classes names and get each one of them, you can do this by each function. Each function loop though all the elements.
$('.onoffswitch4-checkbox').each(function(i){
var statsValue = $(this).val();
console.log(statsValue);
});
The loop works fine, it display what it supposed to do, but there is a mysql update button of which updates only the first row value displayed:
$(document).ready(function() {
$("#update").click(function() {
var fname = $("#fname").val();
var lname = $("#lname").val();
var recordId = $("#recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
async: true,
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
}
});
});
});
<?php
$conn = new mysqli('localhost', 'root', '123456', 'lc');
$sql = "SELECT * FROM lc where customer='souhail'";
$result = $conn->query($sql);
// while ( $row=mysqli_fetch_assoc($result)) {
while($row = $result->fetch_array()) {
echo 'LC ID :<input type="text" id="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" id="lname" value="'.$row['element_101'].'"><br>';
$recordId = $row['lc_id'];
echo '<input id="recordId" name="recordId" value="' . $recordId . '" >';
?>
<button type="button" style="background-color:<?php
if($row['element_101'] == '1'){
echo '#0000FFF';
}elseif ($row['element_101'] == '2'){
echo '#ffff00';
}elseif ($row['element_101'] == '3'){
echo '#00FF00';
}elseif ($row['element_101'] == '4'){
echo '#ffffff';
}
//echo $row['element_101'];
?>;color:#000000" id="update">Go Forward ></button>
<br><br>
<?php
} ?>
You must have unique IDs but instead wrap each set in a container and access relative tags:
$(".update").on("click", function() {
var $container = $(this).closest(".container");
var fname = $container.find(".fname").val();
var lname = $container.find(".lname").val();
var recordId = $container.find(".recordId").val();
$.ajax({
url: 'update.php',
method: 'POST',
data: {
fname: fname,
lname: lname,
recordId: recordId
},
success: function(response) {
alert(response);
},
error: function(xhr, textStatus, error) {
alert(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
Php
while($row = $result->fetch_array()) {
echo '<div class="container">
echo 'LC ID :<input type="text" class="fname" value="'.$row['element_6'].'"><br>';
echo 'Status :<input type="text" class="lname" value="'.$row['element_101'].'"><br>'; $recordId = $row['lc_id'];
echo '<input class="recordId" name="recordId" value="' . $recordId . '">';
echo '<button type="button" clsss="update">Go Forward ></button>';
echo '/div>';
} ?>
I am trying to delete rows from my sql database using checkbox. This is working fine as long as there is only one checkbox marked. But I also want it to be possible to delete multiple rows. I have seen many example, but I cant get it to work. Hope anyone here can help me.
So first the result.php file (here is all the rows / table created):
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH)) {
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
This file is included in my main html (main.html) file, here is the Jquery as well.
Jquery sending chechbox variables to delete.php file:
<script type="text/javascript">
$(".deletelogg").on('click', function(){
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {id:$('.toedit:checked:first').val()},
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
</script>
Last in my delete.php file:
include 'connect-database.php';
for ($i = 0; $i < count($_POST['id']); $i++) {
if ($_POST['id'][$i] != "") {
echo $_POST['id'] ;
$sql = "DELETE FROM Logg Where LoggID LIKE '".$_POST['id']."'";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
}
I was trying to make an array containing all id from the checkbox, but it didn't work.. any help pleas?
A working example: http://jsfiddle.net/Twisty/1y4zy5mn/
You should iterate over your checkboxes and collect the values. Given the following HTML:
<table>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="1" />
</td>
<td>One</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="2" />
</td>
<td>Two</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="3" />
</td>
<td>Red</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="4" />
</td>
<td>Blue</td>
<td>Fish</td>
</tr>
</table>
<button class="deletelogg">Delete</button>
<p></p>
Your JQuery will need to do a little more work. This should work for 1 or many:
$(".deletelogg").on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
}
});
} else {
alert("Please select items.");
}
});
With this, you can switch to a foreach() loop too:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
echo $id;
$sql = "DELETE FROM Logg Where LoggID = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
I'd do it like this way: first make a "checkAll" checkbox, and when is checked, check all your check-boxes. Then at the end of your form, put the "delete" button. When this one is pressed, all the checked check-boxes are deleted. I think this works even for some of the check-boxes (if you only check some of them, not all of them).
<div id="content"></div>
<input type="checkbox" id="checkAll">
//get all the rows from db here, or make them manually
<input type="checkbox" class="check" name="checkbox" value="<?php echo $row->id;?>">
//...
Then, with this piece of js code, you can check them all, or some of them, and "send" them to a server-side script which will grab them, and delete them from the db.
var checkBoxes = document.getElementsByTagName('input');
var param = "";
var params = [];
for (var counter=0; counter < checkBoxes.length; counter++) {
if (checkBoxes[counter].type.toUpperCase()=='CHECKBOX' && checkBoxes[counter].checked == true) {
param += checkBoxes[counter].value+' ';
params = param;
}
}
$.ajax({
type: "POST",
url: "path/to/server/side/script",
data: { params:params },
success: function(resp){
$('#content').html(resp);
}
});
And for checking them all:
$("#checkAll").click(function(){
$(".check").prop('checked', $(this).prop('checked'));
});
I don't know if this is the best way, but is a point to start. Also, don't forget to secure your app.
I have a question about using ajax.I want to delete something of my screen (to be clear, some articles) I'm generating content (the articles) on the screen with this code:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
This all is working very well without ajax. But I want to make this(the delete with the button) happen without a page refresh.
When i for example check the content of $test['id'], i receive one number. My problem with the code below is that when i want to put the title into variabel (var titel) for ajax, it loads all the titels from my page.
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
EDIT
I hope i explained my question in a better way now
Your problem is here
var titel = $(".titelopmaak").text();
You get all the values of the elements with class .titelopmaak but you only need one.
This is the correct one, we go up the tree and then find the item.
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
But, control elements by the title its very bad practice, use id instead of.
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>
You can try like this....
You have to specify individual id for each html elements
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
javascript function
Refer the h1 and div by their ids.
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
deleteArticle.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";