Click counter ajax n php help need

hi all need ur help with some thing,

and ajax and php update

i kinda need a click counter so i know when someone click play
per session user i have a download script which has a session user rule below

//update download button click


if (isset($_POST['action']) && $_POST['action'] == 'update')
{
    if (!isset($_SESSION['downloaded_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set download_counter = download_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':download_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['downloaded_item_'.$id] = true;
                    
    header('location: track_audio.php?id=' . $id);
    exit();
}

column name for click counter is play_counter

html code is


     <div class="sm2-inline-element sm2-button-element">
          <div class="sm2-button-bd">
            <a href="#play" class="sm2-inline-button sm2-icon-play-pause">Play / pause</a>            </div>
          </div>

i dont know how to go about this thats y am asking here

i know its gonna be javascript and ajax n php, ur help is greatly needed thanks

The click query you have seems correct as long as you pass the appropriate id into it. But you don’t need to pass the second parameter download_counter to it, as you don’t use that anywhere in the query. I’m not sure whether PDO will throw an error if you send it a parameter it doesn’t need.

hi thanks for the reply the php code is suppose to pass d update to d table and i need it session to aviod multiple update so am thing d php code will be

if (isset($_POST['action']) && $_POST['action'] == 'update')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;
   
}

some thng of that nature.

not sure about connecting ajax with d php

You’re still passing a second parameter, :play_counter, into the query when you don’t have a parameter of that name in the query. All you’ve done here is change the name of it. And even if you had it, would you want to set it to the same as the auction_id column?

oh sorry i havent written an actual code for it i dont even kow where to start with d ajax pasrt am just showing u d php part cause it wat i used for the download count n rewritten to suit click_counter to pass d info to database, hope u get what am trying to say

apologies for d stress

so heres what i have done still not connect
ajax n html

 <script>
var clickplay = document.getElementById('clickplay');

function countPlay(){
	console.log('anything');

	var url = '../../track_audio.php';
	
	var xhttp = new XMLHttpRequest();
	  xhttp.onreadystatechange = function() {
		if (this.readyState == 4 && this.status == 200) {
		 //;document.getElementById("demo").innerHTML = this.responseText;
		}
	  };
	  xhttp.open("GET", url, true);
	  xhttp.send();
	
	
	
	}
        
        </script>
        <div class="sm2-inline-element sm2-button-element">
          <div class="sm2-button-bd">
            <a href="#play" id="clickplay" class="sm2-inline-button sm2-icon-play-pause">Play / pause</a>            </div>
          </div>

php

//play update button click

if (isset($_POST['action']) && $_POST['clickplay'] == 'update')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;
   
}


how do i go about connecting down to update the databse, u reply is greatly needed

Sort of, but it’s quite difficult to make out what you mean sometimes.

But, it’s this PHP code I am referring to. You are passing two parameters into your query, but you only have a place for one of them in the query. Have you much experience with PDO and parameter passing?

I’d say if this is new stuff for you, split it into two blocks. First, get your PHP code working so that if you click a link, it will update the play counter. Once that is working, convert it to use Ajax. For more help on the Ajax side of it, you need to post in the JavaScript section of the board, though, as you might get more response there.

Your Ajax code never gets called, which is why it’s not registering for you. You’ve created a function countPlay(), but nothing ever calls it. Another issue you have with it is that you don’t pass any parameters through to track_audio.php, so your PHP code won’t know which track to update the details for. A further issue is that your function specifies “GET” as the method to open the PHP code, but in your PHP code you use the $_POST array - these need to be the same.

So, step 1 - get your PHP code working from a basic link or form post code, and go from there on the JavaScript section of the board.

ok ok will first work on the php code first thanks, brb

still didnt get it wworking droop

Still can’t help without seeing any code.

ok thanks

html code

 <div class="sm2-inline-element sm2-button-element">
          <div class="sm2-button-bd">
		  
            <a href="#play" id="play-button" class="sm2-inline-button sm2-icon-play-pause">Play / pause</a>            
			</div>
          </div>

jquery code

<script>
		 var playButton = document.getElementById('play-button')

playButton.addEventListener('click', function (event) {
  var xhr = new XMLHttpRequest()
  var data = new FormData()

  data.append('action', 'update_play')
  xhr.open('POST',  xhr.open('POST', '{SITEURL}track_audio.php')
 xhr.send(data)
 event.preventDefault()
})
</script>

php code

if (isset($_POST['action']) && $_POST['action'] == 'update_play')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;
                    
    header('location: track_audio.php?id=' . $id);
    exit();
}

thanks

I’ve seen this code in another post somewhere, didn’t someone say this line was wrong?

xhr.open('POST',  xhr.open('POST', '{SITEURL}track_audio.php')

Where is your PHP code getting $id from?

hi sorry for late reply yh i posted in the javascsript session like u told me
but i havent been able to solve it yet

heres d full code

php code

if (isset($_POST['action']) && $_POST['action'] == 'update_play')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;
                    
    header('location: track_audio.php?id=' . $id);
    exit();
}

html and javascript

 <div class="sm2-inline-element sm2-button-element">
          <div class="sm2-button-bd">
		  
            <a href="#play" id="play-button" class="sm2-inline-button sm2-icon-play-pause">Play / pause</a>            
			</div>
          </div>
  
  
        				<script>
		 var playButton = document.getElementById('play-button')

playButton.addEventListener('click', function (event) {
  var xhr = new XMLHttpRequest()
  var data = new FormData()

  data.append('action', 'update_play')
 xhr.open('POST', '{SITEURL}track_audio.php')
 xhr.send(data)
 event.preventDefault()
})
</script>
  

havent been able to get it to work

What happens, or does not happen? Does it call your PHP code and something fails in that, or does it just not call the PHP?

Asking this again. Your PHP code uses a variable called $id which it does not seem to get from anywhere.

id comes from a header
which runs the script

// Get parameters from the URL
$id = (isset($_SESSION['CURRENT_ITEM'])) ? intval($_SESSION['CURRENT_ITEM']) : 0;
$id = (isset($_REQUEST['id'])) ? intval($_REQUEST['id']) : 0;



$_SESSION['CURRENT_ITEM'] = $id;



// get auction all needed data
$query = "SELECT a.*, c.cat_name, ac.counter, ac.auction_id AS track_id, ac.play_counter, ac.download_counter, u.type, u.activate_promote, u.promote_artist, u.nick, u.reg_date, u.city, u.country, u.zip FROM " . $DBPrefix . "auctions a
		LEFT JOIN " . $DBPrefix . "users u ON (u.id = a.user)
		LEFT JOIN " . $DBPrefix . "auccounter ac ON (ac.auction_id = a.id)
				LEFT JOIN " . $DBPrefix . "categories c ON (c.cat_id = a.category)

		WHERE a.id = :auction_id AND category != 2020 AND a.suspended != 1 LIMIT 1";
$params = array();
$params[] = array(':auction_id', $id, 'int');
$db->query($query, $params);
if ($db->numrows() == 0)
{
	$_SESSION['msg_title'] = $ERR_622;
	$_SESSION['msg_body'] = $ERR_623;
	header('location: message.php');
	exit;
}
$auction_data = $db->result();

nothing happens when i click d play button, d song just plays but no count occurs

I am confused. Is this the script that produces the page that the user clicks to play the video?

If it is, while you have defined $id in that, I can’t see where you pass it through to “track_audio.php” to use it in there. You do assign it to a session variable in that script, but you don’t extract it from there in track_audio.php as far as I can see.

ETA - at the end of track_audio.php you do a session redirect - I don’t think you should be doing that once you’re calling the code via Ajax as it runs in the background.

And… you say “full code”, but your PHP script doesn’t seem to include anything to connect to the database. Did you miss that out of the post for clarity? Remember that your Ajax call launches that PHP code in track_audio.php in isolation, so everything you need has to be in there.

EATA - there’s loads of missing semi-colons on the end of your JavaScript, is that for this post or are you getting loads of syntax errors in the javascript console in your browser?

hi thanks for the reply and sorry for the late reply i bounce around alot dis days

If it is, while you have defined $id in that, I can’t see where you pass it through to “track_audio.php” to use it in there. You do assign it to a session variable in that script, but you don’t extract it from there in track_audio.php as far as I can see.

**it is connected via a common header thats where all ids come from
include ‘common.php’;
include INCLUDE_PATH . ‘membertypes.inc.php’;
include MAIN_PATH . ‘language/’ . $language . ‘/categories.inc.php’;

// Get parameters from the URL
$id = (isset($_SESSION[‘CURRENT_ITEM’])) ? intval($_SESSION[‘CURRENT_ITEM’]) : 0;
$id = (isset($_REQUEST[‘id’])) ? intval($_REQUEST[‘id’]) : 0;**

ETA - at the end of track_audio.php you do a session redirect - I don’t think you should be doing that once you’re calling the code via Ajax as it runs in the background.

u mean this

if (isset($_POST['action']) && $_POST['action'] == 'update_play')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;
                    
    header('location: track_audio.php?id=' . $id);
    exit();
}

beomes

if (isset($_POST['action']) && $_POST['action'] == 'update_play')
{
    if (!isset($_SESSION['played_item_'.$id])) {
        $query = "UPDATE " . $DBPrefix . "auccounter set play_counter = play_counter + 1 WHERE auction_id = :auction_id";
        $params = array();
        $params[] = array(':auction_id', $id, 'int');
        $params[] = array(':play_counter', $id, 'int');

        $db->query($query, $params);
    }

    $_SESSION['played_item_'.$id] = true;

}

And… you say “full code”, but your PHP script doesn’t seem to include anything to connect to the database. Did you miss that out of the post for clarity? Remember that your Ajax call launches that PHP code in track_audio.php in isolation, so everything you need has to be in there.

it all goes here
include ‘common.php’;

EATA - there’s loads of missing semi-colons on the end of your JavaScript, is that for this post or are you getting loads of syntax errors in the javascript console in your browser?

no error or atleast i dont see 1 wont really know not so dope a coder like u to spot a issue from a mile away

so there i cant get it to work still

I’d expect all these lines of your JS code:

  var xhr = new XMLHttpRequest()
  var data = new FormData()

  data.append('action', 'update_play')
 xhr.open('POST', '{SITEURL}track_audio.php')
 xhr.send(data)
 event.preventDefault()

to end with a semi-colon, just like you do in PHP, and maybe some more of them. I’m not very experienced in JS.

That’s fine, but it wasn’t in the “full code” you posted, so it’s not easy to guess what might or might not be there.

So in this code:

// Get parameters from the URL
id = (isset(_SESSION[‘CURRENT_ITEM’])) ? intval($_SESSION[‘CURRENT_ITEM’]) : 0;
id = (isset(_REQUEST[‘id’])) ? intval($_REQUEST[‘id’]) : 0;**

first of all, you need a $ prefix on the id variable name, like you do everywhere else in PHP. Maybe that’s just missed off for the forum post. If not, then it will give you problems.

But, presuming you’ve fixed that, you still have a problem. Your code looks to see if there’s a session variable for the current item (although there are missing $_ prefixes there, too), if there is that’s what you assign to $id, and if not, you assign 0 to $id. On the very next line, though, you look for a $_REQUEST variable called id, if there is one you assign that value to $id, otherwise you assign 0.

So, if you call it from your Ajax code and have the id in the session variable and not in the $_GET or $_POST array, it’ll be assigned to the $id variable, but then the next line will see there’s no $_REQUEST['id'] variable, and overwrite it with zero. So you should maybe have an if/then/else in there - if there’s a session variable, use that, if there isn’t, see if there’s a $_REQUEST variable and use that, and if there is neither, use zero or don’t run the code, whatever is appropriate.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.