Error in AJAX code causing broswer to crash - javascript

Hello I have written an ajax script that grabs different pages and displays them for X amount of time and then switches to the next page. I use the setTimeout function to display the pages for the X amount of time. In order to grab each page I created a list of different pages in a database that my code looks at then calls the appropriate php function to grab the data.
What seems to be happening is that it causes firefox to crash after a couple of days because firefox seems to run out of memory. My guess is that my code is not efficient but, I am not sure how I can make it more efficient so it does not crash the browser. Any help would be greatly appreciated. Here is my code:
<?php $this->load->view('includes/header'); ?>
<div id="result">
</div>
<?php $this->load->view('includes/footer');?>
<?php $displayName = $this->input->get('name');?>
<script type="text/javascript">
var views = [];
var cell = '';
var i = 0;
var display = <?php echo json_encode($displayName); ?>;
var timeOut = 0;
$(function get_data() {
$.ajax({
url: "get_display_data/"+display,
type: "post",
cache: false,
success: function(data){
views = JSON.parse(data);
if (i >= views.display.length) {
i = 0;
} else if (views.display[i].view == 'Fabrication') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/FabricationStatus/"+views.display[i].view + "/"+ "display1?name="+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else if(views.display[i].view == 'CYLPLNGLCMSH') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/CYLPLNGLCMSHStatus/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else if(views.display[i].view == 'COTCTR') {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/COTCTRStatus/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+"#mainContent");
timeOut = 60;
i++;
} else {
var loadUrl = "<?php echo base_url();?>/index.php/Cells/Display/"+views.display[i].view + "/"+display;
$("#result").empty().load(loadUrl+".mainContent");
timeOut = 30;
i++;
}
setTimeout(get_data, (1000 * timeOut));
}
});
});

Related

Auto Load More on scroll down is loading only first 2 pages

I have auto load more on page scroll down.
My jQuery/ajax is working but it is auto loading only first 2 pages on scroll down. There are more pages/records but it stuck after 2nd page loads.
I cannot understand the issue.
Somebody please help me out. My php and java code is given below
just played around with the same moving lines up and down but no use.
<?php
$pxe = $_GET['pname'];
$sxe = $_GET['sname'];
?>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
getresult.php
<?php
include('inc/db.php');
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($sql);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql." limit ".$start.",".$perPage;
$faq = $dba3->query($query);
if(empty($_GET["rowcount"])) {
$_GET["rowcount"] = mysqli_num_rows($faq);
}
$output = '';
if(!empty($faq)) {
$output .= '<input hidden class="pagenum" value="'.$page.'" />';
$output .= '<input hidden class="total-page" value="'.$pages.'" />';
while ($row = $faq->fetch_assoc()) {
$output .= $row["ename"];
} }
print $output;
?>
no errors just loader image keeps moving
The key is to get the row count from the initial sql, before applying the limit, something like:
$perPage = 10;
$sql = "SELECT * from posts";
$allrows = $dba3->query($query);
$allrowscount = mysqli_num_rows($allrows);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start < 0) $start = 0;
$query = $sql . " limit " . $start . "," . $perPage;
$faq = $dba3->query($query);
You should add async : false, in your ajax request.
url: url,
async : false,
type: "GET",
data: {rowcount:$("#rowcount").val()},
Your browser needs to wait for the response before the next request is sent.

How to show the errors through ajax and Jquery in codeigniter

This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }

Who to append php on chnage with Jquery Ajax

I am trying to append php script to the dom in a div that has the class .new-session but it doesn't work how it should.
Here is my code
$('select[name=quantity]').change(function() {
quantity = $(this).val();
if (quantity == 20) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 20; ?>';
}
elseif(quantity == 30) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 30; ?>';
}
elseif(quantity == 40) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 40; ?>';
}
elseif(quantity == 50) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 50; ?>';
}
elseif(quantity == 60) {
newSession = '<?php echo $_SESSION[\'product\'][\'quantity\'] = 60; ?>';
}
$.ajax({
url: "/multisite/",
dataType: "html",
success: function(newSession) {
$('.set-session').append(newSession);
}
})
});
<div class="set-session">
</div>
You can't append PHP to the DOM, PHP code is run on the server when the page is being created. You use AJAX to run server code in response to a user action, and the script that receives the AJAX call updates the session.
Here's how you can do what you want:
$('select[name=quantity]').change(function() {
var quantity = $(this).val();
$.ajax({
url: "/multisite/setquantity.php",
data: { quantity: quantity }
});
});
The PHP in setquantyt.php should be like:
<?php
session_start();
$_SESSION['product']['quantity'] = intval($_GET['quantity']);

jQuery synchronous asynchronous requests in order

I have tasks that I want to do synchronously; but I don't want to freeze the browser. There could be 1---N tasks.
Below is the synchronous version. It works as expected but freezes the browser.
How can I do this using jQuery deferred object to do these task in order but not lock browser.
NOTE: The server I am request to does NOT allow for 2 requests at once. They need to run one after the other once the request is finished in exact order.
<?php
for ($k = 0;$k<count($partial_transactions);$k++)
{
?>
$("#formCheckout_<?php echo $k; ?>").ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
},
cache: true,
headers: false,
async: false
});
<?php
}
?>
Try this:
var counter = 0;
// Build up an array of all forms that are to be submitted sequentially.
var forms = [
<?php
for ($k = 0;$k<count($partial_transactions);$k++){
if($k == 0){
echo "#formCheckout_{$k}";
}else{
echo ", #formCheckout_{$k}";
}
}
?>
];
// Start the request
make_next_request(forms[counter]);
function make_next_request(form){
form.ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
// Now chain request onto next form.
if(counter < forms.length){
counter++;
make_next_request(forms[counter]);
}
},
cache: true,
headers: false,
async: false
});
}
You could just put it all in a web worker that handles all the data, so the UI thread doesn't get interrupted (but you'll have to give the user some indication that the data is loading.)
See the web worker API for more info, but basically, web workers are native browser objects that allow you to have multi-threaded operations. In other words, your operations can run in the background while the user still interacts with the web page, and then when the operations are complete, they can notify the UI thread (the thread the user is currently on.)
This CPU-intensive data loading that you're talking about seems like a perfect use case for such an API.
I ended up doing it like this. The intensive part is server side. So I took some suggestions and came up with this. (Using recursion)
<script>
var num_transactions_to_void = <?php echo count($partial_transactions); ?>;
var max_index = num_transactions_to_void - 1;
if (num_transactions_to_void > 0)
{
void_sale_request(0);
}
function void_sale_request(index)
{
if (index > max_index)
{
return;
}
$("#formCheckout_"+index).ajaxSubmit({
success:function(response)
{
var data = response.split("&");
var processed_data = [];
for(var i = 0; i < data.length; i++)
{
var m = data[i].split("=");
processed_data[m[0]] = m[1];
}
$("#please_wait").hide();
if (processed_data.CmdStatus != 'Approved')
{
var message = decodeURIComponent(message);
message = processed_data.TextResponse.replace(/\+/g, ' ');
toastr['error'](<?php echo json_encode(lang('sales_attempted_to_reverse_partial_transactions_failed_please_contact_support'));?>, <?php echo json_encode(lang('common_error')); ?>);
}
else
{
toastr['success'](<?php echo json_encode(lang('sales_partial_credit_card_transactions_voided')); ?>, <?php echo json_encode(lang('common_success')); ?>);
}
void_sale_request(index + 1);
},
cache: true,
headers: false
});
}
</script>

Trying to convert jQuery to prototype... jQuery causing issues

I have the following code:
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>
var last_song = '$song[1]';
var jqy = jQuery.noConflict()
var change_radio = setInterval(function ()
{
jqy.ajax({
url : 'modules/ajax/refresh.php',
type : 'GET',
data : {lastsong: 'last_song'},
success: function(data)
{
last_song = data;
jqy('#radio').html(last_song);
}
});
}, ($refresh*1000));
change_radio;
</script>
refresh.php
<?php
$lastsong = $_GET['lastsong'];
$timeout = "2"; // Number of seconds before connecton times out.
$ip[1] = "198.101.13.110"; // IP address of shoutcast server
$port[1] = "8000"; // Port of shoutcast server
//$song = [];
//$msg = [];
//END CONFIGURATION
$servers = count($ip);
$i = "1";
while ($i <= $servers)
{
$fp = #fsockopen($ip[$i], $port[$i], $errno, $errstr, $timeout);
if (!$fp)
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [Connection refused / Server down]</span>";
$error[$i] = "1";
}
else
{
fputs($fp, "GET /7.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) $info = fgets($fp);
$info = str_replace('<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>', "", $info);
$info = str_replace('</body></html>', "", $info);
$stats = explode(',', $info);
if (empty($stats[1]))
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [There is no source connected]</span>";
$error[$i] = "1";
}
else
{
if ($stats[1] == "1")
{
$song[$i] = $stats[6];
$listeners[$i] = $stats[4];
$max[$i] = $stats[3];
// Both IFs the same? Please check that and make one only if its the case
if ($stats[0] == $max[$i]) $msg[$i] = "<span class=\"red\">";
if ($stats[0] == $max[$i]) $msg[$i] .= "</span>";
}
else
{
$listeners[$i] = "0";
$msg[$i] = " <span class=\"red\">ERROR [Cannot get info from server]</span>";
$error[$i] = "1";
}
}
}
$i++;
}
if($song[1] != "")
{
echo $song[1];
exit();
}
echo uriencode($lastsong);
?>
And I want to change it to use prototype instead. I use prototype and jQuery already, and this is conflicting as written. I've no idea where to begin, but any assistance would be appreciated... especially since there are a lot of folks in my situation. Thanks so much.

Categories