I am trying to delete a row of selected ID by passing a parameter into URL. let say, I have entryIDs 1 and 2, whenever I try to select and delete the content of entry 1, it successfully deletes the content of entryID 1 but the problem is when I choose to delete entryID 2 it still deletes entryID 1 instead of 2. I am thinking the content of a variable var row = '".$rows['Blog_ID']."'; doesn't change and only retains the value of entryID 1 even though I choose otherwise.
Here is what I tried so far..
<?php
include("../Connection.php");
$post_query="Select * from indexview order by Blog_ID Desc";
$postsql=mysqli_query($connect_db,$post_query) or die('Connection unsuccessful');
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
echo "<div id='posts'>";
echo" <select onchange = 'down(this.value)' id='downpng' name='downpng'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>";
echo
"<script>
function down(temp) {
var row = ".$rows['Blog_ID'].";
var id = '".$_GET['id']."';
if(temp=='delete'){
var con = confirm('Are you sure?');
if(con){
window.location = 'google.php?entryID=' + row + '&id=' + id;
}else{
window.location = '../Blog/Blog.php?id=".$_GET['id']."';
}
}else{
window.location = '../Blog/edit.php';
}
}
</script>";
When I select <option value ='delete'>Delete</option> it is supposed to redirect me into deleteBlog.php page and delete the content of selected entryID.
deleteBlog.php code:
<?php
include("../Connection.php");
if(isset($_GET['entryID'])){
$user = $_GET['id'];
$entry = $_GET['entryID'];
mysqli_query($connect_db, "Delete from blog_tbl where Blog_ID=" .$entry);
header('Location: ../Blog/Blog.php?id='.$user);
}
?>
Any suggestions will be much appreciated. Thanks!
You need to do minimal php for this, especially when it comes to the javascript part. Just store the blog id (I am going to store it in the name of the select attribute) and extract via javascript. I am going to use jQuery to do the JS stuff.
<?php
# Include database
include("../Connection.php");
# Create a simple function that does not use id="downpng" (id values are
# supposed to be unique
function getOrderDropDown($con)
{
$query = "Select * from indexview order by Blog_ID Desc";
$postsql = mysqli_query($con,$query) or die('Connection unsuccessful');
$str = '';
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
$str .= "
<select name='downpng[".$rows['Blog_ID']."]' class='blog_select'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>";
}
return $str;
}
# Write the selects to page
echo getOrderDropDown($connect_db);
?>
Javascript to extract the selection:
<script>
// I would only do php here, use a special chars, otherwise you will be easily hacked by user input
var id = <?php echo (!empty($_GET['id']))? '"'.htmlspecialchars($_GET['id'],ENT_QUOTES).'"' : 'false' ?>;
// On change of this class type
$('.blog_select').on('change',function(e) {
// Get the name (which contains the id)
var row = $(this).attr('name').replace(/[^0-9]/gi,'');
// This will be the action (delete, edit)
var action = $(this).val();
// On delete, assign the actions and send values
if(action == 'delete'){
var redirect;
var con = confirm('Are you sure?');
if(con){
redirect = 'google.php?entryID='+row+'&id='+id;
}else{
redirect = '../Blog/Blog.php?id='+id;
}
}else{
redirect = '../Blog/edit.php';
}
// Just do one redirect
window.location = redirect;
});
</script>
Related
I've looked really hard on this but I can't get my head around AJAX working with PHP.
This is what I have and when a user clicks on the dropdown I would like it to save into my database
<select>
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
And this is the query i'd like to run:
INSERT INTO snagging (taskstatus, updated_at)
WHERE ID = 1234
VALUES taskStatusRow['name'], $now);
I'll give you a overall flow of AJAX here. I tried to provide comments so as to show the control flow.
<select id="selectOption"> //******* Assign an ID
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
jQuery + AJAX
$(document).ready(function() {
$("#selectOption").change(function(){ //** on selecting an option based on ID you assigned
var optionVal = $("#selectOption option:selected").val(); //** get the selected option's value
$.ajax({
type: "POST", //**how data is send
url: "MYPROCESSPAGE.php", //** where to send the option data so that it can be saved in DB
data: {optionVal: optionVal }, //** send the selected option's value to above page
dataType: "json",
success: function(data){
//** what should do after value is saved to DB and returned from above URL page.
}
});
});
});
Inside your MYPROCESSPAGE.php, you can access the data passed via AJAX like:
<?php
$selectedOptionVal = $_POST['optionVal'];
//DB CONNECTION STEPS
.
.
.
// You are trying to "UPDATE" a table data based on some ID and not inserting. Included both operations
// If you are INSERTING A new table entry, use below code.
//INSERT INTO snagging (taskstatus, updated_at) VALUES ('$selectedOptionVal', 'Now()');
// If you are UPDATING an existing table entry, use below code.
//UPDATE snagging SET taskstatus = '$selectedOptionVal', updated_at = 'Now()' WHERE ID = 1234;
?>
Hope it's helpful.
I have a select option from which I can select a hotel name which I get from a php script.
And then I have another select option which shows room types based on the hotel selected from 1st select option.
And when I select a hotel with the help of ajax I only get one room type in my 2nd select option, while in my table I have multiple room types for a single hotel.
My php code for getting room types.
<?php
include('mysql.php');
$h_id = $_POST['hotel_id'];
$result = mysql_query("SELECT * FROM room_type WHERE hotel_id = '$h_id'");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
exit();
?>
javascript:
jQuery(document).ready(function($){
$('#hotel_list').change(function(){
$.ajax({
type:'post',
url:'roomtype_fetch.php',
data: 'hotel_id='+ $(this).val(),
success: function(value){
var data = value.split(",");
var type_name =data[0];
var type_id =data[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
});
});
});
html for 1st select option with its php to get hotel name.
<select class="form-control" name="hotel_list" id="hotel_list" onchange="cal()">
<option>--Select--</option>
<?php
$query2 = mysql_query("SELECT * FROM hotel") or die("the query cannot be completed at this moment");
if(mysql_num_rows($query2) <1) {
?>
<option>No Hotel Found!</option>
<?php
}
while($row = mysql_fetch_array($query2, MYSQL_ASSOC)){
$hotel_name = $row['hotel_name'];
$hotel_id_1 = $row['hotel_id'];
?>
<option value="<?php echo $hotel_id_1; ?>"><?php echo $hotel_name; ?></option>
<?php
}
?>
</select>
2nd select html code:
<select class="form-control" name="roomtype_list" id="roomtype_list">
<option>--Select--</option>
</select>
Any type of help would be appreciated.
You cant directly do value.split(",") because your php output looks like:
name1,id1name2,id2name3,id3
echo does not add a new line at the end, if you change the line to:
echo $type_name.",".$type_id,"\n";
That would give you an output like:
name1,id1
name2,id2
name3,id3
Which then you can split by "\n" to get an array of lines then by "," to separate name and id:
var data = value.split(",");
data.forEach(function(line){
var type_values = line.split(",");
var type_name = type_values[0];
var type_id = type_values[1];
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
}
But anyway, I think your best option is to change your php to return JSON:
$result = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$result[] = $row;
}
echo json_encode($result);
Then just do something like:
var data = JSON.parse(value);
$("#roomtype_list").empty();
data.forEach(function(type){
$("#roomtype_list").append("<option value="+type.roomtype_id+">"+type.type_name+"</option>");
});
The first thing is, your php loop that generates the types gives a wrong output:
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$type_name = $row['type_name'];
$type_id = $row['roomtype_id'];
echo $type_name.",".$type_id;
}
That gives you something like that:
name1,type1name2,type2name3,type3...
You should add a ; or an other separator like that between, so change the echo line to:
echo $type_name.",".$type_id.",";
That will give you an output like that:
name1,type1;name2,type2;name3,type3...
The second thing is, that you have to loop with jquery through your received types. You split the received string in an array:
var data = value.split(",");
..and so you should do the following in your javascript success function:
...
success: function(value){
var data = value.split(";");
//split all types first with ";"
$.each(data, function() {
var type = $(this).split(",");
//then split the type in name and id
var type_name = type[0];
var type_id = type[1];
//add every type to roomtype_list
$("#roomtype_list").html("<option value="+type_id+">"+type_name+"</option>");
});
}
...
Explanation: Split first all types with the separator ";" and split then the type in name and id with ",". I hope this helps.
I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});
I am new to php and ajax. I have this script that is working for me, it does almost what I want it to do. But I am looking to add this piece of code in to have the image show up once a product is fully selected and it has the id.
$dynamic_image .= '
<img style="height:auto; width:auto; max-width:7em; max-height:10em; padding :12px; margin: 9px; border: 3px solid #e3e3e3;" src="design_images/' . $did . '.png" alt="' . $name . '" />';
I also wanted the 'id' to be hidden, or at least not a selection option.
and to have the price and an add to cart button show up once the product is fully selected.
I know this is a lot to ask, but any help would be amazing because I am fully stuck right now. Thank You!
Here is the select_list.php file
<?php
// Multiple select lists - http://coursesweb.net/ajax/
if(!isset($_SESSION)) session_start();
// Here add your own data for connecting to MySQL database
$server = 'localhost';
$user = 'root';
$pass = '';
$dbase = 'mystore';
// Here add the name of the table and columns that will be used for select lists, in their order
// Add null for 'col_description' if you don`t want to display their data too
$table = 'products';
$ar_cols = array('category', 'subcategory', 'size', 'color', 'id', 'price');
$preid = 'slo_'; // a prefix used for element's ID, in which Ajax will add <select>
$col = $ar_cols[0]; // the variable used for the column that wil be selected
$re_html = ''; // will store the returned html code
$pre_html = '';
// if there is data sent via POST, with index 'col' and 'wval'
if(isset($_POST['col']) && isset($_POST['wval'])) {
// set the $col that will be selected and the value for WHERE (delete tags and external spaces in $_POST)
$col = trim(strip_tags($_POST['col']));
$wval = "'".trim(strip_tags($_POST['wval']))."'";}
$key = array_search($col, $ar_cols); // get the key associated with the value of $col in $ar_cols
$wcol = $key===0 ? $col : $ar_cols[$key-1]; // gets the column for the WHERE clause
$_SESSION['ar_cols'][$wcol] = isset($wval) ? $wval : $wcol; // store in SESSION the column and its value for WHERE
// gets the next element in $ar_cols (needed in the onchange() function in <select> tag)
$last_key = count($ar_cols)-1;
$next_col = $key<$last_key ? $ar_cols[$key+1] : '';
$conn = new mysqli($server, $user, $pass, $dbase); // connect to the MySQL database
if (mysqli_connect_errno()) { exit('Connect failed: '. mysqli_connect_error()); } // check connection
// sets an array with data of the WHERE condition (column=value) for SELECT query
for($i=1; $i<=$key; $i++) {
$ar_where[] = '`'.$ar_cols[$i-1].'`='.$_SESSION['ar_cols'][$ar_cols[$i-1]];}
// define a string with the WHERE condition, and then the SELECT query
$where = isset($ar_where) ? ' WHERE '. implode($ar_where, ' AND ') : '';
$sql = "SELECT DISTINCT `$col` FROM `$table`".$where;
$result = $conn->query($sql); // perform the query and store the result
// if the $result contains at least one row
if ($result->num_rows > 0) {
// sets the "onchange" event, which is added in <select> tag
$onchg = $next_col!==null ? " onchange=\"ajaxReq('$next_col', this.value);\"" : '';
// sets the select tag list (and the first <option>), if it's not the last column
if($col!=$ar_cols[$last_key]) $re_html = $col. ': <select name="'. $col. '"'. $onchg. '><option>- - -</option>';
while($row = $result->fetch_assoc()) {
// if its the last column, reurns its data, else, adds data in OPTION tags
if($col==$ar_cols[$last_key]) $re_html .= '<br/>$'. $row[$col];
elseif($col==$ar_cols[$last_key]) $pre_html .= '<br/>$'. $row[$col];
else $re_html .= '<option value="'. $row[$col]. '">'. $row[$col]. '</option>'; }
if($col!=$ar_cols[$last_key]) $re_html .= '</select> '; // ends the Select list} else { $re_html = '0 results';}
$conn->close();
// if the selected column, $col, is the first column in $ar_cols
if($col==$ar_cols[0]) {
// adds html code with SPAN (or DIV for last item) where Ajax will add the select dropdown lists
// with ID in each SPAN, according to the columns added in $ar_cols
for($i=1; $i<count($ar_cols); $i++) {
if($ar_cols[$i]===null) continue;
if($i==$last_key) $re_html .= '<div id="'. $preid.$ar_cols[$i]. '"> </div>';
else $re_html .= '<span id="'. $preid.$ar_cols[$i]. '"> </span>'; }
// adds the columns in JS (used in removeLists() to remove the next displayed lists when makes other selects)
$re_html .= '<script type="text/javascript">var ar_cols = '.json_encode($ar_cols).'; var preid = "'. $preid. '";</script>';
}else echo $re_html;
?>
Here is the ajax_select.js file for refeference
// Multiple select lists - http://coursesweb.net/ajax/
// function used to remove the next lists already displayed when it chooses other options
function removeLists(colid) {
var z = 0;
// removes data in elements with the id stored in the "ar_cols" variable
// starting with the element with the id value passed in colid
for(var i=1; i<ar_cols.length; i++) {
if(ar_cols[i]==null) continue;
if(ar_cols[i]==colid) z = 1;
if(z==1) document.getElementById(preid+ar_cols[i]).innerHTML = '';
}
}
// sends data to a php file, via POST, and displays the received answer
function ajaxReq(col, wval) {
removeLists(col); // removes the already next selects displayed
// if the value of wval is not '- - -' and '' (the first option)
if(wval!='- - -' && wval!='') {
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); // XMLHttpRequest instance
var php_file = 'select_list.php'; // path and name of the php file
// create pairs index=value with data that must be sent to server
var data_send = 'col='+col+'&wval='+wval;
request.open("POST", php_file, true); // set the request
document.getElementById(preid+col).innerHTML = 'Loadding...'; // display a loading notification
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(data_send); // calls the send() method with data_send
// Check request status
// If the response is received completely, will be added into the tag with id value of "col"
request.onreadystatechange = function() {
if (request.readyState==4) {
document.getElementById(preid+col).innerHTML = request.responseText;
}
}
}
}
Any Ideas?
I'm assuming that function ajaxReq is showing the list of products? and on select of an option you want the image to load?
This would depend on where your image url data will show when you get the list from the ajax.
I would add an id to the select element and use jquery to insert the image on click of an option. Let's say you add the image url to the value.
<select id="selectId">
<option value="/img/product.png">Product List</option>
</select>
<div id="productImg">
</div>
<script>
$(function(){
$("#selectId option").click(function(){
$("#productImg").html('<img src="'+$(this).val()+'"/>Product img');
});
});
</script>
Fiddle with it here: https://jsfiddle.net/kqyfw2s2/
I am working on a very basic administrator functionality of a social network and I came across this issue of not being able to remove an option from select dropdown list that I previously generated using jquery. The dropdown list contains all users of the social network. Administrator upon clicking on "Delete account" deletes the corresponding record from the database.
Now the question being - when I click on "delete account" it works perfectly fine but the option with a username is still there in a dropdown list and is possible to be picked - when picked it obviously returns dozens of PHP warnings and errors because the record is not in a database anymore. How can I remove this option straight away? I tried something like the following, but it doesn't work.
admin_panel.php (only relevant stuff)
<select name='users' id='users'>
<option value="" disabled selected>Select user</option>
<?php
$sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
$userList = [];
while($row=mysql_fetch_assoc($sql)){
$username = $row['username'];
$userID = $row['id'];
$userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
}
echo $userList;
?>
</select></br></br></div>
<div id="user_info">
<!-- generated user info table-->
</div>
<script type="text/javascript">
"$('#user_info').on('click', '#deleteAccount', function(e){
data.command = 'deleteAccount'
data.userID = $('#users').val()
$.post(theURL, data, function(result){
//Do what you want with the response.
$('#delete_account_success').html(result);
})
$("#users option[value='data.userID']").remove();
$('#delete_account_success').show();
$('#delete_account_success').fadeOut(5000);
})
</script>
processUser.php (part of a switch statement)
if(isset($_POST['command'])){
$cmd = $_POST['command'];
$userID = $_POST['userID'];
$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
$userData['userid'] = $row['id'];
$userData['username'] = $row['username'];
$userData['name'] = $row['name'];
$userData['date'] = $row['date'];
$userData['email'] = $row['email'];
$userData['avatar'] = $row['avatar'];
$userData['about'] = $row['about'];
$userData['admin'] = $row['admin'];
}
switch($cmd){
case 'deleteAccount':
$sql= "DELETE FROM users WHERE id =".$userID;
$result=mysql_query($sql);
echo "<img src='pics/ok.png' class='admin_updated_ok'>";
break;
}
On this line
$("#users option[value='data.userID']").remove();
You're removing any option items from #users where the value is equal to the string literal data.userID
Try changing it to
$("#users option[value='" + data.userID + "']").remove();