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.
Related
If ajax call ok than a href not working or if i stop ajax call than href ok, But i want both work on click
View
Ajax Request
$("body").on("click", ".btnad", function(e){
e.preventDefault();
details_id = $(this).attr('id');
$.ajax({
url: 'assets/php/process.php',
type: 'post',
data: { details_id: details_id },
success:function(response){
data = JSON.parse(response);
$("#getID").text(data.id);
$("#getTitle").text(data.ad_title);
$("#getUser_coin").text(data.user_coin);
}
});
});
If I understand correctly, you want to initiate an AJAX request and follow the link. You can't reliably do both an an asynchronous thing (ie an AJAX request) and still allow the browser to follow a link to a new page.
Instead, you should drop your use of AJAX, and instead allow your browser to perform a normal request to assets/php/process.php, but hae that page redirect the browser to the page you want to show next.
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 :)
I have a web application which features a bunch of different items, which are generated from a MySQL table. As users scroll through it, I want them to be able to click a link next to the item which will insert the request into a MySQL database. Normally, I’d do this by creating a PHP page (which I will do anyways) that grabs the item name & user id from the URI using the $_GET method & inserts it into the table. However, in this case, I don’t want the users to be redirected away from wherever they are. I just want the link to send off the request, and maybe display a small message after it is successful.
I figured jQuery/AJAX would be best for this, but as I’m not too familiar with it, I’m not sure what to do. Any tips are appreciated!
You have to do something like
$('.classofyourlink').click(function(e){
e.preventDefault();//in this way you have no redirect
$.post(...);//Make the ajax call
});
in this way the user makes an ajax call by clicking a link without redirecting. Here are the docs for $.post
EDIT - to pass the value to jQuery in your case you should do something like
$('.order_this').click(function(e){
e.preventDefault();//in this way you have no redirect
var valueToPass = $(this).text();
var url = "url/to/post/";
$.post(url, { data: valueToPass }, function(data){...} );//Make the ajax call
});
HTML
<a id="aDelete" href="mypage.php">Delete</a>
Script
$(function(){
$("#aDelete").click(function(){
$.post("ajaxserverpage.php?data1=your_data_to_pass&data2=second_value",function(data){
//do something with the response which is available in the "data" variable
});
});
return false;
});
See http://api.jquery.com/jQuery.ajax/
$('#my-link').click(function(){
$.ajax({
url: "mypage.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
return false;
});
$('.classOfYourLinkToBecliked').click(function(){
$.ajax({
type:'GET',
'url':'yoururl',
data: {yourdata},
processData: false,
contentType: false,
cache: false,
dataType: 'json',
success: function(response){
alert(response);
}
});
});
I have some ajax/jquery code in one of my pages and the problem I'm having is that it doesn't work the first time the page is loaded. If I refresh the page it works no prob. It does work in firefox first time. All the variables that I'm using are ok as I've alerted them out. I don't get a success or error message. It justr doesn't appear to do anything?
Any ideas?
$('.window .request').click(function (e) {
var itm = document.getElementById('txtItm').value;
var qty = document.getElementById('txtQty').value;
var msg = document.getElementById('txtMessage').value;
var op_id = document.getElementById('txtOp_id').value;
$.ajax({
type: "POST",
url: "do_request.php?msg="+msg+"&itm="+itm+"&qty="+qty+"&op_id="+op_id,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
document.getElementById('div_main').style.display='none';
document.getElementById('div_success').style.display='block';
var row_id = document.getElementById('txtRow').value;
document.getElementById('row'+row_id).style.backgroundColor='#b4e8aa';
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Error submitting request.');
}
});
});
It's hard to determine what the problem might be given the information and it sounds like you've not fully tested the page in a consistent manner. It seems likely there is another element on the page affecting the click event, as opposed to the handler logic itself, but there's no way to tell. Make sure you are binding to the click event after the page is ready:
$(document).ready(function(){
$("#uniquedomid").bind('click',function(){
// click handler logic
});
});
Also, as you're new to JQuery, one thing you're going to want to start looking at are all the various ways in which JQuery can improve your life. It does almost everything. But for starters, you're going to want to start using:
$("#uniquedomid")
Instead of
document.getElementById("uniquedomid")
And
$("#uniquedomid").val();
Instead of
document.getElementById("uniquedomid").value
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!