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;
}
});
Related
$('#lev_nr').on('input', {
source: function(request, response) {
$.ajax({
url : 'pallavvikelse/jsonData',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'lev_table',
row_num : 1
},
success: function(data) {
response($.map(data, function(item) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function(event, ui) {
var names = ui.item.data.split("|");
$('#lev_namn').val(names[1]);
var txt = $('#avta').val(names[2]);
if (txt.val() == "ja"){
$('#t').hide();
}
} }).trigger('input');
Can someone see why this does not work?
I am trying to change autocomplete function to on.input but I can't get it to work.
The code works perfectly when i change the first line to $('#leverantors_nr').autocomplete({
and when I remove .trigger('input')
$('#lev_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data);
var names = data.split('|');
alert(names[0]);
}
});
});
I have managed to make it work this far, but when i try to alert(names[0]) i get nothing when alert(data) i get resault.. The data i get loocks like this: 5000950|TEST|BLABLA
Wen i try to split and alert again it dosent work
$('#leverantors_nr').on('input', function() {
$.ajax({
url: 'pallavvikelse/jsonData',
data: {
name_startsWith: this.value,
type: 'country_table',
row_num: 1
},
dataType: 'json',
success: function(data) {
alert(data.lev_namn);
}
});
});
Problem solved:
i changed the database so it outputs array like this:
$arr['lev_nr'] = $row->lev_nr;
$arr['lev_namn'] = $row->lev_namn;
I think you are not properly parsing JSON data.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
So I am working with dropzone, and everything uploads fine, but now I am to the part of adding the image paths to a database. What I am having a problem with is I first want to submit a form with ajax, after that successfully completes I would like to pass the newly created ID on the database into the sending option of dropzone. Everything works separately, but I can not figure out how to get the new ID into the sending option of dropzone. Here are my 2 pieces of code that are relevant.
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#dropzonePreview", {
url: "list/post-image",
parallelUploads: 6,
autoProcessQueue: false,
processing: function(){
this.options.autoProcessQueue = true;
},
sending: function(file, xhr, formData) {
formData.append("_token", $('[name=_token]').val());
}
});
and here is the ajax call. I thought I would try the myDropzone.options.sending, but I can figure out how to attach the formData like in the above code.
var form = $('form', wizard).serialize();
$.ajax({
type: "POST",
url: 'list',
data: form,
success: function(data) {
if (data.success)
{
myDropzone.options.sending(null, null, formData)
{
formData.append("propertyID", $('[name=propertyID]').val(data.propertyID));
}
}
}
});
hopefully it is just something small that I am missing. Thanks for your help in advance.
I just did some tinkering around, and some google searching and I found the answer. Instead of using the sending option, there is an option for params which makes a hidden field. Here is my ajax piece of code that got it working.
$.ajax({
type: "POST",
url: 'list',
data: form,
success: function(data) {
if (data.success)
{
myDropzone.options.params = {'propertyID': data.propertyID};
}
myDropzone.processQueue();
}
});
You have to put ur dropzone proceess queue out of the ajax succeess: like this:
Dropzone.options.dropzoneJsForm = {
autoProcessQueue: false,
acceptedFiles: ".png,.jpg,.gif,.bmp,.jpeg,.pdf,.rar,.zip",
maxFilesize: 2,
maxFiles: 5,
addRemoveLinks: true,
init: function () {
var submitButton = document.querySelector("#btnReg");
myDropzone = this; //closure
submitButton.addEventListener("click", function () {
var coursenameID = $('#coursenameID').val();
var coursetypecodeID = $('#courseTypeCodeID').val();
var hdcourseexecuterID = $('#hdCourseExecuterID').val();
//var coursecreationDateID = $('#courseCreationDateID').val();
var selectedpersons = [];
$("#doublerow input:checked").each(function () { selectedpersons.push($(this).val()) });
$.ajax({
url: '#Url.Action("InsertToDB", "Course")',
type: "POST",
dataType: "json",
traditional: true,
data: { "coursenameID": coursenameID, "coursetypecodeID": coursetypecodeID, "hdcourseexecuterID": hdcourseexecuterID, "selectedpersons": selectedpersons },
beforeSend: function () {
$('#savingdata').addClass('show');
},
success: function (Response) {
console.log(Response);
if (Response > 0) {
courseid = Response;
console.log(Response);
$('#savingdata').addClass('hide');
}
}
});
myDropzone.options.params = { 'propertyID': courseid };
myDropzone.processQueue();
});
}
};
I am building a very large pdf book using PHP, I am using ajax to trigger the script. My issue is that because it so big it was timing out, so I decided to break it and recursively call the script several times. I tested this a few weeks back and it was fine. However now I am getting random "504 gateway timeout" issues with some of the ajax calls.
Im not sure where to even begin debugging this as I believed the entire purpose of doing several ajax calls was to prevent this issue. Unfortunately I dont have access to the server as its on a shared hosting package.
<?php $i =1; for($i;$i<=$number_of_pages;$i++) { ?>
<?php if ($i == $number_of_pages) { $last = 1; } else { $last = 0; } ?>
<script>
$(document).ready(function() {
jQuery('.waiting-gif').show();
var number_of_pages = '<?php echo $number_of_pages; ?>';
var build_progress_width = 480/number_of_pages;
var last = '<?php echo $last; ?>';
$.ajax({
url: 'index.php?route=pdfengine/pdfengine/trigger_pdf_gen',
type: 'post',
dataType: 'json',
data: {
pdf_id : '<?php echo $this->request->get['pdf_id']; ?>',
page_number: '<?php echo $i; ?>',
},
beforeSend: function() {
},
complete: function() {},
success: function(json) {
$('.build-progress-green').css('width', build_progress_width);
$('.pdf-build-progress').append('<div class="build-progress-green"></div>');
if (last == '1') {
$.ajax({
url: 'index.php?route=pdfengine/pdfengine/merge_pdfs',
type: 'post',
dataType: 'json',
data: {
pdf_id : '<?php echo $this->request->get['pdf_id']; ?>',
},
beforeSend: function() {},
complete: function() {},
success: function(json) {
var link = document.getElementById('downloadlink');
// Set the link to the json response
link.href = json['download_link'];
$('#downloadlink').attr('download','reads-pdf-id-' + json['pdf_id'] + '.pdf');
// Unhide the link
link.style.display = 'block';
$('#downloadlink').trigger('click');
$('.waiting-gif').hide();
}
});
}
}
});
});
</script>
<?php } ?>
The main function being called via ajax...
public function trigger_pdf_gen() {
if(isset($this->request->post['pdf_id'])) {
$this->load->model('pdfengine/pdfengine');
$pdf_info = $this->model_pdfengine_pdfengine->getPdfInfo($this->request->post['pdf_id']);
$page_number = $this->request->post['page_number'];
$this->session->data['childs_name'] = $pdf_info[0]['childs_name'];
$this->session->data['pdf_id'] = $pdf_info[0]['pdf_id'];
$this->session->data['gift_message'] = $pdf_info[0]['gift_message'];
$double_pages = explode(',',$this->model_pdfengine_pdfengine->getDoublePages($pdf_info[0]['book_path']));
$is_double_page = 0;
foreach ($double_pages as $double_page) {
if ($double_page == $page_number) { $is_double_page = 1; }
}
$this->generate_final_pdf($pdf_info[0]['pdf_id'],$pdf_info[0]['book_path'],$pdf_info[0]['childs_gender'], $page_number,$is_double_page );
$json = array();
$json[] = "<a href='".DIR_FINAL_PDFS_PUBLIC.$pdf_info[0]['pdf_id']."/final-build-".$pdf_info[0]['pdf_id'].".pdf'>The file :)</a>";
$this->response->setOutput(json_encode($json));
}
}
Is it possible this could be a temporary server related issue?
I found a workaround, I wouldnt call it a solution exactly but it does the job.
I scrapped the for loop and forced each trigger of ajax request on a time delay using javascript.
var counter = 1;
trigger_pdf();
var i = setInterval( trigger_pdf, 61000);
function trigger_pdf() {
$.ajax({
url: 'index.php?route=pdfengine/pdfengine/trigger_pdf_gen',
type: 'post',
dataType: 'json',
data: {
pdf_id : '<?php echo $this->request->get['pdf_id']; ?>',
page_number: counter,
},
beforeSend: function() {
},
complete: function() {},
error: function() {
alert('Build failed and timed out, please contact ####');
},
success: function(json) {
$('.build-progress-green').css('width', build_progress_width);
$('.pdf-build-progress').append('<div class="build-progress-green"></div>');
}
});
if(counter == number_of_pages) {
clearInterval(i);
$.ajax({
url: 'index.php?route=pdfengine/pdfengine/merge_pdfs',
type: 'post',
dataType: 'json',
data: {
pdf_id : '<?php echo $this->request->get['pdf_id']; ?>',
},
beforeSend: function() {},
complete: function() {},
success: function(json) {
var link = document.getElementById('downloadlink');
// Set the link to the json response
link.href = json['download_link'];
$('#downloadlink').attr('download','reads-pdf-id-' + json['pdf_id'] + '.pdf');
// Unhide the link
link.style.display = 'block';
$('#downloadlink').trigger('click');
$('.waiting-gif').hide();
}
});
}
counter++;
}
I want to request ajax many time in for loop . But it only return 1 value . result.ID. Can anyone help me?
$('#show').html('');
var min = parseInt($('#number_coupon_from').val());
var max = parseInt($('#number_coupon_to').val());
var total_time = parseInt($('#time_coupon').val())*1000;
var randcoupon = Math.floor(Math.random()*(max-min+1)+min);
var timetb = total_time/randcoupon;
var random = 0;
var i,j;
for(i=0;i<randcoupon;i++)
{
for(j=random;j>=0;j--)
{
if(j==0)
{
$.ajax({
url: 'backend/publish_auto/update',
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});
}
}
}
});
Thank you !!
use async:False to get ajax response one by one
$.ajax({
url: 'backend/publish_auto/update',
async: false,
type: 'post',
data: {},
dataType: 'json',
success: function (result)
{
if(result.st)
{
$('#show').append('Update Coupon ID: '+result.ID+'<br />');
}
}
});
$counter = $sWall + $sWC + $sOther;
if (!empty($counter)) {
echo '(' . $counter . ')';
$counter = 0;
}
And js:
$(window).blur(function() {
tracktime = new Date();
setInterval(function() {
$.ajax({
type: "POST",
url: "imback.php",
data: {
mode: 'ajax',
getUpdates: 'auto',
},
success: function(msg){
document.title = msg + document.title;
}
});
}, 2000);
})
For showing new unread comments in the title bar. Works fine and displays it as (1), although everytime it call, it adds a (1) so the title gets like this: (1)(1)(1)(1)(1)(1)(1)(1).......
And i only want it to do it once (1) no matter how many calls, so if a new call is response is (2) then it will show (2) and not (2)(1)(1)....
How can i fix this the best way?
When the page is loaded, save the original title to a variable, then when you need to update it, use the saved value.
(function () {
var initial_title = document.title;
$(window).blur(function() {
tracktime = new Date();
setInterval(function() {
$.ajax({
type: "POST",
url: "imback.php",
data: {
mode: 'ajax',
getUpdates: 'auto',
},
success: function(msg){
document.title = msg + initial_title;
}
});
}, 2000);
});
$(window).focus(function () { document.title = initial_title; });
})();
You'll have to store the original title in a variable and then prepend the msg variable to that title variable.
var titleOrig = document.title;
$(window).blur(function() {
tracktime = new Date();
setInterval(function() {
$.ajax({
type: "POST",
url: "imback.php",
data: {
mode: 'ajax',
getUpdates: 'auto',
},
success: function(msg){
document.title = msg + titleOrig;
}
});
}, 2000);
})
You should wrap this in an init function somewhere, but it's the general idea.