jQuery.timer如何在php中获取当前值? [英] jQuery.timer how to get current value in php?

查看:60
本文介绍了jQuery.timer如何在php中获取当前值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此jquery计时器来收集运行时所花费的时间.

https://github.com/walmik/timer.jquery

http://jquerytimer.com/

如何将当前值转换为php变量?

我想要一个按钮,单击该按钮会将当前值保存在输入字段中.

问题是,当我将输入包装成表格并期望使用$ _POST ['fieldID']来收集值时,它将禁用jqueryTimer.

我可以从表单中拉出输入字段,但是收集jQuery呈现的当前值的最佳方法是什么?写一个脚本添加项,用jQueryTimer中的当前值填充一个隐藏字段?

如果调用暂停"和重新启动"也可以更新php可用的值,那将是理想的选择.

编辑显示代码:

<script src='https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.6.5/timer.jquery.min.js'></script>

<!--    http://jquerytimer.com/-->
<script>
    $(document).ready(function(){
        var hasTimer = false;
        // Init timer start
        $('.start-timer-btn').on('click', function() {
            hasTimer = true;
            $('.timer').timer({
                editable: true
            });
            $(this).addClass('d-none');
            $('.pause-timer-btn, .remove-timer-btn').removeClass('d-none');
        });

        // Init timer resume
        $('.resume-timer-btn').on('click', function() {
            $('.timer').timer('resume');
            $(this).addClass('d-none');
            $('.pause-timer-btn, .remove-timer-btn').removeClass('d-none');
        });


        // Init timer pause
        $('.pause-timer-btn').on('click', function() {
            $('.timer').timer('pause');
            $('.resume-timer-btn').removeClass('d-none');
        });

        // Remove timer
        $('.remove-timer-btn').on('click', function() {
            hasTimer = false;
            $('.timer').timer('remove');
            $(this).addClass('d-none');
            $('.start-timer-btn').removeClass('d-none');
            $('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
        });

        // Additional focus event for this demo
        $('.timer').on('focus', function() {
            if(hasTimer) {
                $('.pause-timer-btn').addClass('d-none');
                $('.resume-timer-btn').removeClass('d-none');
            }
        });

        // Additional blur event for this demo
        $('.timer').on('blur', function() {
            if(hasTimer) {
                $('.pause-timer-btn').removeClass('d-none');
                $('.resume-timer-btn').addClass('d-none');
            }
        });
    });

$('.timer').each(function() {
console.log( this.val() );
});
</script>

html:

    <div class='row'>
            <div class='col-md-3'>
                <input type='text' name='timer' class='form-control timer' placeholder='0 sec'  id="timer" />
            </div>
            <div class='col-md-9'>
                <button class='btn btn-success start-timer-btn'>Start</button>
                <button class='btn btn-success resume-timer-btn d-none'>Resume</button>
                <button class='btn btn-secondary pause-timer-btn d-none'>Pause</button>
                <button class='btn btn-danger remove-timer-btn d-none'>Remove Timer</button>
            </div>
        </div>
<form action="" method="" id="form1">
<input type="submit">
<input name="currentTime" type="hidden" id="currentTime" value="needed">
</form>

目标:能够将当前值作为php var,以便可以将其提交到数据库.

先前的尝试发现,如果输入在表单标签内,它将不再起作用.

正在考虑的想法是在某些单击上更新隐藏的输入字段,这将使其可以在PHP中使用以插入到数据库.

解决方案

这是我的建议.它确实基于执行ajax请求.在这种情况下,当然不需要表格.如前所述,提交表单后,与当前页面中的计时器相关的所有信息都会丢失,因为提交会刷新计时器所在的整个页面,甚至会重定向到另一个页面(如果需要的话).

您可以按原样运行我的代码,但是您需要在 INSERT sql语句中更改数据库连接凭据和与数据库表相关的信息.

计时器驻留在 index.php 中.服务器端保存操作在 saveTime.php 中执行-我为其使用了PDO扩展名.数据库连接是在 connection.php 中创建的.

在客户端,通过单击 .save-timer-btn 按钮或启动保存操作- saveTime(). pause-timer-btn 按钮.但是您可以根据自己选择的事件调用 saveTime().

如果未定义发布的计时器值,则PHP代码将发送响应标头,从而触发ajax请求的 error 函数.然后, error 函数将显示 danger 类型的引导警报.如果PHP无法识别所传递的计时器状态,则同样适用.如果保存操作成功,将显示成功警报.

注意:我的代码不依赖您的代码,但它们只是稍有不同.这是因为我使用了计时器的最新版本( 0.7.1 )和演示中使用的代码

https://github.com/walmik/timer.jquery

http://jquerytimer.com/

How to I get the current value into a php variable?

I'd like to have a Button that when clicked saves the current value in the input field.

Problem is that when I wrap the input in a form and expect to use a $_POST['fieldID'] to collect the value it disables the jqueryTimer.

I can pull the input field out of the form but what is the best means to collect the current value presented with jQuery? Write a script addition that populates a hidden field with the current value from jQueryTimer?

It would be ideal if the value available to php could also be updated if the Pause and restart is invoked.

EDIT TO SHOW CODE:

<script src='https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.6.5/timer.jquery.min.js'></script>

<!--    http://jquerytimer.com/-->
<script>
    $(document).ready(function(){
        var hasTimer = false;
        // Init timer start
        $('.start-timer-btn').on('click', function() {
            hasTimer = true;
            $('.timer').timer({
                editable: true
            });
            $(this).addClass('d-none');
            $('.pause-timer-btn, .remove-timer-btn').removeClass('d-none');
        });

        // Init timer resume
        $('.resume-timer-btn').on('click', function() {
            $('.timer').timer('resume');
            $(this).addClass('d-none');
            $('.pause-timer-btn, .remove-timer-btn').removeClass('d-none');
        });


        // Init timer pause
        $('.pause-timer-btn').on('click', function() {
            $('.timer').timer('pause');
            $('.resume-timer-btn').removeClass('d-none');
        });

        // Remove timer
        $('.remove-timer-btn').on('click', function() {
            hasTimer = false;
            $('.timer').timer('remove');
            $(this).addClass('d-none');
            $('.start-timer-btn').removeClass('d-none');
            $('.pause-timer-btn, .resume-timer-btn').addClass('d-none');
        });

        // Additional focus event for this demo
        $('.timer').on('focus', function() {
            if(hasTimer) {
                $('.pause-timer-btn').addClass('d-none');
                $('.resume-timer-btn').removeClass('d-none');
            }
        });

        // Additional blur event for this demo
        $('.timer').on('blur', function() {
            if(hasTimer) {
                $('.pause-timer-btn').removeClass('d-none');
                $('.resume-timer-btn').addClass('d-none');
            }
        });
    });

$('.timer').each(function() {
console.log( this.val() );
});
</script>

html:

    <div class='row'>
            <div class='col-md-3'>
                <input type='text' name='timer' class='form-control timer' placeholder='0 sec'  id="timer" />
            </div>
            <div class='col-md-9'>
                <button class='btn btn-success start-timer-btn'>Start</button>
                <button class='btn btn-success resume-timer-btn d-none'>Resume</button>
                <button class='btn btn-secondary pause-timer-btn d-none'>Pause</button>
                <button class='btn btn-danger remove-timer-btn d-none'>Remove Timer</button>
            </div>
        </div>
<form action="" method="" id="form1">
<input type="submit">
<input name="currentTime" type="hidden" id="currentTime" value="needed">
</form>

GOAL: Be able to have the current value as a php var so it can be submitted to a database.

Prior attempts found that if the input was within a form tag it no longer worked.

Idea in consideration is updating the hidden input field on some click which would allow it to be used in PHP to Insert to DB.

解决方案

Here is my proposal. It's indeed based on performing an ajax request. A form is, of course, not needed in this case. As already commented, by submitting a form, all informations related to the timer in the current page would be lost, because the submit would refresh the whole page where the timer resides, or would even redirect to another page - if so demanded.

You can run my code as it is, but you need to change the db connection credentials and the db table related infos in the INSERT sql statement.

The timer resides in index.php. The server-side saving operation is performed in saveTime.php - I used the PDO extension for it. The database connection is created in connection.php.

On the client-side, the saving operation - saveTime() - is started by clicking the .save-timer-btn button, or the .pause-timer-btn button. But you can call saveTime() on the events of your choice.

If the posted timer value is not defined, the PHP code sends a response header, which triggers the error function of the ajax request. The error function will then display a bootstrap alert of type danger. The same applies if the passed timer state is not recognised by PHP. If the saving operation succeeds, a success alert will be displayed.

Note: My codes don't rely on your codes, but they are just slightly different. This is because I used the last version (0.7.1) of the timer and the code used in the demo from jquerytimer.com. I suggest you to pay attention to each code line. Sorry :-) I also used the version 3.3.7 of Bootstrap.

Note: For proper error reporting/handling you could read this and this articles, since I didn't implement it in my PHP code.

index.php

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
        <meta charset="UTF-8" />
        <!-- The above 3 meta tags must come first in the head -->

        <title>Demo - Timer</title>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" type="text/css" rel="stylesheet" />

        <script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" type="text/javascript"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/timer.jquery/0.7.1/timer.jquery.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $(document).ready(function () {
                var hasTimer = false;

                /**
                 * Save the current timer value.
                 * 
                 * Performs an ajax request to the server, which will 
                 * save the timer value in a database table and return
                 * a corresponding message.
                 */
                function saveTime() {
                    $.ajax({
                        method: 'post',
                        dataType: 'html',
                        url: 'saveTime.php',
                        data: {
                            'time': $('.timer').data('seconds'),
                            'state': $('.timer').data('state')
                        },
                        success: function (response, textStatus, jqXHR) {
                            displayAlert('success', response);
                        },
                        error: function (jqXHR, textStatus, errorThrown) {
                            /*
                             * If the status code of the response is the custom one 
                             * defined by me, the developer, in saveTime.php, then I 
                             * can display the corresponding error message. Otherwise, 
                             * the displayed message will be a general user-friendly 
                             * one - so, that no system-related infos will be shown.
                             */
                            var message = (jqXHR.status === 420)
                                    ? jqXHR.statusText
                                    : 'An error occurred during your request. Please try again.';

                            displayAlert('danger', message);
                        },
                        complete: function (jqXHR, textStatus) {
                            //...
                        }
                    });
                }

                /**
                 * Display a bootstrap alert.
                 * 
                 * @param type string success|info|warning|danger.
                 * @param message string Alert message.
                 * @return void
                 */
                function displayAlert(type, message) {
                    var alert = '<div class="alert alert-' + type + ' alert-dismissible" role="alert">'
                            + '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'
                            + '<span aria-hidden="true">&times;</span>'
                            + '</button>'
                            + '<span>' + message + '</span>'
                            + '</div>';

                    $('.messages').html(alert);
                }

                // Init timer start
                $('.save-timer-btn').on('click', function () {
                    saveTime();
                });

                // Init timer start
                $('.start-timer-btn').on('click', function () {
                    hasTimer = true;
                    $('.timer').timer({
                        editable: true
                    });
                    $(this).addClass('hidden');
                    $('.pause-timer-btn, .remove-timer-btn').removeClass('hidden');
                });

                // Init timer resume
                $('.resume-timer-btn').on('click', function () {
                    $('.timer').timer('resume');
                    $(this).addClass('hidden');
                    $('.pause-timer-btn, .remove-timer-btn').removeClass('hidden');
                });

                // Init timer pause
                $('.pause-timer-btn').on('click', function () {
                    $('.timer').timer('pause');
                    $(this).addClass('hidden');
                    $('.resume-timer-btn').removeClass('hidden');

                    saveTime();
                });

                // Remove timer. Leaves the display intact.
                $('.remove-timer-btn').on('click', function () {
                    hasTimer = false;
                    $('.timer').timer('remove');
                    $(this).addClass('hidden');
                    $('.start-timer-btn').removeClass('hidden');
                    $('.pause-timer-btn, .resume-timer-btn').addClass('hidden');
                });

                // Additional focus event for this demo
                $('.timer').on('focus', function () {
                    if (hasTimer) {
                        $('.pause-timer-btn').addClass('hidden');
                        $('.resume-timer-btn').removeClass('hidden');
                    }
                });

                // Additional blur event for this demo
                $('.timer').on('blur', function () {
                    if (hasTimer) {
                        $('.pause-timer-btn').removeClass('hidden');
                        $('.resume-timer-btn').addClass('hidden');
                    }
                });
            });
        </script>

        <style type="text/css">
            body {
                padding: 50px;
            }
        </style>
    </head>
    <body>

        <div class="container">
            <div class="row">
                <div class="col-xs-12">
                    <h4>
                        Timer Demo
                    </h4>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-6 messages"></div>
            </div>
            <div class="row">
                <div class="col-md-3">
                    <input type="text" id="timer" name="timer" class="form-control timer" placeholder="0 sec">
                </div>
                <div class="col-md-9">
                    <button type="button" class="btn btn-success start-timer-btn">
                        Start
                    </button>
                    <button type="button" class="btn btn-success resume-timer-btn hidden">
                        Resume
                    </button>
                    <button type="button" class="btn pause-timer-btn hidden">
                        Pause
                    </button>
                    <button type="button" class="btn btn-danger remove-timer-btn hidden">
                        Remove Timer
                    </button>

                    <button type="button" class="btn btn-primary save-timer-btn">
                        Save timer value
                    </button>
                </div>
            </div>
        </div>

    </body>
</html>

saveTime.php

<?php

require 'connection.php';

// Validate the timer value.
if (!isset($_POST['time']) || empty($_POST['time'])) {
    /*
     * This response header triggers the ajax error because the status 
     * code begins with 4xx (which corresponds to the client errors).
     * I defined 420 as the custom status code. You can choose whatever
     * code between 401 and 499 which is not officially assigned, e.g.
     * which is marked as "Unassigned" in the official HTTP Status Code Registry.
     * See the link.
     * 
     * @link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
     */
    header('HTTP/1.1 420 No time value defined. Did you start the timer?');
    exit();
}

// Validate the timer state.
if (!isset($_POST['state']) || empty($_POST['state'])) {
    header('HTTP/1.1 420 No timer state recognized. Did you start the timer?');
    exit();
}

// Read the posted values.
$time = $_POST['time'];
$state = $_POST['state']; /* The state of the timer when the saving operation was triggered. */

/*
 * Save the timer value in a db table using PDO library.
 */
$sql = 'INSERT INTO my_timer_table (
            time
        ) VALUES (
            :time
        )';
$statement = $connection->prepare($sql);
$statement->execute([
    ':time' => $time,
]);

// Print success message.
echo 'Time (' . $time . ' seconds) successfully saved when timer was ' . $state . '.';
exit();

connection.php

<?php

// Db configs.
define('HOST', 'localhost');
define('PORT', 3306);
define('DATABASE', 'yourDb');
define('USERNAME', 'yourUsername');
define('PASSWORD', 'yourPassword');
define('CHARSET', 'utf8');

$connection = new PDO(
        sprintf('mysql:host=%s;port=%s;dbname=%s;charset=%s', HOST, PORT, DATABASE, CHARSET)
        , USERNAME
        , PASSWORD
        , [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => FALSE,
    PDO::ATTR_PERSISTENT => FALSE,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]
);

Create table syntax

CREATE TABLE `my_timer_table` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `time` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

这篇关于jQuery.timer如何在php中获取当前值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆