Category Archives: backbone.js

How to configure the htaccess to handle AJAX GET request?

Backbone was running fine and then I accidentally deleted my .htaccess file.

I can access my database fine using a GET request directly from the URL, but when I go in via Backbone GET using ajax, no go.

What could the relation possible be?

Here is relevant PHP:

private function startDB()
{
    try
    {
        $this->db_one = new PDO( 'mysql:dbname=foo;host=localhost', 'foo_user', 'foo_pass' );
        // echo "working";
    }
    catch( PDOException $pdoError )
    {
        echo 'PDO connection failed: <br> ' . $pdoError->getMessage();
    }
}

BackboneJS – Cached files preventing user from getting changes unless they forcefully clear their browser cache

We have a web portal built using BackboneJS and currently are deploying the same on our own Amazon Instance. We use Java Apache Tomcat for the server side part of it.

The issue is that whenever we make any code changes in any of the views and/or controllers or any of the other supporting files. The newly implemented changes though deployed on to the server, do not reflect in the browsers of the users unless they forcefully clear their browser cache via the network tab in the "Developer Tools".

Is there any way to load a fresh copy of the BackboneJS files everytime the user logs in such that any and all newly developed code changes are made available to him the first time itself? As asking them to clear their caches after every deployment is a kind of no go to the "higher ups" :rollseyes:

Desperately looking out for a valid and workable solution.

Apache: How do I re-route all requests to a single file?

I'm writing a static single page Backbone site with a single entry point: index.html

I've been told that because of this, I need to re-route all requests to my url e.g. www.example.com/*, to that index.html file. So, if someone types in www.example.com/lolnotreal, I need that request to be redirected to /index.html but in a manner which my index.html file still could pick up the url attempted, in the example's case: /lolnotreal

Is this even possible considering it's just an html file? Basically I need for backbone to pick up the url attempted.

Thanks for any help

Dearest downvoter: Please explain. I'm not a server expert and my hours of attempts at using .htaccess have failed.

not getting POST data with application/json

I'm using Backbone, PHP(5.6) and Apache(2.4).

Problem: When posting data using Backbone's model.save() the $_POST array is empty on the server.

I know about different ways to fix this.

Client way: setting Backbone.emulateJSON to true or changing the Backbone source.
Server way: reading raw body instead of $_POST.

These work but they feel like hacks and in fact they end up being a bit inconvenient.
Also, Backbone's doc says:

If you're working with a legacy web server that can't handle requests encoded as application/json, setting Backbone.emulateJSON = true; will [fix it].

So it sounds like a server problem. How do I make my server non-legacy?

How to use multi-level Backbone Router fragments with Apache?

I'm having troubles getting Apache rewrites to work when directly loading pages with multi-level route fragments. Here are two examples:

Here is my virtual host configuration:

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.html [L]

Example 1: http://www.fakewebsite.com/products (working)

When I open the Example 1 URL with a single route fragment it loads up without issues using the Apache configuration below. Assets are loaded properly using http://www.fakewebsite.com/assets/image1.png.

Example 2: http://www.fakewebsite.com/products/12345 (not working)

When I open the Example 2 URL with two fragments the page doesn't load. It doesn't load because all of my css and js files are trying to load from http://www.fakewebsite.com/products/assets/image1.png.

How can I get this working for Example 2? I thought using RewriteBase / and RewriteRule ^index\.html$ - [L] would force all non-html files to use the base rather than the fragment.

Using apache to serve a js app and its api

So while working in localhost, I had the following folder structure

/htdocs
    /multikanban      # the js app
    /multikanban-api  # the php api

To make requests from the js app to the php api I basically used relative paths.

Now I am trying to deploy this to my dedicated server. I managed to get both projects working under http://multikanban.com (the app) and http://api.multikanban.com (the api). However, making requests from the app to the api requires of CORS as using a subdomain is considered as not part of the domain. I don't want to use CORS because this api will only be consumed by the app. That's why I moved the multikanban-api folder into the multikanban one and tried to use relative paths.

So far, I find problems because of my .htaccess and apache configuration.

The apache config looks like

#
#  multikanban.com (/etc/apache2/sites-available/multikanban)
#
<VirtualHost *:80>
        ServerAdmin [email protected]
        ServerName  multikanban.com
        ServerAlias www.multikanban.com

        # Indexes + Directory Root.
        # DirectoryIndex /app/index.html
        DocumentRoot /var/www/multikanban/app/
</VirtualHost>

while the .htaccess for the app looks like

# html5 pushstate (history) support:

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteCond %{REQUEST_URI} !multikanban-api 
    RewriteRule (.*) app/index.html [L]
</ifModule>

This is basically the config for backbone's pushstate to work, but I added the RewriteCond to ignore multikanban-api so that the url is not understood as a route of the app.

The problem is that with this config http://multikanban.com/multikanban-api will return a Not Found. I understand this is caused because of DocumentRoot being /multikanban/app and not just /multikanban. That's why I tried to define

 DocumentRoot /var/www/multikanban/ 
 DirectoryIndex /app/index.html

but that doesn't work at all. Acessing http://multikanban.com returns a require.js SyntaxError and doesn't even load the app.

Any ideas of how can I fix this or a way around on how to access the /multikanban-api without using CORS?

Redirect crawler using htaccess with push state enabled

I am trying to create .htaccess rules that redirect webcrawlers to prerender.io so I can get better SEO for my backbone app. I have been trying for hours but I just cant seem to get it correct.

Here is my .htaccess file with my redirect attempt. My intention for this file also is to:

  1. Force all traffic over SSL and add the www prefix
  2. Enable push state so I wouldn't need the the # in the URL

    <ifModule mod_rewrite.c>
    
    RewriteEngine On
    
    #Handle SSL and www redirects
    
    RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
    RewriteCond %{HTTPS} !on
    RewriteRule ^(.*)$ https://www.example.com/$1 [  R=301,L] 
    
    #Handle Prerender.io
    RequestHeader set X-Prerender-Token "example"
    
    
    
    RewriteCond %{HTTP_USER_AGENT} Googlebot|bingbot|Googlebot-Mobile|Baiduspider|Yahoo|YahooSeeker|DoCoMo|Twitterbot|TweetmemeBot|Twikle|Netseer|Daumoa|SeznamBot|Ezooms|MSNBot|Exabot|MJ12bot|sogou\sspider|YandexBot|bitlybot|ia_archiver|proximic|spbot|ChangeDetection|NaverBot|MetaJobBot|magpie-crawler|Genieo\sWeb\sfilter|Qualidator.com\sBot|Woko|Vagabondo|360Spider|ExB\sLanguage\sCrawler|AddThis.com|aiHitBot|Spinn3r|BingPreview|GrapeshotCrawler|CareerBot|ZumBot|ShopWiki|bixocrawler|uMBot|sistrix|linkdexbot|AhrefsBot|archive.org_bot|SeoCheckBot|TurnitinBot|VoilaBot|SearchmetricsBot|Butterfly|Yahoo!|Plukkie|yacybot|trendictionbot|UASlinkChecker|Blekkobot|Wotbox|YioopBot|meanpathbot|TinEye|LuminateBot|FyberSpider|Infohelfer|linkdex.com|Curious\sGeorge|Fetch-Guess|ichiro|MojeekBot|SBSearch|WebThumbnail|socialbm_bot|SemrushBot|Vedma|alexa\ssite\saudit|SEOkicks-Robot|Browsershots|BLEXBot|woriobot|AMZNKAssocBot|Speedy|oBot|HostTracker|OpenWebSpider|WBSearchBot|FacebookExternalHit|rogerbot|linkedinbot|embedly|quora\ link\ preview|showyoubot|outbrain|pinterest [NC,OR] 
    
    RewriteCond %{QUERY_STRING} ^_escaped_fragment_=(.*)$
    
    #Proxy the request
    RewriteRule ^$ http://service.prerender.io/https://%{HTTP_HOST}/%1 [QSA,L]
    
    # html5 pushstate (history) support:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L,QSA]
    
    
    </ifModule>
    

All the apache modules are loaded and working.

Access Control allow origin

Not sure what exactly is the issue - I have web app on apache with Marionette backbone models connecting to server side on different port.I Tried below to allow the access but doesn't not see to work:

This is under Directory tag of httpd.conf

   <IfModule mod_headers.c>
         Header set Access-Control-Allow-Origin  "*"
    </IfModule>


Header module is loaded as ./apachectl -M results below
 Loaded Modules:
 core_module (static)
 so_module (static)
 http_module (static)
 mpm_worker_module (static)
 authn_file_module (shared)
 authn_core_module (shared)
 authz_host_module (shared)
 authz_groupfile_module (shared)
 authz_user_module (shared)
 authz_core_module (shared)
 access_compat_module (shared)
 auth_basic_module (shared)
 reqtimeout_module (shared)
 filter_module (shared)
 mime_module (shared)
 log_config_module (shared)
 env_module (shared)
 headers_module (shared)
 setenvif_module (shared)
 version_module (shared)
 unixd_module (shared)
 status_module (shared)
 autoindex_module (shared)
 dir_module (shared)
 alias_module (shared)

navigate not working ONLY for empty fragment after enabling pushState

So, I had a Backbone Marionette app fully working with hashes. Then, I decided to enable pushState for better UX URLs.

I access the app at:

http://localhost:8888/multikanban/app

I applied the following changes:

  1. Enable pushState

    Backbone.history.start({pushState: true, root: "/multikanban/app/"});
    
  2. Define the following .htaccess

    <ifModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_URI} !index
        RewriteRule (.*) app/index.html [L]
    </ifModule>
    

At this point, the app loads without issues, I can move around, login, etcetera. However, when App.navigate("") is called (when I need to go to the initial app state) I get the following error:

Uncaught SyntaxError: Unexpected token <

landing_app.js:15 Uncaught TypeError: Cannot read property 'showLanding' of undefinedlanding_app.js:15 (anonymous function)require.js:1658 context.execCbrequire.js:874 Module.checkrequire.js:1121 (anonymous function)require.js:132 (anonymous function)require.js:1164 (anonymous function)require.js:57 eachrequire.js:1163 Module.emitrequire.js:925 Module.checkrequire.js:1151 Module.enablerequire.js:782 Module.initrequire.js:1178 callGetModulerequire.js:1572 context.completeLoadrequire.js:1679 context.onScriptLoad

require.js:1903 Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/multikanban/scripts/apps/landing/show/show_controller.js".

With App.navigate("") I am only updating the URL, nothing should be being "transferred" as the error states...

Observations:

  1. The App.navigate("") worked before using pushState.
  2. Changing App.navigate("") to something like App.navigate("a") makes it work but ofcourse the URL is wrong..
  3. Commenting the App.navigate("") doesnt get the app to crash, it simply doesn't update the URL, so yeah the problem should be with App.navigate("")

How can I get App.navigate("") to work? Why is that command apparently interacting with the server, shouldn't it just update the URL and history?

How to get Backbone.js Router to trigger on default/index (no #tag hashtag) in CodeIgniter

I have a CodeIgniter app using .htaccess to remove index.php from the url so they look like this:

http://example.com/admin/
http://example.com/admin/users
http://example.com/admin/reports
http://example.com/admin/files

With http://example.com/admin/files being a single page backbone app, I need to show a list of files by default. Then http://example.com/admin/files#file/123 would edit a specific file.

Here is my Backbone Router:

App.Router = Backbone.Router.extend({
    routes: {
      ''         : 'files',
      'file/:id' : 'file'
    },

    files: function(){
      $(document.body).append("Files route has been called..");
    },

    file: function(id){
      $(document.body).append("File route called with id:" + id);
    }

});
new App.Router;
Backbone.history.start();

I can get the "file" route to trigger with:

http://example.com/admin/files#file/33

However, http://example.com/admin/files is completely ignored by the Backbone Router.

How can I get the default or index Backbone.js route to trigger when using CodeIgniters RewriteRule that eliminates the index.php file?