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
Related
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
i need some workaround/solutions for my ajax issue
i have this simple <html>
<textarea class="msg"></textarea>
<button type="button" class="submit">Submit</button>
<div class="messages">
<?php some php while loop here to display all submitted messages?>
</div>
when i click submit, this ajax gets the value of <textarea> and submits the data into messages.php
$(function() {
$(document).on('click','.submit', function () {
var msg = $('.msg').val();
$.ajax({
type:"POST",
url:"messages.php",
data: "msg=" + msg,
success: function(html) {
$(html).prependTo('.messages');
}
});
});
});
this is my messages.php
//insert into database
$msg= $_POST['msg'];
$db = dbConnect();
$insert= "INSERT INTO messages (content)values ('$msg')";
$db->query($insert);
//get the recently added message and echo it
$query = //select the ID of the added message
$result = $db->($query);
$row = $result->fetch_assoc());
echo $row['id'];
echo $row['content'];
the part where im struggling, is how to query the message being submitted right after it was inserted to the database, so i could echo it in php, and fetch it via ajax.
success: function(html) {
$(html).prependTo('.messages');
}
i know i need some unique identifier of the submitted message, but im not sure how to code it properly.
edit:
ok, the reason i needed to query the added entry, is to get the associated ID of that entry, because i will be using the ID for other functions. all i really need is a reference on my submitted data
$id = $db->insert_id;
$query = "SELECT * FROM messages WHERE id = $id";
$result = $db->query($query);
$row = $result->fetch_assoc();
echo $row['id'];
echo $row['content'];
use last inserted id function it can also help if you are inserting in two different table and inputing same row values
//insert query in this line
$lastid=mysqli_insert_id()//php function
$que = mysqli_query("SELECT * FROM table where id= '$lastid' ");
$r = mysql_fetch_array($que);
echo $r['id'];
hopes this help
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 :-)
i am developing a simple chat module for my client, but not able to handle loop from setInterval()
Here is the js code from which i sending the request to get the data from the database
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>',
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}
and here is the get_data.php file which produce the data according to request
require "../../support/connection/connect_gib.php";
$to = addslashes(trim($_REQUEST['to']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' order by id asc";
$result = mysql_query($query);
while( $row = mysql_fetch_assoc($result) ){
echo "<b>".$row['frm']." : </b> " .$row['message'] . "<br />";
}
i got the result in loop like all the data repeat again and again, but i want the newly updated data, please make me correct what i did wrong..
You are using appendTo function in jQuery.. So all chat messages will be appended after old list. You can use .html() function to replace complete data.
Another way is to get only last chat message from php side, so all data will not be repeated. You can use auto id to point which messages are fetched last.
You should preserve the last id fetched and use that for new request. And on server side you should fetch from there.
$id= addslashes(trim($_REQUEST['id']));
$query = "select * from chat where
guest_id='".mysql_real_escape_string($to)."' AND id > '".mysql_real_escape_string($id)."' order by id asc";
function getData(){
jQuery.ajax({
url: '../../get_data.php',
data: 'to=<?php echo $_SESSION['ch_usr_id']; ?>&id=' + last_id_fecthed,
cache: false,
success: function(data){
jQuery('<div>'+data+'</div>').appendTo("#ch-data-con");
setInterval("getData()", 5000);
}
});
}
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;