...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
March 22, 2012

How to increase the maximum call stack in Javascript?

Question by shershams

I have an event, which can fire itself. I try to make the code as efficient as possible, but it can hit maximum call stack in some circumstances, which are out of my control. It’s not an infinite stack and it will end at some point, but sometimes it can potentially crashe before it finishes because of the limit.

Will I increase the number of call stack if I set up 2 similar event listeners and split the code? Or what can I do?

UPDATE: It’s on DOM change event (working with Webkit only, so don’t care about other browsers), which can also modify the DOM based on some conditions. I haven’t really hit that limit yet, but theoritically, it potentially can. I’m still optimizing the code to make as less DOM manipulations as possible.

UPDATE 2: I’m including sample (not real) example:

document.addEventListener('DOMSubtreeModified', function(event){

    this.applyPolicy(event);

}, true);

function applyPolicy(event){
    if( typeof event != "undefined" ){
        event.stopPropagation();
        event.stopImmediatePropagation();
    }

    if( !isButtonAllowed ){
        $('button:not(:disabled)').each(function(){

           $(this).attr('disabled', true);

        });
    }
}

This is just a sample code, but even in this case, if you have say 100s of buttons, the call stack will be in 100s too. Note that if you use $('button').attr('disabled', true);, this will cause call stack problem, because jQuery will be trying to modify the DOM infinitely.

Answer by am not i am

While it sounds like you may need to rethink some code, one possibility would be to put a recursive call in a setTimeout at some given interval. This allows you to begin a new call stack.

Take this example…

var i = 0;

function start() {
    ++i;
    var is_thousand = !(i % 1000);

    if (is_thousand)
        console.log(i);

    if (i >= 100000)
        return; // safety halt at 100,000
    else
        start()
}

It just logs to the console at every interval of 1,000. In Chrome it exceeds the stack somewhere in the 30,000 range.

DEMO: http://jsfiddle.net/X44rk/


But if you rework it like this…

var i = 0;

function start() {
    ++i;
    var is_thousand = !(i % 1000);

    if (is_thousand)
        console.log(i);

    if (i >= 100000) // safety halt at 100,000
        return;
    else if (is_thousand)
        setTimeout(start, 0);
    else
        start();
}

Now at every 1,000, the function will be allowed to return and the next call will be made asynchronously, starting a new call stack.

Note that this assumes that function is effectively ended when the recursive call is made.

Also note that I have a condition to stop at 100,000 so we’re not infinite.

DEMO: http://jsfiddle.net/X44rk/1/

Answer by Starx

You can’t, they are browser dependant and quite frankly they have quite a wide range, so no need to worry about that IMO.

Read more

CSS DIV Overflow

Question by Devin

Site: http://partsconsign.com/parts/?custid=1

I don’t know what happened. All of a sudden, without changing the css, when I expand the “browse” categories, they overflow outside of the containing divs. Here is the css of the divs:

.bodyArea
{
    width: 900px;
    background-image:url(/images/bg.jpg);
    background-repeat:no-repeat;
    border-width: thin;
    border-style: solid;
    margin-left:auto;
    margin-right:auto;
    -moz-border-radius: 8px;
    border-radius: 8px;
    min-height: 900px;
}

.pageArea
{
    background-image: url(../images/page_bg.jpg);
    background-repeat: repeat;
    width: 95%;
    position:relative;
    margin-left: 25px;
    margin-top: 30px;
    min-height: 700px;
    height:auto;
}

#partCat {
    width: 775px;
    padding:5px;
    cursor:pointer;
}

I don’t see why expanding these divs would cause any kind of overflow. None of these divs have any absolute positioning. What am I doing wrong? #partcat is within .pageArea, which is within .bodyArea. I’ve looked through many questions asked previous here, but all of them seem to have slightly different issues. Help!

Answer by Starx

You div is fixed on 30px height. Remove the height from this part

<div style="height: 30px; width: 100%">

Tested through the firebug, IT WORKS

Read more

How can i uncheck multiple select box options by class with jquery?

Question by tonymarschall

I have multiple multi-select boxes with the same class and i want to unselect all on an event. They have all a div with the same class class_for_all_multi_selects around them.

$("#element_to_uncheck_all_options").change(function() {
  $('.class_for_all_multi_selects'). ...?
});

<div class="class_for_all_multi_selects">
  <select multiple="multiple" name="1">
    <option value="1">option1</option>
    <option value="2">option2</option>
  </select>
</div>

<div class="class_for_all_multi_selects">
  <select multiple="multiple" name="2">
    <option value="1">option1</option>
    <option value="2">option2</option>
  </select>
</div>

How can i uncheck multiple select box options by class with jquery?

Answer by Jigs

you can also try this using prop:

 $("div.class_for_all_multi_selects option:selected").prop('selected',false);

check it out : http://jsfiddle.net/EVrrz/3/

Answer by Starx

Use removeAttr() to remove the selected attribute from all options

$('select option:selected').removeAttr("selected");

Since you said #element_to_uncheck_all_options is a div, you should bind to click events instead of change

$("#element_to_uncheck_all_options").click(function() {
   $('select option:selected').removeAttr("selected");
});
Read more

Errors when using array_push — "First argument should be an array"

Question by Nate

I have the following code:

<?php

function foo($bar) 
{
    global $products; 

    //$products = array();

    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    $results = mysql_query($query);

    while($row = mysql_fetch_array($results, MYSQL_ASSOC))
    {
        array_push($products, $row);
        echo 'name pushed, ';
    }
}

require('mysql_ipb_connect.php'); // connect to ipb mysql database

$products = array(); 
foo(5);

?>

When I run it I get the following output:

Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed,
Warning: array_push() [function.array-push]: First argument should be an array in /home/rgcpanel/public_html/category/category.php on line 14
name pushed, 

If I uncomment “$products = array();” then the output is correct:

name pushed, name pushed, name pushed, 

Why is this happening? I declare the $products array outside of a function (so it’s global), and then specify it as being a global inside the function. Something is not right, but I’m not sure what that is?

Thanks for your advice.

Answer by Michael Berkowski

Per the comments, $products was initialized by an included file which was included inside a function. That defines its scope to the function, rather than globally. So you’ll need to use global $products; before calling the include.

function func_that_defined_products() {
  global $products;
  include('file_that_defines_products.php');
}

// Now when called globally later, it will be at the correct scope.


function foo($bar) 
{
    global $products; 
    $query = 'SELECT p_name FROM 0_products WHERE p_category IN (' . $bar . ')';
    // etc...
}

In any case, I find it a little more readable to use $GLOBALS['products'] instead of the global keyword. And as always, wherever possible it is a preferred practice to pass the variable into a function rather than accessing it globally.

// If you can, do it this way
function foo($bar, $products) {
  // $products was a param, and so global is unnecessary
}

However in your case, if the CMS defines it you may lose the flexibility to do it that way…

Answer by Starx

Uncomment this part

//$products = array();

Initialise the $products as an array

Read more

How to Implement Pages Feature like YouTube / Other sites?

Question by Delos Chang

I’m still new to Javascript and would like to create a ‘pages’ feature for comments and replies.

YouTube videos have a very nice pagination feature that pages the comments well.

How do I go about doing this? My current setup is with PHP, Javascript, and MySQL.

Answer by Starx

Youtube sends an ajax request back to the server and fetches the results which is updated to the page currently viewed. Other sites also use similar technique.

Basic thing you need to know are:

  1. pagination requires two main variables. $page and $itemsPerPage.
  2. Using above variable, you will create a query limit
  3. You will use this limit in your query to fetch the result of the next page.

Example:

$page = (int)$_POST['page'];
$itemsPerPage = 10; //Generally this might be static
$limit = (($page-1)*$itemsPerPage).",".$itemsPerPage;
// For the Page 1, this give 0,10

$query = "SELECT ... LIMIT $limit";
   //Translates to LIMIT 0,10 so takes out the first 10 records or in other words first page
//get the records, creat the markup and echo them

Now, as part of Javascript, here is an example of jQuery Post Request

$("#yourpageonelink").click(function() {
   $.post("yourpage.php", { 
     page: 1 // I am using static value for demo, but you should get this dynamically
   }, function(data)  { 
      //Now data will get the content returned from the php file
     // So update the div
     $("#mainContainer").html(data);
   });
});
Read more

How to synchronize all mobile devices accesing a web page?

Question by Jorge Ortega

It might use a cronjob in PHP. What I need is to display something at the same time, at a specific hour, in all devices that are accessing a determined url at that time (i.e. 12:00:00).

Answer by Starx

You might have to use SERVER TIME for this, since client time cannot be trusted. So, send a POST request to page, regularly to check for the time and get the output if the time is correct and then show.

Example:

JS:

setInterval(checkRegular, 60000);
function checkRegular() {
    $.post('check.php', function(data) {
         if(data.length) {
              //show the message
         }
    }
}

PHP:

<?php 
if($time==$requiredTime) {
   echo "the message";
}
?>
Read more

I have seen many different ways to use CURL in PHP. Which is the "right" one?

Question by Kaoukkos

I have read that CURL is way too fast than File Get Contents and less memory consuming. So, I will go with CURL. I read some articles to find info about it and how to use it properly and efficiently.
The problem is that I found many ways of using CURL, I posted 3 variations below.

My question is which one is the best to use?

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
  $content = curl_exec($ch);


     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $path);
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     $cache = curl_exec($ch);
     curl_close($ch);


 $ch = curl_init("");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $result = curl_exec($ch);
 curl_close ($ch);

Answer by Rocket Hazmat

It all depends on what options you want. Most of cURL’s options will have some default, which will be set if you do not manually set an option.

For example: CURLOPT_RETURNTRANSFER defaults to FALSE (so setting it to FALSE in your code would be redundant).

Passing a parameter to curl_int is just a shortcut for CURLOPT_URL. The other options all depend on what you want to do.

Here is a list of all the cURL options: http://php.net/manual/en/function.curl-setopt.php

Pick the options you want, exclude those you don’t. There’s no “right” way, just the way that works the way you want.

Answer by Starx

Its like asking,

I have see many ways people code PHP, but which one is right?

There is no correct answer for such question, as everybody is going to have their own opinion about every way.

So, I suggest you read the PHP.net’s manual on CURL and choose the correct method based on your coding style, requirement and construct.

Read more

How to extend multiple utility classes

Question by w00

This question is kinda aimed towards PHP but it probably applies to other languages aswell. In PHP you can only extend one class. But what if you need more classes?

Suppose i have the following classes:

class MyClass extends Observer, Logger, OtherUtilClass

MyClass can’t extend more than one class. But it needs to be an observer. And it might need some other base class aswell to fully function. What would be the best approach for this?

Answer by Starx

No

Your idea leads to multiple inheritance and it is not available in PHP for good.

I extremely recommended you read this question to see why you shouldn’t try this.


However, you still can chain the classes. If done in a proper way you can get the functionality of all classes.

Class Observer {}
Class Logger extends Observer {}
Class OtherUtilClasses extends Logger {}

//Now
class MyClass extends OtherUtilClasses {}
Read more

Automatically generate RSS feeds

Question by Sherwin Flight

I have information stored in a database that I want to use to create RSS feeds.

What is the best way to do this?

Also, are there any PHP library/functions that I can pass the data to and they will take care of ensuring that any characters that need to be encoded/stripped are dealt with?

Answer by Starx

PHP Universal Feed Generator is the one you are looking for.

It supports RSS 1.0, RSS 2.0 and ATOM

Read more

build website handheld device friendly

Question by Shruti Jakhete

I want to adapt a method to convert my fixed width website to handheld device friendly website. Could anybody please suggest which method would be the best. Considering it should not compromise the loading time of website. I believe Responsive Web Design should work but I from research I found responsive images used in responsive webdesign sometimes compromise the websie loading time.

Answer by Starx

I think it is wise to detect a mobile browser user agent string (server side) and display content accordingly.

If you are building using PHP, then check out this awesome script.

Usage is something like this:

if($isMobile){
   header('Location: http://m.youdomain.com/' . urlencode($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
   exit();
}

Also check out the Switcher

Read more
...

Please fill the form - I will response as fast as I can!