Message (alert) asking for confirmation - php

I'm beginner in JS.
I have this code:
var fileLimit = parseInt(1);
function refreshFileList() {
$(".dz-preview").remove();
$.ajax({
url: 'http://test/admin/showFilesDJS?type=SplashImage&id=1',
type: 'get',
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
success: function (response) {
$.each(response, function (key, value) {
var mockFile = {
name: value.name,
size: value.size
};
dpzMultipleFiles.emit('addedfile', mockFile);
dpzMultipleFiles.emit('thumbnail', mockFile, value.path);
dpzMultipleFiles.emit('complete', mockFile)
})
},
error: function (response) {
alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
}
});
}
Dropzone.options.dpzMultipleFiles =
{
maxFiles: fileLimit,
clickable: true,
thumbnailWidth: 250,
thumbnailHeight: 250,
autoProcessQueue: true,
dictDefaultMessage: '',
uploadMultiple: true,
paramName: "myFile",
acceptedFiles: ".jpg,.jpeg",
addRemoveLinks: true,
timeout: 50000,
dictRemoveFile: 'Usuń plik',
init: function () {
dpzMultipleFiles = this;
refreshFileList();
this.on("thumbnail", function (file, dataUrl) {
$('.dz-image').last().find('img').attr({width: '100%', height: '100%'});
}),
this.on('completemultiple', function (file, json) {
//$('.sortable').sortable('enable');
});
this.on('success', function (file, json) {
//alert('aa');
});
this.on('addedfile', function (file) {
fileLimit = fileLimit - 1;
});
this.on('drop', function (file) {
fileLimit = fileLimit + 1;
});
this.on("maxfilesexceeded", function (file) {
alert('Plik ' + file.name + ' nie został wysłany na serwer. Limit plików został przekroczony!')
this.removeFile(file);
});
},
removedfile: function (file) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
type: 'POST',
url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
data: {filename: file.name, id: file.name, type: 'SplashImage'},
success: function (data) {
console.log("File has been successfully removed!!");
//refreshFileList();
},
error: function (e) {
console.log(e);
}
});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
}
};
$(function () {
$(".dropzone").sortable({
items: '.dz-preview',
cursor: 'move',
opacity: 0.5,
containment: '.dropzone',
distance: 20,
tolerance: 'pointer',
update: function (event, ui) {
$(".dz-filename span").each(function (index) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
url: 'http://test/admin/changeOrderFilesDJS?type=SplashImage&id=1&index='+index+'&file='+ $(this).text(),
dataType: 'text',
type: 'post',
cache: false,
data: $(this).serialize(),
success: function (data, textStatus, jQxhr) {
},
error: function (jqXhr, textStatus, errorThrown) {
alert('Nastąpił problem z JSON. Proszę o kontakt z administratorem serwisu.');
}
});
});
}
});
});
This is Dropzone.JS. This code work fine.
I would like to add after clicking on the button remove (usuń plik) - the question: do you really want to delete this file? Only after clicking on YES the file would be deleted.
How to do it? I need a simple alert with a question in JS

You can add confirm in the remove function :
removedfile: function (file) {
if (!confirm('Are you sure?')) {
return;
}
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
},
cache: false,
type: 'POST',
url: 'http://test/admin/deleteDJS?id=' + file.name + 'type=SplashImage',
data: {filename: file.name, id: file.name, type: 'SplashImage'},
success: function (data) {
console.log("File has been successfully removed!!");
//refreshFileList();
},
error: function (e) {
console.log(e);
}
});
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : void 0;
}

I think what you are looking for is a confirm().
if (confirm('Are you sure?')) {
console.log('confirmed');
} else {
console.log('declined');
}

You can use bootstrap modal for the confirmation that you want to ask.
the link is here

Related

Fullcalendar Event Add/Edit and Resize.and get sucesscallback without page reload/refresh

When i add new event or update event or change event or drag new time or new user then every time page refreshes. but how to solve this issue for without reloading page and display updated event time or remove event. i'm using calendar version 5 for fullcalendar.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
now: '<?php echo $CurrentDate; ?>',
editable: true,
aspectRatio: 1.8,
scrollTime: '00:00',
timeFormat: 'H(:mm)',
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,timeGridWeek,dayGridMonth'
},
resources: <?php eventGroups(); ?>,
events: function(info, successCallback, failureCallback) {
successCallback(<?php eventGroupsDetails($fromDate,$toDate); ?>)
},
dateClick: function(info) {
$('#addScheduleEntry').modal('show');
$(document).on('click', '.modal_default_ok', function() {
$.ajax({
url: "calendar_event_create.php",
type: "POST",
data: $("#frmEvent").serialize(),
dataType: 'json',
success: function(response){
if(response.result == 'success'){
// how to get updated event and display in calender without page refresh
}
}
});
});
},
eventClick: function(info, jsEvent, view) {
$.ajax({
url: "calendar_event_update.php",
type: "POST",
data: $("#frmEventUpdate").serialize(),
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
},
editable: true,
eventDrop: function(info, delta, revertFunc, ui) {
$.ajax({
url: "save_drop_event_detail.php",
type: "POST",
data: {EventId:EventId},
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
},
eventResize: function(info) {
$.ajax({
url: "save_resize_event_detail.php",
type: "POST",
data: {EventId:EventId},
dataType: 'json',
success: function(response){
// how to get updated event and display in calender without page refresh
}
});
}
});
calendar.render();
});
</script>
<div class="row">
<div id="msg"></div>
<div class="col-md-12">
<div id='calendar'></div>
</div>
</div>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
now: '<?php echo $CurrentDate; ?>',
editable: true,
aspectRatio: 1.8,
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,timeGridWeek,dayGridMonth'
},
views: {
timeGridWeek: {
type: 'timeGrid',
duration: { weeks: <?php if($searchWeek=="") { echo 1; } else{echo $searchWeek;} ?> }
}
},
resources: <?php eventGroups(); ?>,
events: function(fetchInfo, successCallback, failureCallback) {
var fromDate = "<?php echo $fromDate; ?>";
var toDate = "<?php echo $toDate; ?>";
$.ajax({
url: "ajaxRefresh.php",
type: "POST",
dataType: "json",
success: function(response){
var events = [];
$.each(response, function (i, item) {
events.push({
id: response[i].id,
start: response[i].start,
end: response[i].end,
title: response[i].title,
});
});
successCallback(events);
}
});
},
dateClick: function(info) {
$('#addScheduleEntry').modal('show');
$.ajax({
url: "calendar_event_create.php",
type: "POST",
data: $("#frmEvent").serialize(),
dataType: 'json',
async : false,
success: function(response){
if(response.result == 'success'){
calendar.refetchEvents();
}
}
});
},
eventClick: function(info, jsEvent, view) {
var text = JSON.stringify(info, function (key, value) {
var eventId = info.event._def.publicId;
$("#eventDetail").modal("show");
$(document).on('click', '.removeEvent', function() {
var eventId = $("#event_id").val();
var yes = confirm("Are you sure ?");
if(yes == true){
$("#process_loader").fadeIn();
$.ajax({
url: "calendar_event_remove.php",
type: "POST",
data: {eventId:eventId},
dataType: 'json',
async : false,
success: function(response){
if(response.msg == "true"){
calendar.refetchEvents();
}
}
});
}
});
},
editable: true,
eventDrop: function(info, delta, revertFunc, ui) {
$.ajax({
url: "save_drop_event_detail.php",
type: "POST",
data: {EventId:EventId,oldUserId:oldUserId,newUserId:newUserId,newEventStartTime:newEventStartTime,newEventEndTime:newEventEndTime},
dataType: 'json',
async : false,
success: function(response){
if(response.msg == 'success'){
calendar.refetchEvents();
}
}
});
},
eventConstraint: {
slotMinTime: '10:00' ,
slotMaxTime: '11:00'
}
});
calendar.render();
});
</script>
We used this function "calendar.refetchEvents();" and used an AJAX data source for your events, instead of a static one.

before submit and uploadProgress doesnt work in ajax jquery

can any one help me in this problem and i try many ways but beforeSubmit and uploadProgrss doesnt work
$.ajax({
url:"include/ajaxPages/admin/insertNewItem.php",
type:"POST",
data:new FormData(this),
processData:false,
contentType:false,
beforeSubmit:function(){
$(this).find(".progress").width("0%");
},
uploadProgress:function(event,position,total,complete){
$(this).find(".progress").animate({
width: complete+"%"
},{
duration:1000
})
},
success:function(data){
console.log(data);
alert("تم الاضافه بنجاح");
$(".loadingViedo").fadeOut();
window.location = document.URL;
}
})
Try this:
var fd = new FormData();
fd.append('rName', $('#upload-resource .upload').attr('data-name'));
fd.append('rfile', $('#upload-resource .upload').attr('data-file'));
$.ajax({
url: 'include/ajaxPages/admin/insertNewItem.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
xhr: function () { // custom xhr
myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // if upload property exists
myXhr.upload.addEventListener('progress', function (e) {
var done = e.position || e.loaded
var total = e.totalSize || e.total;
var percent = Math.round(done / total * 100);
//console.log('xhr progress: ' + percent + '%');
$(this).find(".progress").animate({
width: percent +"%"
},{
duration:1000
});
}, false);
myXhr.addEventListener('load', function (e) {
//upload done
});
$('#upload-resource .cancel').show().click(function () {
//cancel upload
myXhr.abort();
});
}
return myXhr;
},
success: function (data) {
//to do for success result
}
});

form validation in ajax before submitting form through ajax

Im using ajax to submit a form and inserting the values to the database..I tried many ways but validation error check doesnt come out right.
here is my code
$(document).ready(function() {
$('body').on('click', '#Submit', function(e) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'formrelay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
});
I tried using submithandler (saw in one of the tutorial) but it did not work..pls help..code below
$(document).ready(function(){
$("#relay_form").validate({
rules: {
f_name: { required : true }
},
submitHandler : function (form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url:'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
document.getElementById('Message').innerHTML=data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
This worked for me..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<!-- red color for error message -->
<style type="text/css">
#hardship_form .error {
color: red
}
</style>
<script>
$(document).ready(function() {
$("#relay_form").validate({
rules: {
f_name: {
required: true
}
},
messages: {
f_name: "Please Enter first name"
},
submitHandler: function(form) {
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'form_relay.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function(data) {
document.getElementById('Message').innerHTML = data;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
}
});
});
</script>
Thanks Milan

Display error message when ajax result return null value

I would like to ask how to display error message when null value and 0 value in the ajax result from SQL
{"value":
{"columns": [["More than 85%",null],["Less than 85%",0]],
"type":"pie"}
}
else no pop out message shown.
$.ajax({
type: "POST",
url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
dataType: "json",
success: function (result) {
var chart = c3.generate({
bindto: '#piepie',
data: result.value,
color: {
pattern: ['#f35213', '#f1af4c']
},
pie: { title: "Productivity", }
});
},
error: function() {
if ((result == null) && (result == 0)){
alert ('Data are not ready yet!!');
}
else {
('error');
}
}
});
The variable result doesn't exist in the error: function. You need to do that test in the success: function.
The null and 0 values are deep in the structure, you need to access them properly.
$.ajax({
type: "POST",
url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
dataType: "json",
success: function (result) {
if (result.value.columns[0][1] == null && result.value.columns[1][1] == 0) {
alert ('Data are not ready yet!!');
} else {
var chart = c3.generate({
bindto: '#piepie',
data: result.value,
color: {
pattern: ['#f35213', '#f1af4c']
},
pie: { title: "Productivity", }
});
}
},
error: function() {
alert('error');
}
});
Try this,
$.ajax({
type: "POST",
url: "charts/prod.php?year=" + $("#selectyear").val() + "&month=" + $("#selectmonth").val(),
dataType: "json",
success: function (result) {
if ((result == null) && (result == 0)){
alert ('Data are not ready yet!!');
}else {
var chart = c3.generate({
bindto: '#piepie',
data: result.value,
color: {
pattern: ['#f35213', '#f1af4c'] },
pie: { title: "Productivity", }
});
}
},
error: function() {
alert('error');
}
});

jQuery GET request in loop

I have a script that works like this:
when you go to url
localhost/geocinema/index.php?movie=606
it will download the movie number 606 on my server with this script:
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
}
});
where the "link" is the php file that handles the download.
now I need to download movies from 1 to 600, so I need to somehow to loop through all that URL-s.
I tried sending get requests from another file, like this:
$.ajax({
url: 'http://localhost/geocinema/index.php?movie={1-600}',
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
but since I use the get request in index.php also it doesn't work (it doesn't wait until the file is downloaded).
So the only way I can download all files is if I manually enter the URL-s from 1 to 600 in the browser and wait for the download, which is not very convenient.
Any help will be appreciated, thanks.
You might want to create a queue of ajax requests, so each waits until the previous is finished. If you just initiate all ajax request in a for loop, then all of them will fire at the same time. In case we are uploading 600 videos it is going to be a very hard load. So one solution is to use for loop with ajax async flag: false.
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
async: false,
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Another is do define a function which recursively calls itself when finished uploading.
var currentMovie = 0;
var lastMovie = 600;
function getMovie() {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie='+currentMovie,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
currentMovie++;
if (currentMoview<=lastMovie) {
getMovie();
}
},
success: function(result) {
console.log("Download Success ");
}
});
}
getMovie();
Use a for loop:
for (var i = 1; i <= 600; i++) {
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
}
});
}
Do something like this, it will call the same function after completing the previous call
var i = 1;
function ajaxCall(){
$.ajax({
url: 'http://localhost/geocinema/index.php?movie=' + i,
type: 'GET',
beforeSend: function() {
console.log("Downloading ");
},
complete: function() {
},
success: function(result) {
console.log("Download Success ");
if(i++ <= 600){ ajaxCall(); }
}
})
}
ajaxCall();
I solved it like this:
var url = window.location.href;
var ind = url.indexOf("=")+1;
var res = url.substr(ind)
res = parseInt(res);
res = res+1;
var nxurl = "http://localhost/geocinema/index.php?movie="+res;
$.ajax({
url: link,
type: 'GET',
beforeSend: function() {
console.log("Downloading "+title);
},
complete: function() {
},
success: function(result) {
console.log("Download Success for "+title);
window.location = nxurl;
}
});

Categories