Php like counter - php

I want to create 'like' counter.
Currently I use ajax with php and on button click in like.php I update count in database and echo back count number to jquery.
$('btn').on('click',function(){
$.ajax({
url: 'like.php',
type: 'post',
data: someData,
dataType: 'json',
}).done(function(response){
//increase like shown on response
}).fail(function(jqXHR, textStatus, errorThrown) {
});
});
This would be triggering likes from client side.
I would like to do this on server side instead, so on button click to call php file:
Example (I put this in my page):
like
And then in like.php update count in database as above.
2 questions:
is it possible for url not to change when I click this?
how would I echo back like count from like.php this way? (because I dont use ajax to call like.php like in first example)

to your first question: simply no!
But you could make it a submit button and do post to the same url wich wouldn't change the url and you can push data through submit...
to your second question -> your like.php has to return the whole html with your counter-value ;)
cheerio :)

Related

Counting clicks on an <a> link in a MySQL database

I have different links on my website which lead to other websites. I want to count the amount of clicks on the different links with my MySQL database.
I thought about doing a redirection over a php file which adds it in the database, but I would prefer to not redirect the user. Is it possible that the user just clicks on the tag gets immediately to the external website, and I can still count the click?
Thanks for you answers,
Till
yes you can run an ajax request and when the request is completed then you can redirect user to where ever you want to.
in the ajax request you will count the clicks and save it to the database.
you can do something like
$("a").click(function(){
$.ajax({url: "scriptthatwillcountclick.php", success: function(result){
window.open('redirect_here');
}});
});
Use ajax.
var data = {link:"value"};
$.ajax({
url : "your_file.php",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
You can run this code inside .click function when the link is pressed.
And in your php file just increment the count.
You can use jQuery Ajax funcionality to accomplish your goal, just create an on click even for your "a" element and execute your Ajax to save the click information on your database.
$('a').on('click', function(){
$.ajax({
method: "POST",
url: "save-my-click.php",
data: { 'extrainfo' : "Some extra info" }
});
});
Do not return false, or event.preventDefault() on your click event, because it will brake the redirection.
UPDATE:
You don't need to set the success and error functions because it is going to redirect anyway and you are not going to handle them.

AJAX call fired multiple times

I have a php application to upload excel files to server.I use ajax to send data to server.But some times the ajax call works repeatedly.I called the ajax function in button click as
$(document).on("click", "#btnContinue", function() {
$.ajax({
url: "ExcelColDesptn.php",
data: data,
type: 'post',
success: function(response) {}
});
HTML:
<button id="btnContinue" name="btnContinue" class="btn btn-primary ">Continue </button>
I use firebug to fix it, it shows
I don't know why it happens. Here 'ExcelColDesptn.php' is called 3 times and 'SaveExcelToServer.php' is called 4 times. Sometimes it works exactly 1 time. Any help?
The function you have, is this binding in another function? Which is called multiple times? Because this is a LIVE binding which means, the binding exists even if the content is update.
So I expect the following:
You use ajax to update content
#btnContinue is inside an HTML element which is updated by Ajax?
You call the function to add a new binding to the button
The button gets an extra click binding
so the more times you update your ajax, the more times the upload is executed. Because of the way you bind your click.
Solution:
Make it a normal binding $("#btnContinue").on("click", fn)
Put your binding only in document ready, and not in a function which is called multiple times
use $("#btnContinue").off("click") before your new binding (which is the most ugly solution)
please use your code like this
$('#btnContinue').Click(function() {
$.ajax({
url: "ExcelColDesptn.php",
data: data,
type: 'post',
success: function(response) {}
});
});

How can I use a jQuery var in some php code?

I know there are a few topics on this subject, but after I spent 2 or 3 hours trying to get something good out of them, I just decided to ask this question on a specific point.
So here is my problem : I have got a table and I am using a jQuery function to select a row of this table. Now what i actually want to do is getting the text content of the div contained in the first td of the row.
I already used a getter on it and I am checking the getted value with an alert as you can see in th following code :
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
});
So now, what I am trying to do is to send the myValue variable through an ajax request by replacing my alert by this piece of code :
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(rs)
{
alert(myValue);
}
});
Then, back to my php code, I am tring to observe the obtained variable by using an echo, just like this :
<?php echo $_GET['myValue']; ?>
But there is just no way for me to know if my page got it beacause the echo just prints nothing... So i was wondering if someone could do something for me. Thanks.
PS : Oh, by the way ; I don't really know if this can matter, but my page index.php already receives data by a post.
You can't, but read this, php is on the server, while js usually runs on the client, but your ajax trick can work. Just do some processing in the recieving php.
I usually put my ajax recieving end in a different file, and process the rest by the variables posted.
Just try to put the $_GET['myValue']; into an if, or a switch.
Do a var dump of the request var to see if anything is coming through:
<?php
var_dump($_REQUEST);
If not, do a console.log() on 'myValue' to make sure it exists before sending the ajax request - the issue may lie in your js rather than you php.
If you are POSTing data then adjust accordingly - e.g.
$.ajax({
type: 'post',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('successfuly posted:');
console.log(data);
}
});
then:
<?php echo $_POST['myValue']; ?>
If you were using GET your data would be in the url, e.g:
index.php?myValue=something
I'm not sure if you are aware of that, but you should wrap you function in document ready statement as below.
Next, call the AJAX request on some action, in this case we can use a click on the row in table.
$(document).ready(function () {
$("#myRow").click(function() {
$(".selectedRow").removeClass("selectedRow").addClass("unselected");
$(this).addClass("selectedRow").removeClass("unselected");
var myValue = $(".selectedRow .firstTd div").text();
alert('myValue');
$.ajax({
type: 'get',
url: 'index.php',
data: {"myValue" : myValue},
success: function(data)
{
console.log('you have posted:' + data.myValue);
}
});
});
});
Okay so it seems that i totally misunderstanded on the way that the $.ajax function works.
I now do use the $.post function (which is actually the same), this way :
$.post('pageElement.php', { myValue : $(".selectedRow .firstTd div").text() },
function(data) { $("#test").html(data); }
);
The url "pageElement.php" refers to a page containing this code :
<div><?php echo $_POST['myValue']; ?></div>
The function called at the end of the process just puts this code into a div of my original page, so i can use it as a php variable now and then send it to another page through a form.

Need to add function

I'd like to add a simple functionality to my pages, where a user will see a "follow" button and by clicking it a db record will be created (userID and pageID). I'll handle query on the backend, I suppose. I think I need to do it in AJAX, but I havebn't done much with AJAX. I was also thinking that updating the button status from FOLLOW to FOLLOWING (or something similar) I could do with jQuery, with some sort of toggle, while the request is being processed on the background.
Am I on the right track with this?
You're on the right track.
I've created an example which uses a button like <input type="image" class="follow">. When I user clicks on it it sends a request to the server (url). On success it updates the button image.
$('input[type=image].follow').click(function() {
var button = $(this);
var current_img = $(button).attr('src');
var current_alt = $(button).attr('alt');
$(button).attr('src', '/style/icons/ajax-loader.gif');
$(button).attr('alt', 'Requesting data from the server...');
$.ajax({
url: url of script the processes stuff (like db update),
type: 'POST',
data: {},
dataType: "json",
error: function(req, resulttype, exc)
{
$(button).attr('src', '/style/error.png');
$(button).attr('alt', 'Error while updating!');
window.setTimeout(function() {
$(button).attr('src', current_img);
$(button).attr('alt', current_alt);
}, 3000);
},
success: function(data)
{
$(button).attr('src', '/style/followed.png');
$(button).attr('alt', 'Followed');
}
});
return false;
});
Above is just some example code. Change it at your will. Have fun with it.
AJAX is right, jQuery makes ajax easy.
//Post with jQuery (call test.php):
$.post('test.php', function(data) {
//Do something with result data
});
It sounds like you are on the right track here. If you're working with a smaller application then using an AJAX request and creating your record would be easiest using a Java servlet and putting for example some JDBC code in your doGet or doPost method to perform the database operations.
At the same time your onSuccess method for your AJAX request can call the jQuery code necessary to update your button. Good Luck!

jquery ajax php recordset caching

I currently have a jQuery/ajax request which produces a recordset which appears in #contentDiv on my page. The user can then browse the results and view further details of an item. Once on the page for the item it the user hits back on their browser they return to the default page for my search without their generated search results.
The current jQuery code is:
$j.ajax({
type: 'POST',
url: '/availability/search',
dataType: 'html',
data: data,
success: function(data) {
$j('#col2AvailabilityContent').html(data);
}
});
Is it possible to pass the content of the results generated and passed to #colAvailabilityContent to a cache and draw these out when the back button is used.
Thanks
Yes. The trick is to change your hash location.
For example, let's say your site is http://simnom.com/index.php.
Once your results appear, change your URL to simnom.com/index.php#x, then to index.php#results
Then, when the user hits back button, it will just go to index.php#x.
You can use the javascript:
if(location.hash == '#x') {
$("#col2Availability").html(availabilitycontent);
}
And then keep $j.ajax()'s "data" stored as a global var "availabilitycontent".

Categories