Delete a div id using ajax and jquery and delete from DB - php

I've got several div id's, each containing a different client. I want to be able to click the delete button and using ajax and jquery delete the specific div from the database. I'm getting success in AJAX but it's not deleting anything from the DB. And then obviously, upon deletion, I would like the container to reload dynamically. help!!!
function DeleteClient(){
clientID = $('.clientblock').attr('id')
alert(clientID);
var yes = confirm("Whoa there chief! Do you really want to DELETE this client?");
if (yes == 1) {
dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
$.ajax({
type: 'post',
url: '/clients/controller.php',
datatype: 'html',
data: dataToLoad,
success: function(html) {
alert('Client' + clientID + ' should have been deleted from the database.');
$('#clientscontainer').html(html);
},
error: function() {
alert('error');
}});};
};
controller.php info //
Variables necessary are:
$deleteClient
$clientID
on the delete click, when being passed through post (via firebug)
clientID = 0
deleteClient = yes
edit: so obviously, it's not getting the correct client ID to delete it to the DB as it is passing through post but I am getting an ajax success call and where i have the client ID variable displaying there, it is picking the correct client ID.
alert(clientID) is pulling in 0 as well.
Any ideas?

dataToLoad = 'clientID=' + clientID + '&deleteclient=yes',
Your controller is getting clientID value of 0.
Track down your clientID javascript variable and see if it is fetching the correct clientID.

Related

How to prevent same data inserted repeatedly into table?

This is how I pass the array into the function
$rate=$data["rate"];//this is an array like rate[10,20,30,60,70]
$car->rate = $rate;
$car->rentalRate();
In the function , it accepts the array and insert into the table
public function rentalRate()
{
$rate = implode("','",$this->rate);
$sql = "INSERT INTO rental(day_1,day_3,day_7,day_15,day_30)VALUES('$rate')";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
unset($rate);
}
Problem is,second time onwards it repeats the records. I mean for the first time when I insert only one row is inserted. The second time I insert, the same new record inserted twice. Third time I insert, thrice inserted..same goes for the number of times I insert. If I refresh than I don't have this issue.
WHat could be tracking the number of time I insert the data, could it be the array? or ajax?
This is how I submit the form via ajax
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data["json"] );
}
});
return false;
});
});
hard to say without seeing your full code but here is waht you can do:
Fist, use the dev tools on your browser and see how many requests you are submitting on every click. If they grow with every click it's your JS fault. If not then try to var_dump your POST data at the point of entry in your php scritpt. If the data is not repeated, there is a problem with your php part. (My bet would be with JS, as on AJAX request you create a new instance of php process so it can not track your submissions).

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

How to prevent updating other record of database?

I have table which read all the database from phpMyAdmin and dysplay it by php code.
- I am also can update each cell on the table, example by using the the row of the table which equal to ID in my database and colume which equal to (first name,last name,password)everting work ok.
so if the user click on the one of cell inside the table the jquery send by ajax the parameter ID and the colume one of the field(first name,last name,password).
what is my problem?
my problem is how can I prevent from haker or smart user which can see the jquery code and he will
understanding that he can change the value of any ID or password parmeters and ajax can update database not the correct ID?
supose I display to user table with 10 lines which have ID from 11-20 the user will change the ID parameter ID equal to 500 it can hapend.
$(document).ready(function()
{
var COLUME, VAL,ROW,STATUS,DATASTRING;
$('td').click(function() {
COLUME = $(this).attr('class');
});
//****************
$('tr').click(function() {
ROW = $(this).attr('id');
$('#display_Colume_Raw').html(COLUME+ROW);
//$('#display').html(COLUME+ROW);
$('#span' + COLUME + ROW).hide();
$('#input'+ COLUME + ROW ).show();
STATUS = $("#input" + COLUME + ROW).val();
});
//********************
$(".edittd").mouseup(function() {
return false;
});
//*************
$(document).mouseup(function() {
$('#span' + COLUME + ROW).show();
$('#input'+ COLUME + ROW ).hide();
VAL = $("#input" + COLUME + ROW).val();
$("#span" + COLUME + ROW).html(VAL);
if(STATUS != VAL){
$('#statuS').removeClass('statuSnoChange')
.addClass('statuSChange');
$('#statuS').html('THERE IS CHANGE');
DATASTRING=$('#display_Colume_Raw').html()+','+VAL;
//******ajax code
//dataString = $.trim(this.value);
$.ajax({
type: "POST",
dataType: 'html',
url: "./public/php/ajax.php",
data: 'DATASTRING=' + DATASTRING, //{"dataString": dataString}
cache: false,
success: function(data)
{
//alert(data);
$("#statuS").html(data);
}
});
//******end ajax
}
else
{
//alert(DATASTRING+'status not true');
}
});
});
There is no point showing front-end code as this is something you implement on the back end.
In the method that gets called via AJAX, simply check whether the user has permissions to perform the requested action or not. You can either have a separate check at the top of the method and return if the user it not allowed, or you can build it in to the delete query itself, e.g., by adding a WHERE clause making sure those IDs are ones that user is allowed to delete.
You cannot assign per-row permissions in MySQL so that row A can be viewed/edited by a user but row B cannot.
There is one workaround that's a bit of a pain if you absolutely have to have a solution, and that is that instead of using direct queries against a table (SELECT, INSERT, etc.), write store procedures that do some sort of authentication and/or validation. The procedure can do any kind of complex validation you want--check user ids, check column values, etc.--and return only what that user is authorized to see and/or edit.

Fetching id from database of submitted data

So I am submitting data to the database. Each data sent contains an id that is auto incremented. With ajax or PHP (I am very much new to this, and trying to learn I'm sure it's ajax along with some php) I need to fetch the id of the data that was submitted.
The idea is, after the form is submitted, the user gets the link back to the submitted page. Example:
Quote was submitted! [link] Click to go to the link or go back.
The link will look like this: http://example.com/quote-192
I pretty much have everything else set, I just don't know how I'll get the id and add it to the link.
Here is the PHP that processes the form:
require('inc/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
//echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Oh, and the data is being sent with ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
});
return false;
});
So how would I get the id for each quote and add it to the page after the form has been submitted?
In you php:
echo mysql_insert_id($result)
Then in your jquery ajax:
$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
var id = parseInt(data);
}
]);
this will return the inserted ID as an integer value that you can work with in javascript
Have the PHP print the ID as a response to the request:
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();
jQuery, test code to alert what was echoed by the PHP as a test
// add data as a param to the function to have access to the PHP response
$.post("add.php", $(this).serialize(), function(data) {
alert(data);
});
With this php-function. You can call after inserting.
int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
mysql_insert_id

ajax POST not working, can't figure why

I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.

Categories