This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// плюрализатор (человек/человека в зав-сти от числа) | |
var N = Math.floor(Math.random()*100)+1; // случ число от 1 до 101 | |
function suffix(N) { | |
return [2,3,4].indexOf(N % 10) !== -1 && [12,13,14].indexOf(+String(N).slice(-2)) === -1 ? "a" : ""; | |
} | |
console.log("Записалось " + N + " человек" + suffix(N)); | |
// ES6-версия функции suffix: | |
let N = Math.floor(Math.random()*100)+1; // случ число от 1 до 101 | |
let suffix = N => [2,3,4].indexOf(N % 10) !== -1 && [12,13,14].indexOf(+String(N).slice(-2)) ? "а" : ""; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// добавим нового юзера в БД со статусом TEMP и случайным паролем | |
$new_password = generateRandomString(); | |
$query_str = "INSERT INTO t_users (status,type,password) VALUES ('temp','seller','{$new_password}')"; | |
$query = mysqli_query($db, $query_str); | |
// теперь запросим базу какой user_id она ему дала | |
$user_id = mysqli_insert_id($db); // вот так оказывается это просто! http://php.net/manual/ru/mysqli.insert-id.php |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> | |
</head> | |
<body> | |
<form method='post'> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$query = mysqli_query($db,"SELECT * FROM t_timeslots"); | |
while ($timeslot_row = mysqli_fetch_assoc($query)) { | |
echo $timeslot_row['filed01']." ".$timeslot_row['filed02']; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("input[type=file]").on("change", function(ev) { | |
// отправим аяксом запрос на апдейт | |
console.log("сработал апдейт аватар"); | |
ev.preventDefault(); | |
// var formData = new FormData($("form#update-avatar")[0]); | |
var form = $('form#update-avatar').get(0); // http://stackoverflow.com/a/32955835/6056120 | |
var formData = new FormData(form); | |
$.ajax({ | |
url: 'function_update_img.php', | |
type: 'POST', |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var testObject = { 'one': 1, 'two': 2, 'three': 3 }; | |
// помещаем данные | |
localStorage.setItem('testObject', JSON.stringify(testObject)); | |
// извлекаем данные | |
var retrievedObject = localStorage.getItem('testObject'); | |
console.log('retrievedObject: ', JSON.parse(retrievedObject)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Delegated events на http://api.jquery.com/on - это спасение! | |
// во-первых даже если элементов, для которых создаётся хендлер, на странице много, для них всех создается только 1 евентлисенер, который вешаетcя на самый родителский элемент страницы (body например или document) и ловит "пузырьки" (bubbling up или propagation of events) от кликов по этим дочерним элементам, поднимающиеся на самый верх вплоть до уровня document (если не активирован метод preventPropagation на этих событиях). "Ловля" и опознание нужных событий от нужных элементов происходит по их селекторам класса или id-а или тега, тут всё привычно. | |
// в момент создания (привязки) события к хендлеру, важно наличие в DOMe только основного "родителя", на уровне которого будут ловиться пузырьки от событий этих дочерних эл-тов. Присутствие в DOM-e самих дочерних элементов в момент привязки евентлисенера необязательно, они могут создаваться позже и на них автоматически будет вешаться лисенер, соотв-щий их селектору | |
$("body" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.onerror = function() { | |
return true; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function currentFuncName() { | |
// при вызове этой ф-и внутри других ф-й, она вернёт их имя | |
// но вообще caller и callee уже устарели и не работают в strict mode | |
return (arguments.callee.caller.toString().match(/function\s+([^\s\(]+)/))[1]; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// if statement rules and tricks | |
$a = 3; // переменные начинаются ТОЛЬКО с $, забудешь - получишь ошибку | |
$b = 3; // $this - зарезервирована, название с цифры начинаться не может, а с "_" - может. | |
if ($a == $b) echo "a = b <br />"; // в однострочном вар-те фиг скобки не нужны, поставишь - будет ошибка! | |
if ($a == $b) { // а в многострочном - нужны | |
echo "a = b <br />"; |
NewerOlder