-2

I have a feature where user can view jobs. I want to show the jobs to user accroding to most viewed jobs. So when the view this job button will be clicked their will be table on database view_count that's value will increase. i wrote a script for this but its not working. Maybe the AJAX request is not being sent or received correctly, so the script is not being executed.

here is the button

<a id="view-job-btn-<?php echo $row['job_id']; ?>"
   target="_blank"
   href="explore-job.php?jobid=<?php echo $row['job_id']; ?>"
   class="btn btn-primary view-job-btn"
   data-job-id="<?php echo $row['job_id']; ?>">
    View This Job
    <span class="view-count"><?php echo $row['view_count']; ?></span>
</a>

and script

<script type="text/javascript" >


document.addEventListener('DOMContentLoaded', function() {
    const viewJobBtn = document.getElementById('view-job-btn-<?php echo $row['job_id']; ?>');
    viewJobBtn.addEventListener('click', function() {
        // Rest of the code here
        const jobId = viewJobBtn.dataset.jobId;
    
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'update-view-count.php', true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                console.log(xhr.responseText);
             
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    const viewCountElement = viewJobBtn.querySelector('.view-count');
                    const currentViewCount = parseInt(viewCountElement.textContent);
                    viewCountElement.textContent = currentViewCount + 1;
                    console.log(response);
                        console.log(currentViewCount);
                }
            }
            else{
                console.log("Erororor");
            }
        };
        xhr.send('jobId=' + encodeURIComponent(jobId));
    });
});


</script>

update-view-count.php file code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Check if the job ID is set in the AJAX request
if(isset($_POST['jobId'])) {
    $jobId = $_POST['jobId'];
    
    error_log("Received job ID: " . $_POST['jobId']);

    // TODO: Update the view count for the job in the database
    // Assuming the table name is tbl_jobs
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "job_portal";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "UPDATE tbl_jobs SET view_count = view_count + 1 WHERE enc_id = '$jobId'";

    $result = $conn->query($sql);

    if (!$result) {
        echo "Database error: " . $conn->error;
    } else {
        echo "View count updated successfully";
    }

    $conn->close();
} else {
    echo "Job ID not set";
}
?>

I have a feature where user can view jobs. I want to show the jobs to user accroding to most viewed jobs. So when the view this job button will be clicked their will be table on database view_count that's value will increase. ` The value of the "data-job-id" attribute of the button using the dataset property. This will get the value of the "jobId" variable.

Then, I am creating a new XMLHttpRequest object and setting up the request to update the view count by sending the jobId value to the update-view-count.php file using a POST request.

When the request is complete, the function inside the onreadystatechange event will be executed. If the request was successful (i.e., readyState is 4 and status is 200), that will update the view count on the button by getting the "view-count" element and incrementing its value.`

  • 1
    Your script is vulnerable to [SQL Injection Attack](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). Even if [you are escaping variables, its not safe](https://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string%5D)! You should always use [prepared statements and parameterized queries](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either MYSQLI or PDO instead of concatenating variables into the query. – Barmar Apr 04 '23 at 20:12
  • Have you used the Network tab to see what request is being sent and what response you're getting? – Barmar Apr 04 '23 at 20:15
  • I checked the Network tab. I am not sure, I am correct or not but this tab is empty. – Md. Jahangir Alam Apr 04 '23 at 20:23
  • Are you sure the event listener is running? Add ```console.log(`Incrementing ${jobId}`)``` – Barmar Apr 04 '23 at 20:24
  • console.log(`Incrementing ${jobId}`) its not showing anything. this is i got after clicking the button " document.addEventListener('DOMContentLoaded', function() { const viewJobBtn = document.getElementById('view-job-btn-0216766045'); viewJobBtn.addEventListener('click', function() { const jobId = viewJobBtn.dataset.jobId; const xhr = new XMLHttpRequest(); xhr.open('POST', 'update-view-count.php', true); xhr.send('jobId=' + encodeURIComponent(jobId)); 0216766045 console.log(jobId); console.log(`Incrementing ${jobId}`); – Md. Jahangir Alam Apr 04 '23 at 20:29
  • That means you're not actually adding the event listeners properly to the buttons. Instead of adding a listener to each button, try using event delegation. – Barmar Apr 04 '23 at 20:30
  • `const viewJobBtn = document.getElementById('view-job-btn-');` - are you generating an individual script block for each link? That is quite bad to begin with. You should be using classes for this, not IDs. – CBroe Apr 05 '23 at 06:34
  • Please trim your code to make it easier to find your problem. Follow these guidelines to create a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Community Apr 05 '23 at 14:46

1 Answers1

0

In update-view-count.php use error_log(...) not echo or die. This has PHP write to Apache's error.log. Echos go nowhere.

Check the SQL by manually running the UPDATE from the mysql commandline tool.

Rick James
  • 135,179
  • 13
  • 127
  • 222