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

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);
}
}

Related

Attributes in Web Components do not show up

This is my HTML with a custom web component.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Advanced ToDo App with Web Components</title>
</head>
<body>
<todo-item todo="Walk the dog" data-id="1"></todo-item>
<script src="../static/listItems.js"></script>
</body>
</html>
This is my JS file where I set up the component.
const template = document.createElement("template");
template.innerHTML = `<style>
h4 {
color: white;
font-size: 14px;
display: block;
padding: 10px 5px;
background: orange;
}
</style>
<div class="todo-item">
<h4></h4>
</div>
`;
class TodoItem extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
}
connectedCallback() {
this.shadowRoot
.querySelector(".todo-item")
.addEventListener("click", () => {
console.log(this.getAttribute("data-id"));
});
}
}
window.customElements.define("todo-item", TodoItem);
// Über Daten iterieren
const body = document.querySelector("body");
const dummydata = [
{ id: 1, description: "Walk the dog" },
{ id: 2, description: "Play football" }
];
for (item of dummydata) {
console.log(item.description);
todoItem = document.createElement("todo-item");
todoItem.setAttribute("todo", item.description); # Does not work!
todoItem.setAttribute("data-id", item.id);
body.appendChild(todoItem);
}
The component in the HTML works perfectly fine, but when I try to create them dynamically with JavaScript setting the attributes seem not to work. The "todo"-text does not get displayed. Is setting this "todo" attribute invalid?
Got it - the attribute has to be set inside the connectedCallBack function. When doing it before the attribute valu will be null
connectedCallback() {
this.shadowRoot
.querySelector(".todo-item")
.addEventListener("click", () => {
console.log(this.getAttribute("data-id"));
});
this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
}

How to make the image swap every second

This code will turn the bulb on/off but i want to make the lightbulbs keeps flashing. I've tried different methods and nothing works
<!DOCTYPE html>
<html>
<body>
<img id="bulb" onclick="switch()" src="off.png" width="100" height="180">
<p>On/Off</p>
<script>
function
switch () {
var image = document.getElementById('Bulb');
if (image.src.match("on")) {
image.src = "off.png";
} else {
image.src = "on.png";
}
}
</script>
</body>
</html>
Here is an example, using setInterval(). I have swapped the image to a div thats background changes color, but same principal applies.
I think its also worth pointing out that you could also do this with a css animation and then just use javascript to toggle the class onto the element. But assuming you just wanna stick to JS for now:
let flashInterval = null;
let flashSpeed = 100;
let bulb = document.getElementById('bulb');
function toggleBulb() {
if (bulb.classList.contains('on')) {
bulb.classList.remove('on');
} else {
bulb.classList.add('on');
}
}
function flashBulb() {
if (flashInterval === null) {
flashInterval = setInterval(() => {
toggleBulb();
}, flashSpeed);
} else {
clearInterval(flashInterval);
flashInterval = null;
}
}
document.getElementById('toggleBlub').addEventListener('click', toggleBulb);
document.getElementById('toggleFlash').addEventListener('click', flashBulb);
#bulb {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid #ccc;
background: transparent:
}
.on {
background: #fcba03;
}
<div id="bulb" class=""></div>
<br>
<button id="toggleBlub">Bulb On/Off</button>
<br><br>
<button id="toggleFlash">Flash On/Off</button>
in my opinion, don't use setInterval but u can use a CSS animation rather than it.
You should know about js event and js reserve keyword and be sure to use good code editor so that you can see your error.
I see you trying to keep flashing but you used onclick event that is clickable it will not flashing.
here is the code below, which you want,
<!DOCTYPE html>
<html>
<body>
<img id="bulb" src="off.jpg" width="100" height="180">
<p>On/Off</p>
<script>
var myImage = document.querySelector('#bulb');
var update = setInterval(myUpdate, 1000);
function myUpdate() {
setTimeout(() => {
if (myImage.src.match('off.jpg')) {
myImage.src = 'on.jpg'
} else {
myImage.src = 'off.jpg'
}
}, 500)
}
</script>
</body>
</html>
or you can use onclick event, when you click than it will start flashing
here is the code below
<!DOCTYPE html>
<html>
<body>
<img id="bulb" onclick="mySwitch(this)" src="off.jpg" width="100" height="180">
<p>On/Off</p>
<script>
function mySwitch(myImage) {
var update = setInterval(myUpdate, 500);
function myUpdate() {
setTimeout(() => {
if (myImage.src.match('off.jpg')) {
myImage.src = 'on.JPG'
} else {
myImage.src = 'off.jpg'
}
}, 100)
console.log(myImage)
}
}
</script>
</body>
</html>
I changed your function name to switchBulb because switch is reserved
var intervalID = window.setInterval(switchBulb, 1000);
function switchBulb() {
var image = document.getElementById('bulb');
if (image.src.match("on")) {
image.src = "off.png";
} else {
image.src = "on.png";
}
}

Ajax - JSON - Beginner

The code below "has been" successfully returning the users.json file in an html table. I modified the json, but the code continues to return the original json. I delete the file, then add it back and then it can't find the file. I have cleared what I thought was the browser cache, to no avail.
Question #1: Where does the server "look" for the users.json file on my web server?
Question #2: How can I assure I'm getting the latest changes, when the user clicks the button?
<script>
function CreateTableFromJSON() {
$.ajax({
type: "get",
url: ***"users.json",***
dataType: "json",
success: function (jsonData) {
var table = $('table');
table.empty();
var name = document.getElementById('name').value.toUpperCase();
$.each(jsonData, function (key, item) {
var table_row = $('<tr>');
$.each(item, function (itemKey, itemValue) {
if (key == 0) {
table.append($('<th>', { html: itemKey }));
}
if (item.LastName.startsWith(name)) {
table_row.append($('<td>', { html: itemValue }));
}
});
table.append(table_row);
}
);
},
error: function () {
alert("json not found");
}
});
}
</script>
<style>
th, td, p, input {
font: 14px Verdana;
}
table, th, td {
border: solid 1px #DDD;
border-collapse: collapse;
padding: 2px 3px;
text-align: left;
}
th {
font-weight: bold;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<input type='text' id='name' placeholder='Search Initial ' />
</div>
<p id="showData"></p>
<table id="tbl"></table>
</body>
</html>
Not sure what you mean by your first question. It will "look" at whatever location is in your url.
For your second question: you want to turn off browser caching. Add "cache: false", eg
type: "get",
url: ***"users.json",***
dataType: "json",
cache: false

AngularJS Compiling Model Like StackOverflow

Good day everyone, right now i'm trying to create a textbox like this (stackoverflow textbox) using angularJS .. but im having difficulties on doing so , i have to replace **SOME TEXT HERE** to strong SOME TEXT HERE /strong here's my code ..
$(document).ready(function() {
var app = angular.module("appModule", [], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
/* ALLOW ANGULAR TO RENDER HTML OUTPUT */
app.directive('compile', ['$compile', function($compile) {
return function(scope, element, attrs) {
scope.$watch(function(scope) {
return scope.$eval(attrs.compile);
},
function(value) {
element.html(value);
$compile(element.contents())(scope);
}
)
};
}]);
/* CONTROLLER FOR PROFILE TICKER */
app.controller("ProfileTickerController", function($rootScope, $scope, dataService, FileUploader) {
// INITIAL VALUES FOR PROFILE TICKER
$scope.ticker = '';
$scope.previous = '';
$scope.edit = false;
$scope.editTicker = function() {
$scope.previous = $scope.ticker;
if ($scope.ticker == "<span class='color-light-grey'>Ticker not set</span>") {
$scope.ticker = "";
}
$scope.edit = true;
}
$scope.cancelEdit = function() {
$scope.ticker = $scope.previous;
$scope.edit = false;
}
$scope.saveTicker = function() {
if ($scope.ticker == "") {
$scope.ticker = "<span class='color-light-grey'>Ticker not set</span>";
}
$scope.edit = false;
}
$scope.$watch('ticker', function() {
if ($scope.ticker == undefined) {
$scope.ticker = "";
}
})
$scope.init = function(id) {
var postData = 'profileID=' + id;
// SETUP AJAX CONFIG
var config = {
"method": "POST",
"url": "ajax/getTicker.php",
"data": postData,
"headers": {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded'
}
};
// AJAX TO GET PROFILE TICKER
dataService.ajaxThis(config).then(function mySuccess(response) {
// CHECK IF AJAX SUCCESSFUL
if (response.status != 200) {
console.log('Ajax error! Profile ticker not fetched. Please reload the page and try again.');
} else {
// GET PROFILE TICKER
if (response.data == "") {
$scope.ticker = "<span class='color-light-grey'>Ticker not set</span>";
} else {
$scope.ticker = response.data;
}
}
});
}
$scope.$on('profileLoaded', function(e, id) {
$scope.init(id);
});
});
})
.textarea-non-resize {
resize: none;
}
.grey-box {
background: #efefef;
border: 1px solid #dedede;
padding: 10px;
}
#ticker {
height: 42px;
background-color: #fff;
border-top: 1px solid #dedede;
border-bottom: 1px solid #dedede;
font-family: 'Oswald', sans-serif;
text-transform: uppercase;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
</head>
<script src="script.js"></script>
<body ng-app="appModule" class="ng-scope">
<div class="row">
<div class="col-xs-12 col-sm-12" ng-controller="ProfileTickerController">
<div class="form-group">
<label for="subject">
Ticker
<span ng-show="!edit">
<i class="glyphicon glyphicon-pencil"></i>
</span>
<span ng-show="edit">
<i class="glyphicon glyphicon-ok"></i>
<i class="glyphicon glyphicon-remove"></i>
</span>
</label>
<textarea name="ticker_edit" id="ticker_edit" class="form-control textarea-non-resize" ng-model="ticker" ng-show="edit" placeholder="Customize your ticker here" required cols="50" rows="4" style="margin-bottom: 10px;"></textarea>
<div class="grey-box">
Preview:
<div id="ticker" class="text-center">
<h3 compile="ticker"></h3>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
There's a script error here, but it's working fine in my computer. So anyway how would i replace the said string above using that compiler ?
How about using a Regex to replace the value before you inject it into the element's HTML?
// replace bold text
value = value.replace(/\*\*(.*)\*\*/g, "<strong>$1</strong>");
The above is a simple example and you might need to tweak it a bit to fit your purpose, but the general idea is there.

HTML Progress Bar

How would I add a progress bar to my website, that looks like the one on this website?
Progress Example
It looks like the Apple one!
<progress max="Maximum Value" value="Initial Value" />
See this for more details.
Note that this only works for browsers that support HTML5.
You can use jQuery instead. There in no restriction of HTML5. Also you can apply styles
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Progressbar - Custom Label</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.progress-label {
float: left;
margin-left: 50%;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
}
</style>
<script>
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "Complete!" );
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 99 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 3000 );
});
</script>
</head>
<body>
<div id="progressbar"><div class="progress-label">Loading...</div></div>
</body>
</html>
Source code available here http://jqueryui.com/progressbar/