Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
Related
This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
I want to create a shopping cart and i'm almost finish. I use ajax for dynamic search and ajax for add to cart and use jquery for refresh a specific div when click but i face a problem.My problem is Quantity problem. I use session for store value
//this is my session update code
$con = mysqli_connect("localhost", "root" , "","atest");
session_start();
require("functions.php");
cart_session();
$id=$_POST['id'];
//echo $arr['cart'];
if(isset($_SESSION[$arr["cart"]][$id])){
$_SESSION[$arr["cart"]][$id][$arr["quantity"]]++;
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$sql_s="SELECT * FROM product_1
WHERE p_id={$id}";
//echo $sql_s;
$query_s=mysqli_query($con,$sql_s);
if(mysqli_num_rows($query_s)!=0){
$row_s=mysqli_fetch_array($query_s);
$_SESSION[$arr['cart']][$row_s["p_id"]]=array(
"{$arr["quantity"]}" => 1
);
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$message="This product id it's invalid!";
}
}
//use ajax for update cart
<script>
$("#link").click(function(e) {
e.preventDefault();
var id = $("#id").val();
var dataString = 'id='+id;
$('#loading-image').show();
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$(".container").css({"opacity":".3"});
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$.ajax({
type:'POST',
data:dataString,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
$('#loading-image').hide();
$(".form :input").attr("disabled", false);
$('#remove_cart').show();
$('#link').show();
$(".container").css({"opacity":"1"});
}
});
//$("#chat").load(location.href + " #chat");
//$("#chat").load(location.href+" #chat>*","");
});
</script>
Here is image and Red mark is my problem.
i want to update my cart when i give value and move it then it update my session by ajax and php.
Is there any help? I don't want to user can update there quantity every cart item singly. i want it dynamic just give quantity number and move then it save by ajax.
Assign an onchange event to your quantity input boxes:
$('input[name=quantityBox]').change(function() { ... });
In your function() above, add an AJAX POST request containing something like
var quantity = $('input[name=quantityBox]').val();
// var id = something;
$.ajax({
type:'POST',
data:"productId=" + id + "&updateQuantity=" + quantity,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
In your PHP function above, you check whether the product already exists in user's cart. At that point, change the quantity.
if(isset($_SESSION[$arr["cart"]][$id])){
$quantity = $_POST['updateQuantity'];
$id = $_POST['productId'];
$_SESSION[$arr["cart"]][$id][$arr["quantity"]] = $quantity;
}
Special Thanks To Nvj
Assign an onchange event to your quantity input boxes:
<input id="qty<?php echo $row['p_id'] ?>" value="" onchange="save_quantity(<?php echo $row['p_id'] ?>)">
function with ajax :
function save_quantity(x){
var quantity=$("#qty"+x).val();
$.ajax({
type:'POST',
data:"updateQuantity=" + quantity+ "&id="+x,
url:'update_qty.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
}
php file update_qty.php
session_start();
$qty = $_POST["updateQuantity"];
$p_id = $_POST["id"];
foreach($_SESSION['cart'] as $id => $value) {
if($id==$p_id)
echo $id;
$_SESSION['cart'][$id]['quantity']=$qty;
}
I have this section of code that is suppose to get the Values of the input fields and then add them to the database. The collection of the values works correctly and the insert into the database works correctly, I am having issue with the data posting. I have narrowed it down to the data: and $__POST area and im not sure what I have done wrong.
JS Script
$("#save_groups").click( function() {
var ids = [];
$.each($('input'), function() {
var id = $(this).attr('value');
//Put ID in array.
ids.push(id);
console.log('IDs'+ids);
});
$.ajax({
type: "POST",
url: "inc/insert.php",
data: {grouparray: ids },
success: function() {
$("#saved").fadeOut('slow');
console.log('Success on ' + ids);
}
});
});
PHP Section
<?php
include ('connect.php');
$grouparray = $_POST['grouparray'];
$user_ID = '9';
$sql = "INSERT INTO wp_fb_manager (user_id, group_id) VALUES ($user_ID, $grouparray)";
$result=mysql_query($sql);
if ($result === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysql_error();
}
?>
You cannot send an array trough an ajax call.
First, use something like:
var idString = JSON.stringify(ids);
And use it: data: {grouparray: idString },
On the PHP side:
$array = json_decode($_POST['grouparray']);
print_r($array);
I have a column of buttons in a table, declared like this:
(file index.php)
echo '';
Then this script reads the data in the row of the button clicked and posts it to another php file:
<!-- scripts that gets the lecturer chosen to SHOW functionality-->
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
});
});
</script>
That file (show_lecturer.php) stores the data read in a table (keep_track) in the database:
(file show_lecturer.php)
<?php
ob_start(); //eliminates buffer collisions
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
?>
Then I create an empty dialogbox with jquery, to populate it with the data taken from the database:
(file index.php)
<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
$(function() {
//show lecturer dialog
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
</script>
Then these data are taken from the table keep_track and echoed in the above dialog:
(file index.php)
$name; $surname;
require_once('connect_db.php');
$firstname = pg_query(connect(), "SELECT name FROM keep_track");
while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name']; }
$lastname = pg_query(connect(), "SELECT surname FROM keep_track");
while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name']; }
echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';
echo $name."".$surname;
echo '</div>';
?>
So when I click the button of row x, a dialogbox opens with the data from the row x.
The only thing that is not working correctly is this:
The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).
To illustrate the data I get:
(Initially the table keep_track is empty)
Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming.
So you need to process your results using the ajax Success callback function.
</script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
do_post_and_show_info(names, surname);
});
});
function do_post_and_show_info(names, surname){
request= $.ajax({
type: "post",
cache: false,
url: "show_lecturer.php",
data: { x: names, y: surname} ,
dataType: "json",
});
request.done(function(json){
if (json.status =="ok"){
// DO YOUR THING!
Alert(json.data.names + " " + json.data.surnames);
}
else {
alert("Error! " + json.error + " : " + json.remarks);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus + ":" + jqXHR.responseJSON);
});
}//do_post_and_show_info
</script>
I usually return a datastructure like this in PHP (so in your show_lecturer.php)
<?
// get your data before this in the variable $data
// put your status "OK" or "ERROR" in $status
// put some error info in $extraInfo
// of course some processing is involved, but here's a simple example
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error = "";
$data['names'] = $name;
$data['surnames'] = $surname;
echo json_encode(array(
"status" => $status,
"error" => $error,
"remark" => $extraInfo,
"data" => $data
));
?>
Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.
I wrote the content of the dialog (div) in another file and used
$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});
instead of
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
This did the trick.
Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.
The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).
There were also other minor changes I had to do to make it work, but this is the main idea.
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??