O
O
Oleg2018-11-04 21:45:59
MODX
Oleg, 2018-11-04 21:45:59

How to make a counter on MODX that is common to all users and increases on button click?

The site has a test page. It consists of 3 sections.
The first one shows how many times the test has already been passed.
In the second, the actual test itself with questions.
In the third test results.
I need the counter value to increase by 1 when moving from the second section to the third (this transition occurs when clicking on the "Show Results" button).
The question is actually. Where is the best place to store this value? And how to increase it?
I now stupidly copied the template, created a custom field of type "Number" and attached it to the new template. Set the page with the test this template. I got the number, everything is ok. But how to increase it? Or maybe it's better to do something differently?
upd. Transitions between sections occur without reloading the page and without AJAX.
upd2. In general, I share one of the solutions. I don't know if it's right or wrong, but it works. I will wait for comments.
Created two files in the assets folder:
counter.txt
counter.php
The current value of the counter is stored in txt.
In php, the code that increments the value by 1. Here is the code itself:

<?php

$cnt = file_get_contents('counter.txt');
$cnt++;

$file = fopen('counter.txt', 'w');
$write = fwrite($file, $cnt);
fclose($file);

In the script.js file, I add two pieces of code.
The first one makes an AJAX request to the txt file, grabs its content and adds it to the page:
$.ajax({
  url: "/assets/counter.txt",
  dataType: "text",
  async: true,
  success: function(response) {
    $('.counterWrap').text(response);
  }
});

The second click simply accesses the php file without passing any data:
$('.btn').one('click', function() {

  $.ajax({
    url: '/assets/counter.php',
    type: 'POST',
    data: ''
  })
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2018-11-08
@ig0r74

Instead of a text file, use the system setting. Instead of a php file - a snippet, call it on a specially created page with an empty template. And already access this page via Ajax.
Example:

$Setting = $modx->getObject('modSystemSetting', 'site_name');
$Setting->set('value', 'My New Site Name');
$Setting->save();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question