multiple ajax requests giving 504 gateway timeouts - php

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++;
}

Related

Json encode error in codeigniter

I tried to load a view in my codeigniter controller and also i pass a status to my ajax function. In the ajax function i wrote a sweetalert popup in the sucess function when my status is 1. now my actual problem is when i load a view in the controller the status is not passing to my ajax function.can anyone figureout what the problem is any help is appreciable.
controller
$query = $this->package_view_model->enquiry_history();
if (isset($query))
{
$status = 1;
$this->load->view('packages/enquiry');
}
echo json_encode (array("status"=>$status));
ajax function
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url() ?>tour-package/send-mail',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}
Hope this will help you :
$query = $this->package_view_model->enquiry_history();
$status = 1;
if (! empty($query))
{
$this->load->view('packages/enquiry');
}
echo json_encode(array("status" => $status));
exit;
I think there is a problem with the ending slash in the baseurl. So, change the way you're generating the url.
function sendMail(package_url)
{
var formData = $("#enqform").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("tour-package/send-mail") ?>',
data: formData,
dataType: 'json',
success: function(data){
if(data.status == 1){
swal({
title:'Thankyou for your interest!!!',
text: "Our excecutives will contact you soon.",
html: true,
type: "success",
showCancelButton: false,
showConfirmButton:false
});
window.setTimeout(function() {
window.location.href = '<?php echo base_url() ?>tour-packages';
}, 1000000);
}
}
});
return false;
e.preventDefault();
}

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;
}
});

Call Ajax Again in for loop

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 />');
}
}
});

Longpolling : Sending extra variable

I am doing a simple longpolling using jquery and php.. It's going on great.. but when I am sending and extra variable.. then the longpolling is not showing the current value that it's supposed to show... My code is below..
The one which is working :
function getContent(time)
{
var queryString = {'time': time};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
The one which is working on page refresh.. but longpolling is not happening...
function getContent(time)
{
var name = '<?php echo $name; ?>';
var queryString = {'time': time, 'name':name};
$.ajax(
{
type: 'GET',
url: 'test.php',
data: queryString,
success: function(data){
var obj = jQuery.parseJSON(data);
$('#response').html(obj.data_from_file);
getContent(obj.time);
},
error : function(){
getContent(time);
}
}
);
}
$(document).ready(function(){
getContent();
});
PHP side...
while (true) {
$last_ajax_call = isset($_GET['time']) ? (int)$_GET['time'] : null;
$name = $_GET['name'];
//rest of the code...............
}
else{
sleep(1);
continue;
}

PHP/Javascript: Making (1) in title as unread

$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.

Categories