I have a select element created dynamically with items from my database. I would like to be able to delete the record from the database if the delete button is selected. Currently I have an AJAX function that is sending a GET request to my current page to remove it, and it removes the item from my options, however, my PHP used to access my database is never called and therefore when I refresh, the query is ran and what I just "removed" is displayed again because it is still in my db. I know I must be missing something simplistic, I just can't quite put my
finger on it and would appreciate any help or advice. I'm open to other methods as well. This is definitely not my strong suit.
My AJAX:
window.onload = function () {
document.getElementById("deleteLoc").onclick = function () {
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "adminLocationEdit.php", //Where to make Ajax calls
data:{deleteLoc : $("#lList option:selected").val() },
dataType:"text", // Data type, HTML, json etc.
});
$("#lList option:selected").remove();
}
};
My HTML:
<select id ="lList" multiple="multiple" style="width:400px;height:400px;">
<?php
//Query that selects all locations from the database and creates the list dynamically.
$qry = "SELECT * FROM location";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-1");
//Echo the db results into the select box.
while($row = odbc_fetch_array($qry_result)){
//Sets each row to variable.
$locID = $row['locationName'];
echo "<option id =\"$locID\" name = \"$locID\" onclick =\"$('#form1').load('incl/adminLocationEdit.php?loc='+$(this).attr('id'));displayFieldsets('form1', 'locList', 'lList');\">" . $locID . "</option>";
}
?>
My PHP:
//If user wants to add a new location
if(isset($_POST['addLoc'])){
//Re-directs
//header("Location: adminLocation.php");
exit;
}
//If user wants to Delete a location from the database.
if(isset($_POST['deleteLoc'])){
$contentToDelete = $_POST['deleteLoc'];
//Deletes current location from the database.
$qry = "DELETE FROM location WHERE locationName = '" . $contentToDelete . "'";
$qry_result = odbc_exec($admconn,$qry) or die("A database error has been detected. Err: adminLocationListEdit-2");
}
You are mixing both GET and POST
If you are looking for post,
This should be
data:{deleteLoc : $("#lList option:selected").val() },
Or if you are looking fr GET
type: "GET",// this should be GET not POST
Related
Hi I was asked to get some data from the last row in the database using ajax post request.
I have two files which are PHP scrip which is used to connect to the database and get all the data and convert the data to json format. I performed ajax post to PHP script to get all data. I want to modify the ajax post to request an additional data from the last row of the tables in database.
For example, in student table, there are 10 rows of data in database. I want to get data from the last row. My question is how to get values from the last row in the database..
Requirement: do not modify the SQL code as I need all the data and additionally the last row of data.
I do not want this code data[9]['student_name'];
here is my code below...
html file
<html>
<head>
<script type="text/javascript" src="/Cesium-1.34/ThirdParty/jquery-1.11.3.min.js"></script>
</head>
<div id="result"</div>
<script type="text/javascript">
showData();
function showData()
{
$.ajax({
type: "post",
url: "student.php",
dataType: "json",
data: "how to request data from the last row of the database????
success: function(data){
console.log(data);
}
});
};
</script>
</body>
</html>
php script
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
?>
My question is how to get data from the last row of database?
Requirement: do not modify the SQL code as I only want to modify the ajax post. Please help me. This is for my project.
Change the PHP code as follows.
<?php
$conn = mysqli_connect('localhost','root','netwitness') or die ("Could not connect database");
$db = mysqli_select_db($conn,'abdpractice') or die ('Could not select database');
$result = mysqli_query($conn,"select * from student");
$json_array = array();
while ($row = mysqli_fetch_assoc($result))
{
$json_array[] = $row;
}
$limit = count($json_array);
echo json_encode($json_array[$limit-1]);
?>
Your question is a bit unclear. It seems you want to send a param to PHP the only the last row, but I'm not sure. If that's true, you can do what #Rossi proposed adding a parameter like:
data: {
lastOnly: true
}
And at the end of the script:
if (!isset($_POST["lastOnly"])) {
echo json_encode($json_array);
} else {
echo json_encode($json_array[count($json_array)-1]);
}
But, if still wants to get all data from back-end but deal with the last row in your javascript, you can do what i've said in the comments:
success: function(data) {
var lastRow = data[data.length - 1];
}
UPDATE: To get only one field.
You can send back only one value and your data will receive a string instead of a json object:
echo $json_array["student_name"];
You can get the the property from your json object:
data.student_name
I have some functionality implemented with Google maps API so that a user can add a marker to the map. When the marker is added, it is then stored in 'dummy' table.
It is supposed to stay in the dummy table until an administrator approves the marker. When the administrator approves the marker it should then be deleted from the dummy table and added to the regular table with the rest of the markers.
Currently I have some code below that displays a list of rows from the dummy table and allows me to delete the rows from the table but it does not add the rows to the current table. Is there a simple way to modify this code to do this?
index.php - Jquery
$(document).ready(function() {
//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
e.returnValue = false;
var clickedID = this.id.split('-'); //Split string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "response.php", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut("slow");
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
Index.php - PHP
<?php
//include db configuration file
include_once("config.php");
//MySQL query
$Result = mysql_query("SELECT * FROM markersunapproved");
//get all records from markersunapproved table
while($row = mysql_fetch_array($Result))
{
echo '<li id="item_'.$row["id"].'">';
echo '<div class="del_wrapper"><a href="#" class="del_button" id="del-'.$row["id"].'">';
echo '<img src="images/icon_del.gif" border="0" />';
echo '</a></div>';
echo $row["name"];
echo $row["address"];
echo $row["lat"];
echo $row["lng"];
echo $row["type"].'</li>';
}
//close db connection
mysql_close($connecDB);
?>
response.php
<?php
//include db configuration file
include_once("config.php");
if(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"]))
{ //do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
//try deleting record using the record ID we received from POST
if(!mysql_query("DELETE FROM markersunapproved WHERE id=".$idToDelete ) )
{
//If mysql delete query was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
mysql_close($connecDB); //close db connection
}
else
{
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
?>
You could simply add an INSERT before deleting the entry from markersunapproved
mysql_query("
INSERT INTO [YOUR DESTINATION TABLE]
SELECT *
FROM markersunapproved
WHERE id = {$idToDelete}
");
First you must copy the data before deleting:
INSERT INTO regular_table
(name,
address,
lat,
lng,
type)
SELECT name,
address,
lat,
lng,
type
FROM dummy_table
WHERE 1
AND dummy_table.id = id;
For this to work correctly the "id" column in the regular_table should be auto-increment with primary index assigned, in order to autogenerate the "id" of each row in the insert.
and second, run the query that is already in your code:
DELETE FROM dummy_table
WHERE id = id
i have problim in jquery
i working in interactive map, in click form href for city i wnat insert the city name or number in sql query .
this link
link citys :
<a href='#' class='city_pr' id=aden> </a>
mysql query:
$sql="select * from project where city='$_SESSION[CITY]' AND active =1 ";
How to make a change when the session to mysql query on click the link below Download Page Navigation with jquery
It is not possible to use PHP session directly with jQuery, you need to do an ajax call.
Try this.
Explanation:
This will capture the value inside the link, do a post to a PHP file and print the data in "result" div without refreshing the page.
(Don't forget to read my observation at the end of the post)
HTML:
<a href='#' id='country'>USA</a>
<br/>
<div id="result"></div>
JS:
$('#country').click(function(){
// get the value inside the <a> tag
var country = $(this).html();
$.post('process.php', { country:country }, function(data){
// Everything is Ok, so data won't be 0
if(data != 0){
// Print country information
$('#result').html(data);
}
});
});
process.php
<?php
if($_POST() && isset($_POST['country'])){
/* Connect to DB */
$link = mysql_connect('server', 'user', 'pwd');
if (!$link) {
// No connection
print(0);
exit();
}
$db = mysql_select_db('db', $link);
if (!$db) {
// DB selection error
print(0);
exit();
}
/* sanitize the value */
$country = mysql_real_escape_string($_POST['country']);
/* do your query */
$sql = "SELECT * FROM country WHERE country_name = '$country'";
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
// At this point I am supposing that you stored in your table
// latitudes and longitudes of countries.
echo "Latitude is: ".$row['latitude']." Longitude is: ".$row['longitude'];
}
} else {
// No results found
print(0);
}
}
?>
Observation:
Try using other way to send the country value to the server.
For example:
if I have:
<a href='#' id='country'>United States of America</a>
In SQL query I will have:
SELECT * FROM country WHERE country_name = 'United States of America';
A better way could be:
<a href='#' id='us'>United States of America</a>
So in my JS I will have to replace var country = $(this).html(); for this:
//outputs 'us'
var country = $(this).attr('id');
Then in your SQL query you will get this:
SELECT * FROM country WHERE country_name = 'us';
It is more reasonable to use codes and no names (names are just to show the user, for better understanding because then you will have more problems to sanitize the value for using it with your query and also use functions like trim(); to remove spaces and others). If you do that you will have to change your query to find the country by code:
SELECT * FROM country WHERE country_code = 'us';
Hope this helps :-)
Hello i have gone through Long polling, websockets and APE, Ajax push, Ajax Pull. As the technology of websockets isnt yet much introduced in our World Wide Web now. i thought i would use the normal setInterval functions to check the database. this is for a chat application, my code :-
on Home.php :
Javascript:
$(document).ready(function(){
setInterval(function(){
var id = $id; // this is the id of the last message inserted in the database
var data = 'id='+id;
$.ajax({
type : "POST",
url : "check.php",
data : data,
success : function(data){
if(data)
{
$(".comments").append(data);
}
}
});
},1000);
and check.php
php code :
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM messages WHERE id>'$id' ORDER BY id DESC");
$num2 = mysql_num_rows($get);
$get2 = mysql_fetch_assoc($get);
$id = $get2['id'];
if($num2!=0)
{
$username = $get2['username'];
$a = mysql_query("SELECT * FROM people WHERE username='$username'");
$n = mysql_num_rows($a);
$b = mysql_fetch_assoc($a);
$file = $b['filename'];
$pic = "<img src=\"images/" .$file. "\" width=\"40\" height=\"40\">";
$name = $get2['fullname'];
$message = $get2['message'];
echo $pic.$message."<br/>";
}
else
{
}
if there is a new record inserted in the database it echo's out properly but then it doesnt update the $id in the home.php page so it sends the old id again and again and the comment gets appended again and again.
what i want is. for every interval . the $id of the home.php should be updated so that it sends only the present message id to the check.php page.
I gues that the first code you've post is in your template of home.php and the $id then goes replaced with the real number of the last ID.
this works for the first time when the page is processed with PHP, but once downloaded on users machine, you only have to rely on JavaScript...
I'm not sure in which form you receive the data from check.php, but you need to do something like
id = data.id
data = 'id='+id;
i am trying to implement pagination. A set of 9 products are displayed at a time. then upon clicking on a "View More" button, the content of a div should refresh by AJAX and show the next set of 9 products..here's the php code
if(!isset($_SESSION['current'])){
$query = "SELECT MAX(addedon) AS addedon FROM tags";
$result = mysql_query($query);
report($result);
$dated = mysql_fetch_assoc($result);
$recent = $dated['addedon'];
$_SESSION['current'] = $recent;
}
$query = "SELECT id, addedon
FROM tags
WHERE addedon <= '{$_SESSION['current']}'
ORDER BY addedon DESC
LIMIT 9
";
$result = mysql_query($query);
report($result);
while($row = mysql_fetch_assoc($result)){
$_SESSION['current'] = $row['addedon'];
$id = $row['id'];
$query = "SELECT name, image, cost
FROM tags, stock
WHERE tags.id={$id} AND stock.tagid = tags.id
";
$result1 = mysql_query($query);
report($result1);
$prodInfo = mysql_fetch_assoc($result1);
$pname = $prodInfo['name'];
$pimg = $prodInfo['image']; //the path to the actual image
$pcost = $prodInfo['cost'];
echo "<div class=\"oneproduct\">";
echo "<h3>{$pname}</h3><br />";
echo "<img src=\"{$pimg}\" height=\"{$ht}\" width=\"85px\" alt=\"prodImg\" /><br />";
echo "<span>Rs. {$pcost}</span>";
echo "<input type=\"image\" src=\"images/addcart.png\" class=\"addBtn\" />";
echo "</div>";
}
after all the products would be fetched and displayed, the last product on the page is stored as 'current' variable of SESSION.
problem is: the ajax thing always returns the initial set of 9 products and as soon as i refresh the page, the next set of products are coming..how do i make my link change the content?
The ajax code:
$("#viewMore").bind('click', function(){
$.ajax({
url:'showNineProds.php',
type:'POST',
dataType:'html',
success:function(data){
$("div#nineproducts").html(data);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
showNineProds.php simply calls a function that has been written above..
The correct way to do this is for the client-side code to specify with parameters to the AJAX call which "page" of records to be fetched. By using a session variable like this, the server has no concept of which records to get at which time. It's always going to return the "next" result. So any time you load that web page, it's going to serve the "next" set of records. There's no way to page backward in the result set.
Basically, you would store in local JavaScript values (or hidden form elements on the page, however you feel comfortable storing a value on the page) the information of the current result set and your AJAX call would send the necessary information to the server to return the requested result set.
For example, you could have a local JavaScript value that says which start record you're seeing and your page size:
startRecord = 1;
pageSize = 10;
Then if you click your "next" button the AJAX call would supply parameters to the server telling it what to fetch:
startRecord + pageSize, pageSize
You'd want to add a little bit of logic to determine if you're on the first or last page to disable "prev" and "next" functionality, of course. And there's a lot more you can do (variable page sizes, filtering and searching, sorting, etc.) but this is the basic gist of it.
You don't seem to be sending back the info from the ajax call. basically yoi might be fetching the values on the DB but don't seem to be sending the data back to the call..
do you echo the result set in some format? I can't see that in the code. in any case you can't access the $session variables from the js... these are accessible server side in php.