Upating mysql fields asynchronously with ajax when "Like" is clicked - php

The question is fairly simple. Whenever user clicks on "like" I want to use javascript to update the mysql database through ajax. I have tried all means bit have found nothing helpful. I know I will also need a server side script but the ajax is the main issue.
Here is the counter code I set up.
document.observe("dom:loaded", function()
{
$("likeForumLink").onclick=processForumLike;
});
function processForumLike(event)
{
var numberOfLikes=parseInt($("hiddenLikes").value);
numberOfLikes+=1;
$("hiddenLikes").value=numberOfLikes+"";
this.innerHTML="You liked this";
if(numberOfLikes==1)
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" like)";
}
else
{
$("numberOfLikes").innerHTML="("+numberOfLikes+" likes)";
}
var likes=$("hiddenLikes").value;
new Ajax.Request("seeForum.php?id=$("subjectId").value", {
method:'get',
parameters:{hiddenLikes:likes},
onSuccess: ???? //Don't know
onComplete:??? //Don't know
on Failure:???? //Don't know
});
}
And then I can use my server side script as follows.
P.S. It lies in the same page "seeForum.php?subjectId=$("subjectId").value"
<?php if(isset($_GET["hiddenLikes"]))
{
$updateQuery="UPDATE `subject table` SET `likes`='".$_GET["hiddenLikes"]."' where `subjectId`='".$_REQUEST['subjectId']."' ";
$result=mysql_query($updateQuery);
checkConnect($result,"query of $updateQuery");
?>
Please help. All my work has come to a halt.

First of all, you shouldn't be using a GET request to update data, that should be a POST. And this:
"seeForum.php?id=$("subjectId").value"
doesn't do what you probably think it does. What it does do is cause a syntax error because it looks like "x" x "x" to the JavaScript interpreter and that's not JavaScript. I'm not sure which JavaScript library you're using (Prototype perhaps?) but I think you probably want to put all your parameters into parameters to avoid having to worry about URL encoding and things like. Furthermore, there's no reason to tell the server how many "likes" you already have and there is a good reason not to: someone might have "liked" the page while you're looking at some the number of likes you currently have will be wrong; so hiddenLikes isn't needed at all.
Something like this would be better on the JavaScript side:
new Ajax.Request("likeIt.php", {
method: 'post',
parameters: { id: $('subjectId').value },
onSuccess: function(transport) {
// Update the "likes" label with something like this,
// I'm not that familiar with Prototype though so I'm
// guessing.
$('likes_label').update(transport.responseText);
},
onComplete: ???? // The function to call when it has finished.
onFailure: ???? // The function to call when it doesn't work.
});
And then, in the PHP, just send a simple UPDATE to the database to increment the number of likes in likeIt.php, something like this:
<?php
# Perform whatever authentication you need...
if(isset($_POST["id"])) {
# Set up your database connection and then...
$result = mysql_query("UPDATE `subject_table` SET `likes` = `likes` + 1 WHERE `subjectId` = '" . mysql_real_escape_string($_POST["id"]) . "'");
# Check $result and send some data back to the client (if desired), if
# you send something back then the onComplete, onFailure, and onSuccess
# JavaScript functions would be responsible for doing something with it.
}
# Send back the updated number of "likes" as text/plain.
?>

Well thinking it through, if the user clicks on like, all you really want to do is increment the like counter in the page itself. You can do this in the onComplete: function(){ increment the like counter }. If some kind of error does occur, i don't think you would want to display it to the user, depends on how you want to handle that part, many ways to do it, you could log the error.

Related

Delete an entry from db on PHP page exit

I have a php page in which a user tries to find online people.
There a search button, clicking on which, an entry is made for the current user in the database and the control goes inside a loop, where every 5 secs a search is made in the database to find if a new entry has been made, if an entry is found then the details of the partner is shown to him.
I want that if the user exits or navigates away from the page before a partner is being found, then his entry must be deleted from the db.
I am trying to store the 'id' created against the user inside a session variable, make an ajax call and delete the entry, but somehow this concept is not working.The data is not getting deleted. Is this because of the loop which is still finding the user or something else, m not able to get it.
Can anyone tell me what is going wrong with my approach ?
A code snippet that I am using is hereby
window.onbeforeunload = function() {
funcDeleteonexit();
return "Are you sure you want to navigate away?";
}
function funcDeleteonexit(){
$.get("functions.php",{
data:"delete"
},function(data,status){
});
}
Inside my functions.php, I have
if($_GET){
if ($_GET['data']=="delete"){
echo deletefromDb();
}
}
function deletefromDb() {
$mysqli = new mysqli("localhost", "root", "", "test");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$currentid = (int)$_SESSION['currentId'];
$query1 = "delete from test where id =". $currentid;
$mysqli->query($query1);
$mysqli->close();
return $currentid;
}
If you want something done when someone exits the page, this will in most cases give you trouble if you want a specific event to be fired then. There will be cases a browser cannot fire the event (p.e. client crash etc.).
Therefore I'd suggest a different approach. Control this from the server side, and don't rely on the users browser or input.
Firstly, you can poll your data while regularly firing Ajax events from the browser. You've not stated this, but I think you do something like this:
function yourrequest(){
$.ajax({
type: "GET",
url: "your/php/script.php",
success: function(data){
// do something, p.e. update a div
}
});
};
setInterval(yourrequest, 5000);
(Please don't tear this code sample apart, its just to show the basics).
On the server side, you already have the users id somewhere in your database. Add a timestamp field to this table (call it last_request or something like that). Everytime you send some data to the client, check if there are users with a last_request below your desired threshold, and delete those ids. No need to wait for a specific event then.
This needn't be done exactly there, you can also do something different, p.e. a cleanup job cronned every 5 minutes or so which does this seperately to not disturb the users request at all.
I'm suggesting that browser just not sending ajax, or interupting it.
So try to make your AJAX request synchronous. For JQuery seems to be set async parameter to false
$.get("functions.php",{
data:"delete",
async : false
},function(data,status){
});

Warn user when new data is inserted on database

I don't know how to search about this so I'm kinda lost (the two topics I saw here were closed).
I have a news website and I want to warn the user when a new data is inserted on the database. I want to do that like here on StackOverflow where we are warned without reloading the page or like in facebook where you are warned about new messages/notifications without reloading.
Which is the best way to do that? Is it some kind of listener with a timeout that is constantly checking the database? It doesn't sounds efficient...
Thanks in advance.
You need javascript ajax and json and callback function to check constantly. It can be done by push services but PHP is bad with that and you need websockest, etc. facebook uses timeout calls. not sure for the stackoverflow
refreshInterval = 500
refreshTimeout = setTimeout( getNotificationCounts, refreshInterval );
function getNotifications() {
$.ajax({
url : 'path_to_your_php',
type : 'POST',
data: //put for exampel user_id but it cvan be handled by sesion as well
dataType : 'json',
success : function(data) {
alert('You have'+ data.total +' new messages')
refreshTimeout = setTimeout( getNotificationCounts, refreshInterval ); //this will check every half of second
}
});
}
then in PHP, for example you have a flag in database with which you check if data is new to teh databse. Mind the formatting and to proper sql escape
$result=mysql_query("SELECT count(*) as total from myTable where user_id=$_POST['user_id'] AND is_read=0");
//note instad of $_POST you can use session if users are logged in, or however you are handling it
$data=mysql_fetch_assoc($result);
echo json_encode($data)
;
After that you can create another ajax call that marks messages as read once user clicks on them. or opens a dialog listing or wahtever
mysql_query("UPDATE myTable WHERE user_id=$_POST['user_id'] SET is_read=1");

Calling a php function using ajax/javascript

Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link

How do I wait for input from the client side after a server side query?

To consolidate a few SQL calls I'm trying to make one query to the server and then have the client side iterate through each result. The caveat is that I need to wait for user input before processing the next result. Is this possible?
I have a jquery call similar to below:
$.post('functions/file_functions.php', {type: 'test', f: 'load'}, function(data) {
if (data.success) {
$.each(data.files, function() {
// Can I wait for user input at this point and then process the next
// file after a users interaction (e.g. a button click)?
});
}
}, "json");
I'm going to expand on my comment a bit, and hopefully make it a useful answer. JavaScript is single-threaded, so there's no way to block the execution of a function while waiting for something else (such as an element being clicked on) to happen. Instead, what you could do is store the list of files into an array when the AJAX POST request returns successfully, then use a separate click event handler to cycle through them (I assume getting one file per click).
Code may look something like this:
$(function() {
var files, index = 0;
$.post('functions/file_functions.php', {type: 'test', f: 'load'}, function(data) {
if (data.success) {
files = data.files;
}
}, "json");
$('.mybutton').click(function() {
if(files) {
var file = files[index++];
// do something with the current file
}
});
});
One of the ways to have "blocking" user input in javascript is to call window.prompt (among others like window.confirm, or window.showModalDialog). However its not really customizable, you might want to just save the data coming back from the server and have some kind of a user input event based processing.
In code it would look like this:
var the_answer = window.prompt("What's the airspeed velocity of an unladen swallow?");
console.log(the_answer);

Delete file using a link

i want to have function like delete file from database by using link instead of button. how can i do that? do i need to use href/unlink or what?
Can i do like popup confirmation wther yes or no. i know how to do that, but where should i put the code?
this is the part how where system will display all filename and do direct upload. Beside each files, there will be a function for 'Remove':
$qry = "SELECT * FROM table1 a, table2 b
WHERE b.id = '".$rs[id]."' AND a.ptkid = '".$rs[id]."' ";
$sql = get_records_sql($qry);
foreach($sql as $rs){ ?>
<?echo ''. basename($rs->faillampiran).'';
?><td><?echo ' [Remove]';?></td><?
?><br>
<? }
?>
thankz all
The elegant way of doing this would be to use both PHP and JavaScript. PHP is a server-side language, and should probably be removed as much as possible from the client side stuff. One great way to do it would be to essentially create yourself an API.
The API would be a PHP script that deletes a row. It takes a variable in via GET and returns a boolean that says "yes we deleted the row" or "something went wrong." I like to use JSON, which in JavaScript is easier to work with than XML, and jQuery's getJSON function, a package that makes it really easy to get going.
In the .php file (we call it api.php later), if your results are successful return out success boolean. We use PHP's json_encode on an array, and echo out the result:
$variable = someFunctonToSanitize($_REQUEST['idToDelete']);
$query_to_run = "delete query using $variable";
$result = mysql_query($query_to_run);
// set headers
header('Content-type: text/json');
header('Content-type: application/json');
// if the query was successful, echo true
if($result) {
echo json_encode(array("success"=>"true"));
} else { // else echo false
echo json_encode(array("success"=>"false"));
}
In your JavaScript, here using jQuery (this is discouraged, see comments below):
$('#deleteLink').click(function(event) {
// prevent link from actually going anywhere
event.preventDefault();
// Fire off API request
$.getJSON("api.php?idToDelete=whatever", function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
});
});
With a .post() request, per #Col. Shrapnel and #josh3736's comments (note: also changed $_GET to $_REQUEST to work with both):
$.post("api.php", { "idToDelete": "whatever" },
function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
}, "json");
In your HTML:
Delete!
No links nor buttons can be used for the database interaction. It is server-side code to do such things. You have to understand that your application has 3 layers:
an HTML form
an server-side code
a database
the first one cannot interact with the last one directly.
So, on the one hand, it doesn't matter, with link or button you do call your server side code (the code remains the same).
But, on the other hand, there is a rule:
use GET method (link) to request information and POST (form/button) to modify it.
So, you should not use links to remove files, because some too smart bot can wipe all your database in a second.
As for your question where to place the code, just write a php script, unlink.php which deletes a file by hardcoded path. Then, after you've done that, make this file an action for the HTML form. Hardcoded one. Once you've done that - you can try to generate this form from your database.
This - step-by-step way - is the only possible way to develop a wab-application
Make a link:
Delete
Then make a delete.php that handles deleting and make sure you check that the session is authorised.
In PHP you use unlink() to delete a file. If you provide a page which accepts the file name (or better yet, file Id) as a parameter you can call unlink() on the file. Obviously there are some serious security implications which you will need to account for.
For confirm Delete, use this in onclick function()
In a href tag, itself :
<a href="" onclick="return ConfirmDelete();" ></a>
In upper Page use javascript like this,
function ConfirmDelete() {
var confm = window.confirm("Are you sure want to delete this !");
if(confm == true) {
return true;
} else {
return false;
}
}
For delete option give the same page link and pass the parameter and get the parameter by get function
<a href='samepagename?deleteid='.<?php echo $id;?>
In get parameter use like this,
$deleteid = $_GET["deleteid"];

Categories