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
Related
I'm trying to parse an API json file to an HTML table, i posted the contents of the JSON API file in here for reference: https://pastebin.com/raw/jWaET2TU
For start i wanted to make it simple, just 3 values.
ID | NAME | DESCRIPTION
I can print all data, then when I try to fetch individual values or i get an error or a blank page.
This is all i have till now, but can't figure out what's wrong in the code.
.HTML
<table id="personDataTable">
<tr>
<th>ID</th>
<th>NAME</th>
<th>DESCRIPTION</th>
</tr>
</table>
<style>
table {
border: 2px solid #666;
width: 100%;
}
th {
background: #f8f8f8;
font-weight: bold;
padding: 2px;
}
</style>
.JS
$.ajax({
url: 'https://apiexample.com',
type: "get",
dataType: "json",
success: function(data) {
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row);
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
row.append($("<td>" + rowData.headline + "</td>"));
}
I'm struggling with a detail on a project and I can't see any solution. We're getting datas writen by an Ai from a MySQL bdd and showing them as text in a fancy way http://82.223.18.239/writing.php
As you can see, the text isn't properly justified in the begining, it is when the writing process hit the bottom of the page, and I don't know how to fix this. When "white-space: pre-wrap" isn't used, everything work fine but I lose the line jump. Any help ?
Our wip code
<head>
<div id="header"></div>
<div id="body"></div>
<div id="footer"></div>
<script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style type="text/css">
#myTable{
width:"90%";
min-width:250px;
white-space: pre-wrap;
word-wrap:break-word;
position:absolute;
border:solid 0px;
top:200px;
left:720px;
right:720px;
bottom:50px;
font-family:"Times New Roman", Times, serif;
text-align:justify
}
#body {
padding-bottom:60px;
height:2px;
}
</style>
</head>
<body>
<div id="myTable"> <div>
<script type="text/javascript">
var skip = 0;
function get_data(index) {
$.ajax({
url : 'getData.php',
type : 'POST',
data: ({"skip":skip}),
success : function(data) {
if(data && data.trim()!='') {
skip = skip+1;
showText("#myTable", data, 0, 2);
}
else {
setTimeout(function () { get_data(skip); }, 30000);
}
},
error : function(request,error)
{
alert("Request error : "+JSON.stringify(request));
}
});
}
function showText(target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
else {
get_data(skip);
}
}
//var period = 10000; //NOTE: period is passed in milliseconds
get_data(skip);
//setInterval(page_refresh, period);
</script>
</body>
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.
I'm trying to hide the search result when the search is back to empty. Is there a way to do that?
Everything is working fine. I just don't like to see the search result of the last letter. Example if you type A and you empty the input box. The result will stay there.
Thanks to the person that know the answer.
<div id="result"></div> should be the one to be blocked.
My CSS code for the search:
.content{
width:275px;
}
#searchid
{
width:275px;
border:solid 1px #000;
padding:10px;
font-size:14px;
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px;
}
#result
{
position: absolute;
width:275px;
padding:10px;
display:none;
border-top:0px;
overflow:hidden;
border:1px #CCC solid;
background-color: white;
}
.show
{
padding:10px;
border-bottom:1px #999 dashed;
font-size:15px;
height:50px;
}
.show:hover
{
background:lightgrey;
color:#FFF;
cursor:pointer;
}
My HTML Code for the search input box:
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search"/>
<div id="result"></div>
</div>
My Search Display are like that:
<div class="show" align="left">
<span class="name">' . $rowsTitle['title'] . ' ' . $label . "<br>".
</div>
JQuery that I use to get the search information:
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = 'search='+ searchid;
if(searchid!='')
{
$.ajax({
type: "GET",
url: "/sheridan/script/search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$('#searchid').click(function(){
jQuery("#result").fadeIn();
});
});
I forgot to add the JQuery function that I use to get the information out of the database.
I haven't cleared the result div as you are filling it with data when there is a letter.
$(".search").on("keyup", function(){
if($(this).val()==""){
$("#result").hide();
}
else {
$("#result").show();
}
});
Fiddle
You will have to use JavaScript to perform this action as CSS does not support any way to identify empty input fields.
I have chosen to use jQuery for this example but it could easily be achieved using no external libraries.
$('.search').on('input', function() {
$('#result').toggle( $(this).val() );
});
JSFiddle
Use JQuery
$( "#searchid" ).keypress(function() {
var search = $( "#searchid" ).val()
if(search==''){
$("#result").html();
}
});
Try following code:
$(document).ready(function(){
$("#searchid").keypress(function(){
var len = $("#searchid").val().length;
if (len <= 0)
{
//make result blank
$("#result").hide();
}
});
});
edit:
use $("#result").hide();
or
$("#result").css("display","none");
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);
}
}