Jquery limit user upload to 5 posts every minute - javascript

I have got this jquery/ajax
var uploaded=0;
if (uploaded!=0) {
setInterval(function() {
uploaded--;
}, 60000);
alert(uploaded);
}
$(".UploadMSub").click(function(event){
event.preventDefault();
var form_data = new FormData($('.SubmUploadFu')[0]);
if (uploaded<=5) {
$.ajax({
url: '../connect.php',
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data)
{
var json_x = $.parseJSON(data);
var classRes = json_x[0].substring(0, 1);
$(".Result").html(json_x[0]).addClass(classRes).fadeIn(500).delay(2500).fadeOut(500,function() {
$(this).removeClass(classRes);
});
$(".Posts").children(".NumberOf").html(json_x[1]);
$(".Text").val("");
$("#Nameupload").val("");
$(".PhotShow").slideUp(500);
uploaded++;
}
});
}else{
$(".Result").html("You can upload up to 5 posts in one minute").addClass("E").fadeIn(500).delay(2500).fadeOut(500);
}
});
And this php
function isFileUploadAllowed() {
$isAllowed = true;
$timeNow = time();
$timeFrameInSeconds = 30;
$maxUploadsInTimeFrame = 5;
$firstUploadTime = $_SESSION['firstUploadTime'] ? intval($_SESSION['firstUploadTime']) : $timeNow;
$numberOfUploadsInTimeFrame = $_SESSION['numberOfUploadsInTimeFrame'] ? intval($_SESSION['numberOfUploadsInTimeFrame']) : 0;
$givenTimeFrameExpired = (($firstUploadTime + $timeFrameInSeconds) < $timeNow);
if (!$givenTimeFrameExpired) {
if ($numberOfUploadsInTimeFrame + 1 > $maxUploadsInTimeFrame) {
$isAllowed = false;
}
}
if ($isAllowed === true) {
if ($givenTimeFrameExpired) {
$_SESSION['firstUploadTime'] = $timeNow;
$_SESSION['numberOfUploadsInTimeFrame'] = 0;
}
$_SESSION['numberOfUploadsInTimeFrame']++;
}
return $isAllowed;
}
if(isset($_POST['new_post'])){
$Text=htmlspecialchars($_POST['new_post'],ENT_QUOTES);
$Text=trim($Text);
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'])) {
if (isFileUploadAllowed()) {
$fileP=$_FILES['Upload_f'];
$fileP_name=$fileP['name'];
$fileP_tmp=$fileP['tmp_name'];
$fileP_size=$fileP['size'];
$fileP_error=$fileP['error'];
$fileP_extension=explode('.', $fileP_name);
$fileP_extension=strtolower(end($fileP_extension));
$allowed=array('jpg','png');
if (in_array($fileP_extension, $allowed)){
if ($fileP_error===0) {
if ($fileP_size<=2097152){
$fileP_new_name=uniqid().'.'.$fileP_extension;
}
}
$NotInarray=false;
}else{
$fileP_new_name="";
$NotInarray=true;
}
$Fileuploaded=true;
}
}else{
$fileP_new_name="";
$fileP=0;
$Fileuploaded=false;
$NotInarray=false;
}
$Posts=$con->query("SELECT Posts FROM user_opt WHERE Username='$NameId'");
$row=$Posts->fetch_row();
if (strlen($Text)>400) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}elseif(strlen($Text)==0 && $fileP==0){
$Res="Both fields are empty";
$PostNum=$row[0];
}elseif($Fileuploaded===true){
if ($NotInarray==true) {
$Res="Only jpg and png files are allowed";
$PostNum=$row[0];
}elseif ($fileP_error!=0) {
$Res="Error occurred.Please try again";
$PostNum=$row[0];
}else{
$Res="Success";
$PostNum=$row[0]+1;
}
}else{
$Rand=generateRandomString(100);
$query=$con->query("INSERT INTO uploads (Rand,Username,image,`Text`,`Date`) VALUES('$Rand','$NameId','$fileP_new_name','$Text',NOW())");
$querya=$con->query("UPDATE user_opt SET posts=posts+1 WHERE Username='$NameId'");
$PostNum=$row[0]+1;
$Res="Success";
}
echo json_encode(array($Res,$PostNum));
}
But the problem is when user uses dev tools he can easily change
if (uploaded<=5) {
To
if (uploaded<=50) {
And jquery will take increase limit to 50.How can i prevent that?
Also may the problem be in php function?Cause if my php function works properly it should not insert data into database but it does

You have no else clause for if (isFileUploadAllowed()), so you're not clearing the variables. You can combine that test with the outer test:
if (is_uploaded_file($_FILES['Upload_f']['tmp_name'] && isFileUploadAllowed())

Related

how do i save my login details and redirect page properly?

** i am trying to do save login details and it works but when signin(true) fuction called page get reload infinity times **
signin(true)
// doing sign in
function onlogin(dataResult, is_check_login) {
$("#preloader").show();
var dataResult = JSON.parse(dataResult);
if (dataResult.statusCode == 200) {
$("#preloader").hide();
var signedin_user_id = dataResult.row_id;
// open dashboard if already logged in
window.location.href = '../page/index.html';
document.getElementById("dashboard_name").innerHTML = dataResult.name;
} else if (dataResult.statusCode == 201) {
$("#preloader").hide();
if (is_check_login) {
//open sign in form if not logged in
window.location.href = '../page/signin.html';
} else {
$("#preloader").hide();
console.log('invalid login');
}
}
}
function sign_in(is_check_login = false) {
var signin_email = $('#signin_email').val();
var signin_password = $('#signin_password').val();
if (is_check_login || (signin_email != "" && signin_password != "")) {
$.ajax({
url: `https://www.name.com/page/php/${is_check_login ? "checklogin" : "login"}.php`,
type: "POST",
data: {
signin_email: signin_email,
signin_password: signin_password
},
cache: false,
success: function (result) {
onlogin(result, is_check_login);
}
});
} else {
alert('Please fill all the field !');
}
}

Lazy loading works for loading data, but not when filtering

Here the first script is written for lazy loading the table data and the second script is written for filtering with lazy loading but the second one is not working.
I have a Codeigniter report in which I did some filtering on the table data. I am using jQuery AJAX to lazy load data. What I expected is that when I fetch the data with a filter the lazy loading is not working. Shall i use first script for both table load by default and for filter. i am getting confusion. Can anyone please tell me how to merge both script as a single script for both. Please help.
$(document).ready(function() {
$('#filter').popover({
placement: 'bottom',
title: (' ') + '<button type="button" class="close pull-right" data-dismiss="alert" style="color:black;">×</button>',
html: true,
content: $('#customdiv').html()
});
$(document).on("click", ".popover .close", function() {
$(this).parents(".popover").popover('hide');
});
var limit = 20;
var start = 0;
var action = 'inactive';
function lazzy_loader(limit) {
var output = '';
for (var count = 0; count < limit; count++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_message').html(output);
}
lazzy_loader(limit);
function search_fields(limit, start) {
$(".spinner").show();
$.ajax({
url: "<?=base_url()?>missed_call_campaign/fetch_data",
method: "POST",
data: {
limit: limit,
start: start
},
cache: false,
success: function(data) {
$(".spinner").hide();
if (data == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found</p>');
action = 'active';
} else {
$('#load_data').append(data);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
if (action == 'inactive') {
action = 'active';
search_fields(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data").height() && action == 'inactive') {
lazzy_loader(limit);
action = 'active';
start = start + limit;
setTimeout(function() {
search_fields(limit, start);
}, 100);
}
});
});
function subcategory() {
var ClickedCategory = new Array();
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subcategory_checkbox",
data: {
type: 'text',
ClickedCategory: ClickedCategory
},
success: function(response) {
$("#collapsepp").hide();
$("#collapseqq").html(response);
}
});
}
function subsource() {
var ClickedSource = new Array();
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$.ajax({
type: 'POST',
url: "<?=base_url()?>missed_call_campaign/subsource_checkbox",
data: {
type: 'text',
ClickedSource: ClickedSource
},
success: function(response) {
$("#collapserr").hide();
$("#collapsess").html(response);
}
});
}
function clearFilter() {
location.reload();
}
$(document).ready(function() {
$(document).on("click", "#data_filter", function() {
var CheckedRep = new Array();
var ClickedStatus = new Array();
var ClickedType = new Array();
var ClickedCategory = new Array();
var ClickedSubCategory = new Array();
var ClickedSubCategory_Filter = new Array();
var ClickedSource = new Array();
var ClickedSubSource = new Array();
var ClickedSubSource_Filter = new Array();
$('.RepClicked').each(function() {
if ($(this).is(':checked')) {
CheckedRep.push($(this).val());
}
});
$('.StatusClicked').each(function() {
if ($(this).is(':checked')) {
ClickedStatus.push($(this).val());
}
});
$('.TypeClicked').each(function() {
if ($(this).is(':checked')) {
ClickedType.push($(this).val());
}
});
$('.CategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedCategory.push($(this).val());
}
});
$('.SourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSource.push($(this).val());
}
});
$('.SubSourceClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource.push($(this).val());
}
});
$('.SubCategoryClicked').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory.push($(this).val());
}
});
$('.SubCategoryChecked_Filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubCategory_Filter.push($(this).val());
}
});
$('.SubSourceClicked_filter').each(function() {
if ($(this).is(':checked')) {
ClickedSubSource_Filter.push($(this).val());
}
});
if ((CheckedRep.length > 0) || (ClickedStatus.length > 0) || (ClickedType.length > 0) || (ClickedCategory.length > 0)
(ClickedSource.length > 0) || (ClickedSubSource.length > 0) || (ClickedSubCategory.length > 0) ||
(ClickedSubCategory_Filter.length > 0) || (ClickedSubSource_Filter.length > 0)) {
var limits = 20;
var starts = 0;
var actions = 'inactive';
lazzy_loading(limits);
if (actions == 'inactive') {
actions = 'active';
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(window).height() > $("#load_data_filter").height() && actions == 'inactive') {
lazzy_loading(limits);
actions = 'active';
starts = starts + limits;
setTimeout(function() {
filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter);
}, 100);
}
});
}
});
function lazzy_loading(limits) {
var output = '';
for (var counts = 0; counts < limits; counts++) {
output += '<tr class="post_data">';
output += '</tr>';
}
$('#load_data_filter').html(output);
}
function filter_data(limits, starts, CheckedRep, ClickedStatus, ClickedType, ClickedCategory, ClickedSubCategory, ClickedSubCategory_Filter,
ClickedSource, ClickedSubSource, ClickedSubSource_Filter) {
$.ajax({
url: "<?=base_url()?>missed_call_campaign/toDoAjax",
method: "POST",
data: {
type: 'text',
CheckedRep: CheckedRep,
ClickedStatus: ClickedStatus,
ClickedType: ClickedType,
ClickedCategory: ClickedCategory,
ClickedSource: ClickedSource,
ClickedSubSource: ClickedSubSource,
ClickedSubCategory: ClickedSubCategory,
ClickedSubCategory_Filter: ClickedSubCategory_Filter,
ClickedSubSource_Filter: ClickedSubSource_Filter,
limits: limits,
starts: starts
},
cache: false,
success: function(response) {
$(".spinner").hide();
$("#load_data").hide();
if (response == '') {
$('#load_data_message').html('<p class="content-desc">No More Data Found123</p>');
action = 'active';
} else {
$('#load_data_filter').append(response);
$('#load_data_message').html("");
action = 'inactive';
}
}
});
}
});
I suggest you to reinitialize the lazy load after success you fetched data from the back end.

JQuery check the file size from inside a function

So I have these Jquery code where the function will check the file extension and the file size from the input file. The checking for the file extension works fine, but the file size checking is not working, can you guys help me with this problem?
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("The maximum file size is 1 mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = $('#file_IdentitasKTP\\/Paspor').val();
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});
Try this :
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
...
you can check file size by :
console.log(fileinput[0].size)
For example to upload image by AJAX. You will simply write this code. You will size with object. it will return size of that object.
$(document).ready(function(e) {
$("#uploadimage").on('submit', (function(e) {
e.preventDefault();
formdata = new FormData(this);
if (formdata[0].size = < 1000) {
$.ajax({
url: "PHp File name path", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: formdata, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
} else {
alert("You can not Upload this file Please resize this image.")
}
}));
This is the updated code for this question.
$(document).ready(function () {
/* Some other code
*/
var fileExtension = ['jpeg', 'jpg', 'png', 'pdf'];
var status = false;
function checkFile(fileinput){
if ($.inArray(fileinput[0].name.split('.').pop().toLowerCase(), fileExtension) == -1) {
alert("Tolong upload file dengan extensi: " + fileExtension.join(', '));
fileinput.value = "";
return status = false;
}
if (fileinput[0].size > 1048576) {
alert("Tolong upload file dengan ukuran dibawah 1mb");
fileinput.value = "";
return status = false;
}
else {
return status = true;
}
}
$('#btn_IdentitasKTP\\/Paspor').on('click', function () {
$('#file_IdentitasKTP\\/Paspor').trigger('click')
});
$('#file_IdentitasKTP\\/Paspor').change(function () {
var fileinput = this.files;
checkFile(fileinput);
if (status == true) {
var file_name = this.value.replace(/\\/g, '/').replace(/.*\//, '');
$('#text_IdentitasKTP\\/Paspor').val(file_name);
status = false;
}
});
});

Function to check if it's holiday in jquery by date

I'm trying to make a function in jquery which checks if a given date is a holiday according to my database. I have created the function:
IsAHoliday(date)
Here is my code:
function IsAHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
async: false,
data: dataString,
success: function(r)
{
return r;
}
});
}
With this code i can't execute something like
if(IsAHoliday(date)) {
How could i achieve this ?
EDIT: Here is my datumPraznik.php
<?php
include_once('db-config.php');
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum=:datum');
$stmt->execute(array(':datum'=>$datum));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0)
{
$praznik = true;
}
else
{
$praznik = false;
}
echo $praznik;
?>
So what you could do get your PHP to return JSON so you can handle it with AJAX success function.
$datum = $_REQUEST['action'];
$stmt=$db_con->prepare('SELECT * FROM praznici WHERE praznik_datum='.$datum);
$stmt->execute();
if($stmt->fetchColumn() > 0){
$praznik = true;
} else {
$praznik = false;
}
return json_encode(array('praznik' => $praznik));
And your AJAX would be
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
console.log('This is a holiday');
} else {
console.log('This is not a holiday');
}
});
So your updated function would be:
function isHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
var data = 'action='+ datum;
$.post('include/datumPraznik.php', data, function(d) {
if(d.praznik === true) {
return true;
} else {
return false;
}
});
}
And use it as:
if(isHoliday(date) === true) {
// do something
}
First, PHP needs to return JSON, so change:
echo $praznik;
to:
echo json_encode($praznik);
Second, since AJAX is asynchronous (you shouldn't use async: false), your function should take callbacks:
function IsAHoliday(date, truecb, falsecb) {
var datum = moment(date).format('YYYY-MM-DD');
var dataString = 'action='+ datum;
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
cache: false,
data: dataString,
success: function(r)
{
if (r) {
truecb();
} else {
falsecb();
}
}
});
}
You then call it like:
IsAHoliday(date, function() {
// stuff to do on holiday
}, function() {
// stuff to do on non-holiday
});
I wasn't able to fix my problem using your solutions but i've combined them and came to this solution.
I've made a global variable (array) and called ajax which returns ALL HOLIDAY DATES and stores them in the global variable.
var prazniciArray = [];
$(document).ready(function()
{
$.ajax ({
type: "POST",
url: 'include/datumPraznik.php',
dataType: 'json',
cache: false,
success: function(rez)
{
praznici = rez;
for (var i = 0; i < praznici.length; i++) {
prazniciArray.push(moment(praznici[i]));
}
$('#datetimepicker1').data("DateTimePicker").disabledDates(prazniciArray);
}
});
}
After that i could make the function:
function IsHoliday(date) {
var datum = moment(date).format('YYYY-MM-DD');
if(jQuery.inArray(datum, praznici) !== -1)
{
return true
}
else
{
return false;
}
}
datumPraznik.php
<?php
include_once('db-config.php');
$stmt=$db_con->prepare('SELECT praznik_datum FROM praznici');
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$praznici = count($row);
$prazniciarray = array();
for ($i = 0; $i < $praznici; $i++) {
array_push($prazniciarray,$row[$i]["praznik_datum"]);
}
echo json_encode($prazniciarray);
?>
And my table looks like this:
praznik_id | praznik_ime | praznik_datum
-----------------------------------------
| 1 | Thanksgiving | 2017.07.01

Tree_view undefined after read kendo tree

Here's my problem:
I load a first time my tree to display him.
I can change the value of the Session's files name "state" to enable or disable a node in my tree.
But after I change ne value in my database and return the JSON, I read again the tree to refresh my tree with the changes but it's failed and write in console :
" TypeError: Tree_view.getElementsByClassName(...)[0].children[(item.id_perso - 1)].children[1] is undefined".
That I don't understand is I pass my first time by these functions and it work well, but when I reload it failed apparently because the it undefined.
Thank's for any help.
$(document).ready(function() {
$('#Tree_view').kendoTreeView({
template: "#= item.name #",
dataSource: Parcours,
dataTextField: 'name',
loadOnDemand: true,
expand: onExpandedItem
});
});
function onExpandedItem(e) {
var id_user = #Model.id;
var item = $('#Tree_view').data('kendoTreeView').dataItem(e.node);
var treeview = $('#Tree_view').data('kendoTreeView');
var type = item.fields.type;
if (item.level() > 0) {
item.id_parcours = item.parentNode().id_parcours;
if (item.level() == 2) {
item.id_promo = item.parentNode().id;
}
}
else item.id_parcours = item.Id;
switch (type) {
case 'parcours':
item.children.transport.options.read = {
url: '#Url.Action("Get_Session", "Users")' + '?user_id=' + id_user,
dataType: "json",
};
break;
case 'session':
item.children.transport.options.read = {
url: '#Url.Action("Get_Matiere")' + '?user_id=' + id_user,
dataType: "json"
};
break;
default:
break;
}
if (item.level() == 0) {
setTimeout(function() { waitDisable(item, treeview); }, 1000);
}
}
function waitDisable(item, treeview) {
if (item.fields.type == "parcours")
{
var node = Tree_view.getElementsByClassName('k-group')[0].children[item.id_perso - 1].children[1].children;
for (i = 0; i < item.children._data.length; i ++)
{
if (item.children._data[i].state != null) {
node[i].children[0].children[1].className = "k-in k-state-disabled";
node[i].children[0].children[0].className = ".k-icon-remove";
}
else node[i].children[0].children[0].className = "k-icon k-plus";
addRow(node, item, i, treeview);
}
}
}
var cmp = 0;
var One_Time = false;
function addRow(node_Here, item, i, treeview) {
var actual_row = node_Here[i].children[0];
if (actual_row.childNodes.length < 3) {
var newSpan = document.createElement('button');
if (item.children._data[i]._childrenOptions.data.state != null) {
newSpan.appendChild(document.createTextNode("Re-Up"));
newSpan.className = "change_state btn btn-success btn-xs";
}
else {
newSpan.appendChild(document.createTextNode("Down"));
newSpan.className = "change_state btn btn-danger btn-xs";
}
actual_row.appendChild(newSpan);
}
cmp += 1;
if (cmp == item.children._data.length)
One_Time = true;
if (One_Time) {
addClickListner(item, i, treeview);
One_Time = false;
cmp = 0;
}
}
function addClickListner(item, i, treeview) {
$(".change_state").click(function (event) {
var name_Promo_Rm = event.target.parentNode.children[1].textContent;
var User_Select = event.view.Parcours.transport.read.data.user_id;
$.ajax({
url: '#Url.Action("ChangeStatutBase", "Users")',
type: 'GET',
dataType: 'json',
data: { Name_Promo: name_Promo_Rm, User_id: User_Select },
});
refreshTree(treeview);
})
}
// Refresh tree
function refreshTree(treeview) {
// Save open items
saveExpandedItems(treeview);
// Reload data source
treeview.dataSource.read();
// Load open items
console.log("OKKKKKKK");
setTimeout(loadExpandedItems(), 600);
}
I've resolved my problem, in the "setTimeout" in the bottom I've placed "()" in the first parameter and it doesn't put the pause and data don't have the time to be loaded.

Categories