The service worker does not call cached files when offline - html

I cached the offline.html and image files using a service worker. Navigating to offline.html works fine. But it fails to load image from offline.html. At offline.html, it tries to get the image cached by the service worker directly without fetching it, but it fails because the internet is disconnected.
I tried changing the cache.match('/offline.html') part to cache.match(event.request), but this does not move to offline.html. How do I configure the cached files to be used in offline.html when the Internet is disconnected?
// service-worker.js
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
const ASSETS = ["offline.html", "image/icon_replay_b_15pt.png"];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
cache.addAll(ASSETS);
})()
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
if ("navigationPreload" in self.registration) {
await self.registration.navigationPreload.enable();
}
})()
);
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate") {
console.log(event.request.url);
event.respondWith(
(async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
console.log("Fetch failed; returning offline page instead.", error);
const cache = await caches.open(CACHE_NAME);
return cache.match("/offline.html");
}
})()
);
}
});
<!-- offline.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OFFLINE</title>
<style>
body { font-family:'NanumSquare'; }
body, html {width:100%; height:100%; margin:0; }
* {
box-sizing: border-box;
}
.btn-outline-01 {
border:1px solid #C9CACA;
}
.btn {
height:44px;
background:transparent;
border-radius: 5px;
font-size: 16px;
font-weight: 700;
}
.icon-wrap {
width:24px;
height:24px;
}
.icon-wrap img {
width:100%;
height:100%;
}
* { margin:0; }
.internet-err-wrap {
width:100%;
height:100%;
overflow: hidden;
}
.internet-err {
width:800px;
margin:0 auto;
position:relative;
}
.internet-err .err-text {
position:absolute;
left:5%;
top:35%;
}
.internet-err .err-text h2 {
font-weight:900;
font-size: 26px;
color:#333333;
}
.internet-err .err-text > p {
color:#9FA0A0;
margin-top:10px;
}
.internet-err .err-text button {
display: flex;
justify-content: center;
align-items: center;
margin-top:40px;
font-family:'NanumSquare';
padding:0 20px;
}
.internet-err .err-text button .icon-wrap {
margin-right:5px;
}
.internet-err svg {
width:160%;
}
</style>
</head>
<body>
<div class="internet-err-wrap">
<div class="internet-err">
<div class="err-text">
<button class="btn btn-outline-01" onclick="window.location.reload()">
<div class="icon-wrap">
<img src="/image/icon_replay_b_15pt.png" alt="" />
</div>
<p>retry</p>
</button>
</div>
</div>
</body>
</html>

So here you have written the code only mode of navigate but if you want to fetch the image and css from cache then you should use mode as image and style.
This will allow you to fetch the images and css.
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate") {
// Open the cache
event.respondWith(
caches.open(cacheName).then((cache) => {
// Go to the network first
return fetch(event.request.url)
.then((fetchedResponse) => {
cache.put(event.request, fetchedResponse.clone());
return fetchedResponse;
})
.catch(() => {
// If the network is unavailable, get
// return cache.match(event.request.url);
return cache.match("offline.html");
});
})
);
} else if (
event.request.destination === "image" ||
event.request.destination === "style"
) {
event.respondWith(
caches.open(cacheName).then((cache) => {
return cache.match(event.request);
})
);
// return;
} else {
return;
}
});

Related

How to give some space between my buttons

I need help giving my buttons some space. No matter what I try, I just can't seem to space them out.
You can see my github repository here.
The following is my HTML with stylesheets inside.
<script src="update.js"></script>
<script src="sw.js"></script>
<script>
let d = new Date();
//alert(d);
let hrs = d.getHours();
let min = d.getMinutes();
let day = d.getDay();
let auth = false;
fetch('https://raw.githubusercontent.com/AzlanCoding/iframe-browser-pwa/main/lock.js')
.then(response => response.text())
.then(data => {
let split_str = "/split/";
const data_arr = data.split(split_str);
let lock = data_arr[1];
if (data_arr[0] === "lock") {
setInterval(lock,500);
}else{
alert(data_arr[0]);
}
console.log(data_arr[0]);
});
</script>
<!DOCTYPE html>
<html lang="en">
<style>
body {
background-color: ##2C2F33;
}
</style>
<head>
<meta name="theme-color" content="#2C2F33">
<meta charset="UTF-8">
<meta name="description" content="Azlan's iframe Browser">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!meta http-equiv="cache-control" content="no-cache, must-revalidate, post-check=0, pre-check=0, no-store">
<!meta http-equiv="cache-control" content="max-age=0" />
<!meta http-equiv="Pragma" content="no-cache">
<!meta http-equiv="Expires" content="0">
<title> Iframe Browser </title>
<link rel="canonical" href="https://azlancoding.github.io/iframe-browser-pwa/" />
<link rel="manifest" href="/iframe-browser-pwa/manifest.webmanifest">
<meta name="keywords" content="bypass, school, browser in website, cloud browser">
<link rel="stylesheet" href="css/styles.css">
<title> iFrame browser </title>
<script language="javascript">
const getValidUrl = (url = "") => {
let newUrl = window.decodeURIComponent(url);
newUrl = newUrl.trim().replace(/\s/g, "");
if(/^(:\/\/)/.test(newUrl)){
return `https${newUrl}`;
}
if(!/^(f|ht)tps?:\/\//i.test(newUrl)){
return `https://${newUrl}`;
}
return newUrl;
};
function setCookie(c_name,value,exdays){
var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name){
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1){
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1){
c_value = null;
}
else{
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1){
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start,c_end));
}
return c_value;
}
checkSession();
function checkSession(){
var c = getCookie("visited");
if (c === "yes") {
alert("Welcome back! Make sure you have your extension on.");
}
else {
alert("By continuing, you agree to the terms and conditions in azlancoding.github.io/iframe-browser/TermsAndConditions")
ext_install();
}
}
function ext_install()
{
if (window.confirm('An extension is required for this website to work. Do you want to install it now?'))
{
setCookie("visited", "yes", 365)
window.location.href='https://chrome.google.com/webstore/detail/ignore-x-frame-headers/gleekbfjekiniecknbkamfmkohkpodhe';
};
};
function checkCookie() {
let user = getCookie("alerted");
if (user != "") {
alert("Welcome again !");
} else
{ext_install();}
}
//document.getElementById("myIframe").src = "https://wwf.org";
var iframe = document.getElementById("myIframe");
//var website = iframe.src;
//console.log(website);
document.addEventListener("scroll", function(event)
{
var style = document.getElementById("myIframe").style;
style.webkitTransform = style.webkitTransform ? "" : "scale(1)";
})
/*function resizeIframe()
{
document.getElementById('myIframe').height = 100%;
}*/
function ResetBox()
{
if(document.getElementById("URL").value == '')
{document.getElementById("URL").value='';};
}
function LoadPage()
{
var objFrame=document.getElementById("myIframe");
var newurl = getValidUrl(document.getElementById("URL").value);
objFrame.src = newurl;
}
var elem = document.documentElement
function openFullscreen() {
if (elem.requestFullscreen)
{
elem.requestFullscreen();
}
else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
}
}
function closeFullscreen() {
if (document.exitFullscreen)
{
document.exitFullscreen();
}
else if (document.webkitExitFullscreen)
{
document.webkitExitFullscreen();
}
else if (document.msExitFullscreen)
{
document.msExitFullscreen();
}
}
</script>
<style>
.iframe-container {
overflow: visible;
/* 16:9 aspect ratio */
//padding-top: 56.25%;
position: 60px 0px;
//margin-top: 60px;
}
:root {
--fallback-title-bar-height: 45px;
}
.draggable {
app-region: drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: drag;
}
.nonDraggable {
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
#child {
width: window.innerWidth;
//height: window.innerHeight;
height: 100vh;
flex: 1 1 auto;
position: absolute;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
left: 0;
right: 0;
}
.button {
background-color: #ffffff;
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 10px;
margin: 4px 2px;
margin-right: 5px;
cursor: pointer;
border-radius: 10px;
app-region: no-drag;
/* Pre-fix app-region during standardization process */
-webkit-app-region: no-drag;
}
fieldset {
border: 0px;
}
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
}
#titleBarContainer {
position: absolute;
top: 0;
left: 0;
height: env(titlebar-area-height, var(--fallback-title-bar-height));
width: 100%;
background-color:#254B85;
}
#titleBar {
position: absolute;
top: 0;
display: flex;
user-select: none;
height: 100%;
left: env(titlebar-area-x, 0);
//left : 0px;
width: env(titlebar-area-width, 50%);
color: #FFFFFF;
font-weight: bold;
text-align: center;
}
#titleBar > span {
margin: 5;
padding: 0px 32px 0px 32px;
}
#titleBar > input {
flex: 1;
margin: 0px;
border-radius: 5px;
border: none;
padding: 8px;
}
#mainContent {
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: env(titlebar-area-height, var(--fallback-title-bar-height));
overflow-y: scroll;
}
</style>
</head>
<body style="background-color:#254B85">
<div id="titleBarContainer" >
<div id="titleBar">
<span class="draggable">Iframe Browser</span>
<input class="nonDraggable" type="text" ID="URL" placeholder="Enter a URL" value="https://www.google.com"></input>
<input type="submit" class="frmSubmit" value="Go" onclick="LoadPage()">
<input type="button" VALUE="&#65513" onClick="history.back()">
<input type="button" VALUE="&#65515" onClick="history.forward()">
<input type="button" class="fullscreen" value="⛶" onclick="openFullscreen()">
<input type="button" class="Exitfullscreen" value="Exit Fullscreen" onclick="closeFullscreen()">
<input type="button" class="newWindow" value="New Window" onclick=" window.open('https://azlancoding.github.io/iframe-browser-pwa/','_blank')">
<input type="button" class="cloudbrowser" value="Cloud Browser" onclick="window.open('https://replit.com/#azlancoding/free-and-unlimited-cloud-browser?embed=true','_blank')">
</div>
</div>
<!div style="Clear:both;">
<!input type="text" value="https://www.google.com" class="frmUrlVal" ID="URL" placeholder = "Enter a URL" >
<!/div>
<div id = "child" >
<iframe align="top" width="100%" height="100%" allowtransparency="true" style="background: #FFFFFF;" src="https://www.google.com" onload = "check()" onerror"ext_install()" allow="camera;microphone" frameborder=yes loading ="lazy" name="myIframe" id="myIframe"> </iframe>
</div>
<script>
window.onbeforeunload = () => '';
var urlbox = document.getElementById("URL");
urlbox.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
LoadPage();
}
});
function check(){
document.getElementById("URL").value = "";
}
</script>
<script>
if (navigator.serviceWorker) {
navigator.serviceWorker.register (
'/iframe-browser-pwa/sw.js',
{scope: '/iframe-browser-pwa/'}
)
}
</script>
<script src="js/app.js"></script>
</body>
</html>
The stylesheet may be weird as it is used to support Windows Overlay Controls which allowed buttons to be placed on top next to the buttons to minimise, maximise and close the window. I just changed the manifest to support tabbed experimental feature.
Any help is appreciated.
Update:
I tried to use <span> but it over did it...

Puppeteer screen not vertically centering flexbox item properly

I am seeing this using puppeteer-stream to record video (it's a thin 1-file wrapper around puppeteer).
Notice how it's not centered vertically. There is no scrollable area either, this is it.
The HTML is this:
<!doctype html>
<html lang='en'>
<head>
<meta charset='utf-8'>
<style>
html, body {
margin: 0;
padding: 0;
height: 800px;
width: 800px;
}
#content {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
background-color: #000;
}
#row {
display: inline-block;
font-size: 32px;
width: 600px;
text-align: center;
}
#row * {
text-align: center;
position: relative;
color: #9A7FAE;
}
#row .highlight {
color: #BEE5B0;
}
</style>
</head>
<body>
<div id='content'><div id='row'><span>i am some text</span></div></div>
</body>
</html>
And the Puppeteer script is essentially this:
const { launch, getStream } = require('puppeteer-stream')
const fs = require('fs')
const file = fs.createWriteStream(`${__dirname}/poem.webm`)
const wait = (ms) => new Promise((res, rej) => setTimeout(res, ms))
async function start() {
const browser = await launch({
defaultViewport: null,
args: [`--window-size=${800},${800}`]
})
const page = await browser.newPage();
await page.setViewport({
width: 800,
height: 800,
})
await page.goto('file:///Users/me/poem.html')
const stream = await getStream(page, { audio: true, video: true })
await page.click('#row')
console.log("recording")
stream.pipe(file).on('end', () => {
console.log('end')
})
setTimeout(async () => {
await stream.destroy()
file.close()
console.log("finished")
await browser.close()
}, 1000 * 30)
}
start()
Why is it not centering vertically? How do I get it to vertically center?

Make element's height adaptative to what's inside

I want to make a grey-colored background for my list in ReactJS.
The problem is that the background seems to have a fixed height which seems to be smaller than the inside's height...
I never met this problem before, and the only way I found to have the background size bigger than the element's is to put height: XXXpx, which is not suitable...
Can someone explain me what I did wrong ?
Here is my class file :
import React, { Component } from "react";
import { ListGroupItem } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import { API } from "aws-amplify";
import "./ProjectList.css";
export default class ProjectList extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
projects: [],
reducedView: true,
projectsNumber: 1000,
numberOfElementsToDisplay: 1000
};
}
async componentDidMount() {
try {
const projects = await this.projects();
console.log(projects)
this.setState({ projects });
} catch (e) {
alert(e);
}
this.setState({ isLoading: false });
}
projects() {
return API.get("economics-endpoint", "/list");
}
handleClick(e) {
this.setState({ reducedView: false });
e.preventDefault();
}
renderNotesList(projects) {
return [{}].concat(projects).map(
(note, i) => {
if(i !== 0){
if((this.state.reducedView && i <= this.state.numberOfElementsToDisplay) || !this.state.reducedView){
return(
<div className="element">
<ListGroupItem className="mainContainer">
<div>
ProjectName#{i}
</div>
</ListGroupItem>
</div>
);
}
}
else{
if(this.state.projectsNumber === 0){
return(
<div className="element">
<LinkContainer to={`/econx/new`}>
<ListGroupItem className="new">
<div>
+ Create New Project
</div>
</ListGroupItem>
</LinkContainer>
<div className="errorMessage">
You don't have any existing project yet.
</div>
</div>
);
}
else{
return(
<div className="element">
<LinkContainer to={`/econx/new`}>
<ListGroupItem className="new">
<div>
+ Create New Project
</div>
</ListGroupItem>
</LinkContainer>
</div>
);
}
}
}
);
}
render() {
return (
<div className="ProjectList">
<div className="projects">
{!this.state.isLoading &&
this.renderNotesList(this.state.projects)}
</div>
</div>
);
}
}
And my css file :
.ProjectList .notes h4 {
font-family: "Open Sans", sans-serif;
font-weight: 600;
overflow: hidden;
line-height: 1.5;
white-space: nowrap;
text-overflow: ellipsis;
}
.projects{
background-color: #E0E0E0;
border-radius: 10px;
padding: 1%;
}
.list-group-item{
margin-bottom: 3px;
padding: 0px;
line-height: 200px;
text-align: center;
vertical-align: middle;
border-radius: 6px;
padding-bottom: 50px;
}
.list-group-item:first-child{
padding: 0px;
border-radius: 6px;
}
.list-group-item:hover{
vertical-align: baseline;
}
.element{
width: 20%;
float: left;
padding: 0% 1% 1% 1%;
}
This doesn't answer your CSS question. I did have some thoughts on the JavaScript, though. I'll offer my refactor for your consideration. Hopefully I interpreted your original logic correctly:
import React, { Component } from "react";
import { ListGroupItem } from "react-bootstrap";
import { LinkContainer } from "react-router-bootstrap";
import { API } from "aws-amplify";
import "./ProjectList.css";
export default class ProjectList extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
projects: [],
reducedView: true,
projectsNumber: 1000,
numberOfElementsToDisplay: 1000
};
}
async componentDidMount() {
try {
const projects = await this.fetchProjects();
console.log(projects);
this.setState({ projects });
} catch (e) {
alert(e);
} finally {
this.setState({ isLoading: false });
}
}
fetchProjects = () => {
return API.get("economics-endpoint", "/list");
};
handleClick = e => {
e.preventDefault();
this.setState({ reducedView: false });
};
render() {
const {
isLoading,
numberOfElementsToDisplay,
projectsNumber,
reducedView
} = this.state;
const projects = reducedView
? this.state.projects.slice(0, numberOfElementsToDisplay)
: this.state.projects;
return (
<div className="ProjectList">
<div className="projects">
{!isLoading && (
<React.Fragment>
<div className="element">
<LinkContainer to={`/econx/new`}>
<ListGroupItem className="new">
<div>+ Create New Project</div>
</ListGroupItem>
</LinkContainer>
{projectsNumber === 0 && (
<div className="errorMessage">
You don't have any existing projects yet.
</div>
)}
</div>
{projects.map((project, index) => (
<div className="element">
<ListGroupItem className="mainContainer">
<div>ProjectName#{index}</div>
</ListGroupItem>
</div>;
))}
</React.Fragment>
)}
</div>
</div>
);
}
}
This fixes your off-by-one issue by hopefully capturing your intentions as I understand them:
If it's not loading...
Show a "Create New Project" item
If they don't have any projects yet, show them a message
If they do have projects, create a new element for each one
It's worth considering whether your projectsNumber could be replaced with projects.length. If so, you can probably combine (2) and (3) above to be an either-or scenario: If they don't have projects, show a message, if they do, show the projects.

How to enable a dark theme by default, instead of toggle button?

I'm specifically looking at this site here:
https://coin.dance/
In the upper left corner there is a dark/light theme toggle button, and I wanted to know how to enable something like this by default(dark style would be enabled before light). I've been looking through the index.html, and all I can see of interest is this snippet of javascript:
<body class="dark">
<script type="text/javascript">
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
// Registration was successful
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
// registration failed :(
console.log('ServiceWorker registration failed: ', err);
});
}
function localStorageSave(key, value) {
if (supportsLocalStorage()) {
localStorage.setItem(key, JSON.stringify(value));
return true;
}
return false;
}
function localStorageLoad(key) {
if (supportsLocalStorage()) {
var value;
try {
value = JSON.parse(localStorage.getItem(key));
} catch (e) {
return false;
}
if (value) {
return value;
}
}
return false;
}
function supportsLocalStorage() {
try {
if (typeof localStorage !== 'undefined') {
try {
localStorage.setItem('cd_ls_test', 'yes');
if (localStorage.getItem('cd_ls_test') === 'yes') {
localStorage.removeItem('cd_ls_test');
return true;
} else {
return false;
}
} catch(e) {
return false;
}
}
} catch(e) {
return false;
}
return false;
}
if (supportsLocalStorage()) {
$('body').toggleClass('dark', localStorageLoad('dark'));
}
I'm interested because I like the overall theme of the site, and it's simplicity, but I wanted to know how it was done, and I cannot grasp where to start looking and editing.
You can easily do this with jquery just set a dark color background on your css by default and turn it on light color with button :
$(".button").click(function(){
if ($(this).hasClass("clicked")){
$(".bg").css("background-color","black");
$(this).removeClass("clicked");
}
else
{
$(".bg").css("background-color","white")
$(this).addClass("clicked")}
});
body{
margin:0px;
}
.bg{
height:100vh;
width: 100%;
background-color:black;
}
.button{
color:red;
position:absolute;
margin:0px;
cursor:pointer;
padding:20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bg">
<p class="button">Dark-light</p>
</div>

index.php is not receiving the JSON sent by the backbone Post

I've been trying to understand how Backbone works and communicates with the back-end code, and I have an issue of not being able to receive the JSON I send to my php file.
Here is the code:
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href='http://fonts.googleapis.com/css?family=Abel' rel='stylesheet' type='text/css' />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Understanding Backbone</title>
<style type="text/css">
body { padding: 0; margin: 0; background-color: #fff; }
h2 { font-family: Abel, sans-serif; margin: 0; padding: 0 0 5px 0;}
input { background-color: #ddd; border: 0; }
input:active { background-color: #bbb; }
#new-status { margin: 20px; padding: 20px; background-color: #67A9C3; }
#statuses { margin: 20px; padding: 20px; background-color: #92B456; }
</style>
</head>
<body>
<div id="new-status">
<h2>New monolog</h2>
<form>
<textarea id="status" name="status"></textarea>
<br />
<input type="submit" value="Post" />
</form>
</div>
<div id="statuses">
<h2>Monologs</h2>
<ul></ul>
</div>
<script src="js/jquery-min.js"></script>
<script src="js/underscore.js"></script>
<script src="js/backbone.js"></script>
<script src="js/main.js"></script>
</body>
</html>
JS:
var Status = Backbone.Model.extend({
url: 'api/index.php'
});
var Statuses = Backbone.Collection.extend({
model: Status
});
var NewStatusView = Backbone.View.extend({
events: {
"submit form": "addStatus"
},
initialize: function(options) {
this.collection.on("add", this.clearInput, this);
},
addStatus: function(e) {
e.preventDefault();
this.collection.create({ text: this.$('textarea').val() });
},
clearInput: function() {
this.$('textarea').val('');
}
});
var StatusesView = Backbone.View.extend({
initialize: function(options) {
this.collection.on("add", this.appendStatus, this);
},
appendStatus: function(status) {
this.$('ul').append('<li>' + status.escape("text") + '</li>');
}
});
$(document).ready(function() {
var statuses = new Statuses();
new NewStatusView({ el: $('#new-status'), collection: statuses });
new StatusesView({ el: $('#statuses'), collection: statuses });
});
index.php:
<?php
echo(var_dump($_POST));
?>
This is what I get for the response:
array(0) {
}
I've been breaking my head over this, so please HELP!
After some more research on stackoverflow(awesome community btw) I was able to find that backbone does not send straight post or get to the RESTful api, or whatever the code-behind might be, but instead it is a set of headers. So you have to poke around the $_SERVER global and find out what is being requested. You'll be able to find your request in the $_SERVER["REQUEST_METHOD"], than perform a switch/case to decide what you want to do with that request. The data being sent through (in backbone's case is always a JSON string) is in the HTTP body and to get it out I used the file_get_contents('php://input'), and decode the JSON so that php can work with it.
<?php
$requestMethod = $_SERVER["REQUEST_METHOD"];
switch ($requestMethod)
{
case 'POST': $data = json_decode(file_get_contents('php://input'), true);
echo $data;
break;
}
?>
#orangewarp, I really wanted to understand what was happening under the hood without using a RESTful php framework.
$raw_data = file_get_contents("php://input");
var_dump($raw_data);
if( !empty($raw_data) ){
$data = #json_decode($raw_data, true);
if( $data ){
var_dump($data);
}
}