Skip to main content

Posts

Showing posts from April 12, 2012

How to improve performance of Jquery autocomplete

I was planning to use jquery autocomplete for a site and have implemented a test version. Im now using an ajax call to retrieve a new list of strings for every character input. The problem is that it gets rather slow, 1.5s before the new list is populated. What is the best way to make autocomplete fast? Im using cakephp and just doing a find and with a limit of 10 items. Source: Tips4all

HTML/JavaScript UI widgets GUI builder

I've heard and used some of the libraries like Ext JS, qooXdoo, jQuery UI, dijit. I know there are unofficial attempts to create GUI builders but they are not really great. Any chance there is a HTML/JavaScript UI widget library with a decent GUI builder? Source: Tips4all

Javascript: undefined !== undefined?

Update - As of October 2011, some browsers (Safari 5.1, Firefox 7) no longer seem to let you change window.undefined, but some still do (Chrome 14) When I recently integrated Facebook Connect with Tersus , I initially received the error messages Invalid Enumeration Value and Handler already exists when trying to call Facebook API functions. It turned out that the cause of the problem was object.x === undefined returning false when there is no property 'x' in 'object'. I worked around the problem by replacing strict equality with regular equality in two Facebook functions: FB.Sys.isUndefined = function(o) { return o == undefined;}; FB.Sys.containsKey = function(d, key) { return d[key] != undefined;}; This made things work for me, but seems to hint at some sort of collision between Facebook's Javascript and my own. Any ideas what could cause this? Hint: It is well documented that undefined == null while undefined !== null . This is not the issue

What is the difference between " and " in JavaScript?

I saw this question and I am wondering about the same thing in JavaScript. If you use the character ' or the character " when making strings in JavaScript, the application seems to behave the same. So what is the difference between these two characters? The only advantage I have seen in using ' to build strings is that I can do stuff like: var toAppend = '<div id="myDiv1"></div>'; Instead of: var toAppend = "<div id=\"myDiv1\"></div>"; Is there any significant difference between them that I should be aware of? Source: Tips4all

jQuery: How to select "from here until the next H2&rdquo;?

I'm setting up a very straightforward FAQ page with jQuery. Like so: <h2>What happens when you click on this question?</h2> <p>This answer will appear!</p> This is all inside a very specific div, so I'll be selecting the header with $('#faq h2') . Simple, right? Click on the H2, and use this.next() to make the next paragraph show up. (The caveat with this page is that a non-programmer will be maintaining it, which is why I'm not using classes: there's no guarantee that any new entries would have the right classes in them.) So! The problem: <h2>What happens when you click on the next question?</h2> <p>That is an interesting conundrum.</p> <p>Because the maintainer is kind of long-winded</p> <p>and many answers will span a few paragraphs.</p> So how, without adding in div s and classes and whatnot, can I have my this.next() routine select everything between the question-that-was-

JSON left out Infinity and NaN; JSON status in ECMAScript?

Any idea why JSON left out NaN and +/- Infinity? It puts Javascript in the strange situation where objects that would otherwise be serializable, are not, if they contain NaN or +/- infinity values. Looks like this has been cast in stone: see RFC4627 and ECMA-262 at the top of p. 197: Finite numbers are stringified as if by String(number). NaN and Infinity regardless of sign are represented as the string null. Source: Tips4all

Programmatically stop Javascript execution in FireFox/FireBug

I am currently debugging complex Javascript/AJAX code written with mootools with FireBug. I am looking for a way to stop the JS execution as if it was a breakpoint programmatically. Ex: instructions ... degugger.breakpoint(); // the execution stops here as if a breakpoint was // manually set other instructions ... any idea? Source: Tips4all

Non-ajax GET/POST using jQuery (plugin?)

This is one of those situations where I feel like I'm missing a crucial keyword to find the answer on Google... I have a bag of parameters and I want to make the browser navigate to a GET URL with the parameters. Being a jQuery user, I know that if I wanted to make an ajax request, I would simply do: $.getJSON(url, params, fn_handle_result); But sometimes I don't want to use ajax. I just want to submit the parameters and get a page back. Now, I know I can loop the parameters and manually construct a GET URL. For POST, I can dynamically create a form, populate it with fields and submit. But I'm sure somebody has written a plugin that does this already. Or maybe I missed something and you can do it with core jQuery. So, does anybody know of such a plugin? EDIT: Basically, what I want is to write: $.goTo(url, params); And optionally $.goTo(url, params, "POST"); Source: Tips4all

Can javascript access a filesystem?

I was pretty sure the answer was NO , and hence google gears, adobe AIR, etc. If I was right, then how does http://tiddlywiki.com work? It is persistent and written in javascript. It is also just a single HTML file that has no external (serverside) dependencies. WTF? Where/how does it store its state? Source: Tips4all

JavaScript Charts API: Flot jQuery Plugin OR Google Visualization?

I am looking for a charts library to be displayed on a website. I will use intensively this library (for area, line and bar charts mainly), so I prefer to secure my choice before starting implementing. The list of website chart libraries that I have initially considered are: Plotkit Emprise JS Charts Sparkline Protochart gRaphael Bluff YUI Charts : However after some researches on this forum and investigations on the web, I have reduced my candidate list to these two libraries: Flot jQuery plugin Google Visualization Which one do you advise me to use and why (if you have worked with one or two of them, please tell me your feedback)? How do they compare one to each other regarding ease of use, performance and features? Thank you EDIT: Based-Flash Chart libraries were not eligible with my constraints Source: Tips4all

What is xhtml"s role attribute? What do you use it for?

I have read w3's page on this here , but it is still vague to me. Is the role attribute's purpose to clarify the code? Or will it be interpreted by some browsers or spiders? Can it be used as a dom selector using some javascript libraries (I am thinking that since the id attribute has to be unique, this could be use to identify multiple resources on a page)? Source: Tips4all

Best non-flash upload component for web applications?

I would like recommendations for upload scripts/components. My criteria: No flash Plain Javascript ok, jquery ok Must provide progress bar (updated from for instance ajax call). Probably isn't relevant, but I use ASP.NET MVC on server side. Thanks UPDATE Yes, I know there will need to be a server side component to this, but I can provide that. I'm more interested in the client side scripts. (Perhaps some solutions will be tied to their server side implimentations though - I don't know) Just to clarify - it doesn't have to be .net specific. I'm happy to use a component that only comes with (for instance) PHP server side scripts, and roll my own for .net. Thanks for all the answers - some very useful info there. In the end I accepted the 'AJAX uploader' - It didn't meet the progress bar requirement, but it seems that nothing might (at least without flash). I think I will also look into the possibililty of creating my own, based on

Modifying document.location.hash without page scrolling

We've got a few pages using ajax to load in content and there's a few occasions where we need to deep link into a page. Instead of having a link to "Users" and telling people to click "settings" it's helpful to be able to link people to user.aspx#settings To allow people to provide us with correct links to sections (for tech support, etc.) I've got it set up to automatically modify the hash in the URL whenever a button is clicked. The only issue of course is that when this happens, it also scrolls the page to this element. Is there a way to disable this? Below is how I'm doing this so far. $(function(){ //This emulates a click on the correct button on page load if(document.location.hash){ $("#buttons li a").removeClass('selected'); s=$(document.location.hash).addClass('selected').attr("href").replace("javascript:",""); eval(s); } //Click a button to chang

PHP pass function as param then call the function?

I need to pass a function as a parameter to another function and then call the passed function from withing the function...This is probably easier for me to explain in code..I basically want to do something like this: function ($functionToBeCalled) { call($functionToBeCalled,additional_params); } Is there a way to do that.. I am using PHP 4.3.9 Thanks! Source: Tips4all

Scaling Drupal

I am working on a Drupal based site and notice there are a lot of seperate CSS and js files. Wading though some of the code I can also see quite a few cases where many queries are used too. What techniques have you tried to improve the performance of Drupal and what modules (if any) do you use to improve the performance of Drupal 'out of the box'? Source: Tips4all

best way to determine if a URL is an image in PHP

Using PHP, given a URL, how can I determine whether it is an image? There is no context for the URL - it is just in the middle of a plain text file, or maybe just a string on its own. I don't want high overhead (e.g. reading the content of the URL) as this could be called for many URLs on a page. Given this restriction, it isn't essential that all images are identified, but I would like a fairly good guess. At the moment I am just looking at the file extension, but it feels like there should be a better way than this. Here is what I currently have: function isImage( $url ) { $pos = strrpos( $url, "."); if ($pos === false) return false; $ext = strtolower(trim(substr( $url, $pos))); $imgExts = array(".gif", ".jpg", ".jpeg", ".png", ".tiff", ".tif"); // this is far from complete but that's always going to be the case... if ( in_array($ext, $imgExts) )

Looping Through All a Server"s Sessions in PHP

Is there a way in PHP to get a list of all sessions (and the variables within each) on the server? Basically, we have a maintenance function which needs to know which users are currently logged into the site. We already store data for each user in a session variable, but I am hoping that I can loop through each of these sessions and pluck out the data I need. MY PHP is very limited (I am a .Net developer ussually) but if anyone knows if this is even possible (and how to do it) I'd be very grateful. I googled this, and the results I found tended to inidcate that it WASN'T possible, but I find this very hard to accept. Still, If you can't you can't but I thought my buddies on StackOverflow could give me a definitive answer! Source: Tips4all

Is there a reason I should not start with C#

I think I'm leaning toward C# and .net as a concentration language for learning web development. I would like to learn good programming fundamentals and I've looked at pretty much everything else. The four I've narrowed it down to have been C#, Python, Ruby and PHP. Is there a reason to stay away from C# (and I don't think the cost issue would really apply to my solo-developer situation but I could be totally wrong). Any thoughts? I realize that these are all great languages so I'm not trying to ask which is the best overall. However, would Ruby be a viable alternative for a first language or does it have too much "magic under the hood" coupled with Rails, and unorthodox methodologies? I do like what I've seen with the language. Source: Tips4all

Zend Framework form with jquery

Any one a idea how to simply create a form with Zend_Form and jquery? I want to use Zend_Form to validate the form so I don't have to dual script the form in JavaScript and PHP. Thank you, Ivo Trompert Source: Tips4all

Prevent Back button from showing POST confirmation alert

I have an application that supplies long list of parameters to a web page, so I have to use POST instead of GET. The problem is that when page gets displayed and user clicks the Back button, Firefox shows up a warning: To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. Since application is built in such way that going Back is a quite common operation, this is really annoying to end users. Basically, I would like to do it the way this page does: http://www.pikanya.net/testcache/ Enter something, submit, and click Back button. No warning, it just goes back. Googling I found out that this might be a bug in Firefox 3, but I'd like to somehow get this behavior even after they "fix" it. I guess it could be doable with some HTTP headers, but which exactly? Source: Tips4all

How to start using and developing on Ubuntu Linux?

I am a newbie Linux user who came from 10 years using windows OS, and developing in Microsoft languages. I want to have a good experience in Linux world and developing on it. First, I want to learn how to use this new OS, then how to start developing on it, I am interested in web applications, specially using Java/PHP because I have some experience in both and it will be a good start. Second, I want to learn how to develop on it. Are there any video tutorials to give me a good starting push? any recommended books or references? Source: Tips4all

PHP vs template engine

I'm currently having a discussion about the choice between php as a template engine versus a template engine on top of php. What is your choice, and why? I say, why another template engine, if php is an template engine itself. Source: Tips4all

ExtJS grab JSON result

I'm generating JSON response from PHP witch looks like this: { done:'1', options: [{ message:'Example message'},{message:'This is the 2nd example message'}]} I want to grab these results using ExtJS. This is what I have so far: Ext.Ajax.request({ loadMask: true, url: 'myfile.php', params: {id: "1"} }); What do I have to write next to get the json results like this: var mymessages = jsonData.options; And mymessages should contain Example message and This is the 2nd example message. Thank you. Source: Tips4all

Copy Image from Remote Server Over HTTP

I am looking for a simple way to import/copy images from remote server to a local folder using PHP. I have no FTP access to the server, but all remote images can be accessed via HTTP (i.e. http://www.mydomain.com/myimage.jpg ). Example use: A user wishes to add an image to his profile. The image already exists on the web and the user provides with a direct URL. I do not wish to hotlink the image but to import and serve from my domain. Source: Tips4all

MySQL - ignore insert error: duplicate entry

I am working in PHP. Please what's the proper way of inserting new records into the DB, which has unique field. I am inserting lot of records in a batch and I just want the new ones to be inserted and I don't want any error for the duplicate entry. Is there only way to first make a SELECT and to see if the entry is already there before the INSERT - and to INSERT only when SELECT returns no records? I hope not. I would like to somehow tell MySQL to ignore these inserts without any error. Thank you Source: Tips4all

What are the PHP-specific antipatterns that you know of?

PHP as a Blunt Instrument I hear PHP getting bashed around a lot lately. In quite a few projects, I have seen insane php code bases - so bad you really wonder if the person was on hallucinogenic drugs when they wrote the code. Sometimes, I wonder what the code would have been like if the initial developers had a bit more guidance as to what not to do. However, I have also seen some very well organized PHP projects that were done in 100% OOP and were a pleasure to maintain, but they were not written by "php programmers." I give all of our junior devs a link to Java Anti-Patterns . One of the nice things about that page is the Java-specific examples because there are many features of Java that lend themselves to common mistakes. I was hoping to find a similar list for php, but a google search did not reveal anything meaningful. There are a few questions already out there for what a developer should know when programming PHP , but I wanted to focus on the negative.

How do I remove accents from characters in a PHP string?

I'm attempting to remove accents from characters in PHP string as the first step to making the string usable in a URL. I'm using the following code: $input = "Fóø Bår"; setlocale(LC_ALL, "en_US.utf8"); $output = iconv("utf-8", "ascii//TRANSLIT", $input); print($output); The output I would expect would be something like this: F'oo Bar However, instead of the accented characters being transliterated they are replaced with question marks: F?? B?r Everything I can find online indicates that setting the locale will fix this problem, however I'm already doing this. I've already checked the following details: The locale I am setting is supported by the server (included in the list produced by locale -a ) The source and target encodings (UTF-8 and ASCII) are supported by the server's version of iconv (included in the list produced by iconv -l ) The input string is UTF-8 encoded (verified using PHP's mb_ch

MySQL INTO OUTFILE overide existing file?

I've written a big sql script that creates a CSV file. I want to call a cronjob every night to create a fresh CSV file and have it available on the website. Say for example I'm store my file in '/home/sites/example.com/www/files/backup.csv' and my SQL is SELECT * INTO OUTFILE '/home/sites/example.com/www/files/backup.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' FROM ( .... MySQL gives me an error when the file already exists File '/home/sites/example.com/www/files/backup.csv' already exists Is there a way to make MySQL overwrite the file? I could have PHP detect if the file exists and delete it before creating it again but it would be more succinct if I can do it directly in MySQL. Source: Tips4all

Replace URLs in text with HTML links

Here is a design though: For example is I put a link such as http://example.com in textarea . How do I get PHP to detect it’s a http:// link and then print it as print "<a href='htttp://example.com'>http://example.com</a>"; I remember doing something like this before however, it was not fool proof it kept breaking for complex links. Another good idea would be if you have a link such as http://example.com/test.php?val1=bla&val2blablabla%20bla%20bla.bl fix it so it does print "<a href='http://example.com/test.php?val1=bla&val2=bla%20bla%20bla.bla'>"; print "http://example.com/test.php"; print "</a>"; This one is just an after thought.. stackoverflow could also probably use this as well :D Any Ideas Source: Tips4all

How to detect duplicate values in PHP array?

I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and out put the results. For example, given the following array: $array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi'); I would like to print: apple (2) orange pear (2) banana kiwi (3) Any advice on how to approach this problem? Thanks. Mike Source: Tips4all

Alternative to mysql_real_escape_string without connecting to DB

I'd like to have a function behaving as mysql_real_escape_string without connecting to database as at times I need to do dry testing without DB connection. mysql_escape_string is deprecated and therefore is undesirable. Some of my findings: http://www.gamedev.net/community/forums/topic.asp?topic_id=448909 http://w3schools.invisionzone.com/index.php?showtopic=20064 Thank you in advance! Source: Tips4all

Where and when to open a database connection

I am working on implementing use of the mysql class found here in an existing script. The script almost always needs to interact with the database, even if there are times when it does not. What is the best practice in this case? Should I open a connection and keep that open until the end of the script or should I open a connection when I need one, closing it when I'm done, to avoid opening a connection when the script does not need it? Source: Tips4all

AJAXify site

I have legitimate reasons to do what I am trying to explain. I have an existing site say abc.com which has regular pages etc. everything written in php. Now I would like to AJAXify the site i.e. when a user clicks on a link, it should fetch the link using AJAX and replace the page contents. This is the easy part and I can achieve it using jQuery get function. Now the problem comes when the user bookmarks the page. I can use hash tags to specify if the user is on another page, but instead of using javascript to fetch the new page again, is it possible to fetch it directly using PHP when the page is called. Can you please give me an outline on how to achieve the above. This functionality is similar to what Facebook has. Thankyou for your time. Source: Tips4all

PHP: Truncate HTML, ignoring tags

I want to truncate some text (loaded from a database or text file), but it contains HTML so as a result the tags are included and less text will be returned. This can then result in tags not being closed, or being partially closed (so Tidy may not work properly and there is still less content). How can I truncate based on the text (and probably stopping when you get to a table as that could cause more complex issues). substr("Hello, my <strong>name</strong> is <em>Sam</em>. I&acute;m a web developer.",0,26)."..." Would result in: Hello, my <strong>name</st... What I would want is: Hello, my <strong>name</strong> is <em>Sam</em>. I&acute;m... How can I do this? While my question is for how to do it in PHP, it would be good to know how to do it in C#... either should be OK as I think I would be able to port the method over (unless it is a built in method). Also note that I have included an HT