Display Data Got From JSON In Reactjs In Table - ajax

Here I wrote A code which fetches data from API http://fcctop100.herokuapp.com/api/fccusers/top/recent and displays Data in Form Of Table Which Looks Like Below In My Case As You Can See is Repeating For Every
But I want To Make It Look Like
Here Is What I Did So Far
var MainBox = React.createClass({
render:function(){
return(
<App/>
);
}
});
var App = React.createClass({
//setting up initial state
getInitialState:function(){
return{
data:[]
};
},
componentDidMount(){
this.getDataFromServer('http://fcctop100.herokuapp.com/api/fccusers/top/recent');
},
//showResult Method
showResult: function(response) {
this.setState({
data: response
});
},
//making ajax call to get data from server
getDataFromServer:function(URL){
$.ajax({
type:"GET",
dataType:"json",
url:URL,
success: function(response) {
this.showResult(response);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return(
<div>
<Result result={this.state.data}/>
</div>
);
}
});
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div>
{result}
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
});
ReactDOM.render(
<MainBox />,
document.querySelector("#app")
);
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>React Tutorial</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<div id="app"></div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</body>
</html>

The following should list all your items as a single row in your table, and only give you one table. One tip is to not use the index as the key for your map function. It's better to use some natural key or identifier in your result, some kind of id that will enable React better comparison of the components. A blog post describing this and some documentation.
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
{result}
</tbody>
</table>
</div>
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
);
}
});

Related

POST http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not Found) after ajax call

My server giving me the response as following
when my ajax call to the same page. Before Ajax call everything is working fine on console but after ajax call and updating database, this error is occurring. I think my Ajax_url is not correct but I want to get ajax data on same page that name is "custom_Settings.php" as mentioned in url.
Please help me to solve this error.
Thanks!
jquery-3.4.1.min.js:2 POST
http://localhost/DemoWebsite/wp-admin/custom_Settings.php 404 (Not
Found)
JS
<script type="text/javascript">
var $j = jQuery.noConflict();
$j(document).ready(function(){
saveNewPositions();
});
function saveNewPositions(){
var positions = [];
$j('.updated').each(function(){
positions.push([$j(this).attr('data-index'), $j(this).attr('data-position')]);
$j(this).removeClass('updated');
});
$j.ajax({
url: 'custom_Settings.php',
method: 'POST',
dataType: 'text',
data: {
update: 1,
positions: positions
}, success: function(response){
console.log(response);
}
});
}
</script>
PHP
function wp_pageOrdering_field_settings(){
global $wpdb;
if (isset($_POST['update'])) {
foreach($_POST['positions'] as $position){
$index = $position[0];
$newPosition = $position[1];
}
$wpdb->update(
'wp_page_settings',
array('page_order' => $newPosition),
array('ID' => $index)
);
wp_die();
}
HTML
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title></title>
</head>
<body>
<div class="container" style="margin-top: 100px;">
<div class="row justify-content-center">
<div class="col-md-4 col-md-offset-4">
<table class="table table-stripped table-hover table-border">
<head>
<tr>
<td>Page Title</td>
</tr>
</head>
<tbody>
<?php
$var = get_option('Accessable_Pages');
$list = implode(",", $var);
$newRes = $wpdb->get_results("SELECT ID, post_title, page_order FROM wp_page_settings WHERE ID IN ($list) ORDER BY page_order ASC",ARRAY_A);
if($newRes){
foreach ($newRes as $value1 ) {
echo '
<tr data-index="'.$value1['ID'].'" data-position="'.$value1['page_order'].'">
<td>'.$value1['post_title'].'</td>
</tr>
';
}
}
?>
</tbody>
</table>
</div>
</div>
</div>

angular js ng-repeat is not working

In ng-repeat do not show any data but the data is available in response.
The loop is not working properly.
<html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.passward}}</td>
</tr>
</form>
</div>
</body>
console.log(response) show the data in console
<script>
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http) {
$http.get("show.php")
.then(function (response) {
$scope.names=response.data;
console.log(response)
} );
});
</script>
</html>
So I tried your code and have a few corrections, the reason you are not able to see any data may be due to, usage of tr and td tags without the table tag as the parent, please check my below code, where I have added the table and tbody tags, Also, inorder to simulate a http request, I have use the $timeout which will set the data after 3 seconds, please study the example and implement it to your code!
var app = angular.module('myApp', []);
app.controller('thecontroller', function($scope, $http, $timeout) {
var data = [{
name: "one",
email: "one#one.com",
password: "1234"
}, {
name: "two",
email: "two#two.com",
password: "1234"
}, {
name: "three",
email: "three#three.com",
password: "1234"
}, ]
$timeout(function() {
$scope.names = data;
}, 3000);
/*$http.get("show.php")
.then(function(response) {
$scope.names = response.data;
console.log(response)
});*/
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="thecontroller">
<form>
<table>
<tbody>
<tr ng-repeat="x in names">
<td>{{x.name}}</td>
<td>{{x.email}}</td>
<td>{{x.password}}</td>
</tr>
</tbody>
</table>
</form>
</div>
</body>
</html>

Ajax call not working on datatables pages,except first page

i am using datatables.And on the table there is button on each row.
When I click on the trash button,ajax works only for the first 10 row.
But when I move on to next pages it does not work anymore.
Here is my table code:
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<table id="example" class="table table-bordered">
<thead>
<tr>
<th class="success">Id</th>
<th class="success">Image</th>
<th class="success">Title</th>
<th class="success">Action</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect,"SELECT * FROM movie");
while ($result = mysqli_fetch_row($query)){
echo'
<tr>
<td>'.$result[0].'</td>
<td><img class="img-responsive" style="max-height:50px;" src="'.$result[5].'"></td>
<td>'.$result[1].'</td>
<td>
<div class="btn-group" data-toggle="buttons">
<label id="remID" class="btn btn-sm btn-default">
<span class="text-danger glyphicon glyphicon-trash"></span>
</label>
<label class="btn btn-sm btn-default">
<span class="text-primary glyphicon glyphicon-edit"></span>
</label>
</div>
</td>
</tr>
';
echo'
<script>
$(document).ready(function(){
$("#remID").click(function(){
$.post("remMovie.php",
{
id:"'.$result[0].'"
},
function(data,status){
alert(status);
});
});
});
</script>
';
}
?>
</tbody>
</table>
Here is my PHP part of ajax action:
<?php
include('adminchk.php');
include('config.php');
$movieID = $_POST['id'];
$query = mysqli_query($connect,"DELETE from movie where id='$movieID'");
if ($query){
echo"movie deleted";
}
else {
echo"ERROR!";
}
?>
I dont know why this is happening.I want the trash button to work for every row of datatable.
To execute any Code after the Data Table has been paginated (basically redrawn), you need to add fnDrawCallback function inside .dataTabale() method. All codes written inside the Callback function will work after the table has been redrawn. Here is an example...
$(document).ready( function() {
$('#example').dataTable({
"fnDrawCallback": function( oSettings ) {
// Write any code (also ajax code that you want to execute)
// that you want to be executed after
// the table has been redrawn
}
});
});
You should try something like fnDrawCallback event.
Here is the doc : http://legacy.datatables.net/usage/callbacks#fnDrawCallback
When the datable change, you bind the buttons with the function you want.
JS :
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
}
} );
} );

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

JavaScript to get user input from editable table cell and send to server via json

I created a table with five columns dynamically. Two (the second and third column) of the five columns should be editable on the fly. Each time when user click on one the editable table cell, JavaScript should catch the user input and send the data to the server in json format. I have problem catch the user input and send to the server. Please help. This is my sample code -
<!DOCTYPE html>
<html>
<head>
<title>Editable table</title>
<style type="text/css" title="currentStyle">
#import "css/table.css";
</style>
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
</head>
<body id="dt_example">
<div id="container">
<div class="full_width big">
Data table<br />
</div>
<div class="editab">
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<td>00123</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
<tr>
<td>00234</td>
<td onClick="editTableCell(this)">B20</td>
<td onClick="editTableCell(this)">$2,500.00</td>
<td>3.99 %</td>
<td>160</td>
</tr>
<tr>
<td>00345</td>
<td onClick="editTableCell(this)">C40</td>
<td onClick="editTableCell(this)">$3,500.00</td>
<td>3.99 %</td>
<td>180</td>
</tr>
<tr>
<td>00456</td>
<td onClick="editTableCell(this)">A20</td>
<td onClick="editTableCell(this)">$4,500.00</td>
<td>3.99 %</td>
<td>200</td>
</tr>
<tr>
<td>00567</td>
<td onClick="editTableCell(this)">B30</td>
<td onClick="editTableCell(this)">$5,500.00</td>
<td>3.99 %</td>
<td>225</td>
</tr>
<tr>
<td>00678</td>
<td onClick="editTableCell(this)">C10</td>
<td onClick="editTableCell(this)">$6,500.00</td>
<td>3.99 %</td>
<td>250</td>
</tr>
<tr>
<td>00789</td>
<td onClick="editTableCell(this)">A30</td>
<td onClick="editTableCell(this)">$7,500.00</td>
<td>3.99 %</td>
<td>300</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript">
var SelectState = false;
var SelectedElement = null;
var TextInput = null;
var CellText = null;
var txt = "test";
var idcount = 0;
function editTableCell( e ){
if ( SelectState == false ){
SelectedElement = e;
CellText = e.innerHTML;
e.innerHTML = "";
var objInput = document.createElement("input");
objInput.type = 'text';
objInput.value = CellText;
objInput.id = "txt" + idcount++;
objInput.onkeypress = editTextBox;
objInput.size = 15;
TextInput = objInput;
e.appendChild(objInput);
SelectState = true;
} else if (e != SelectedElement) {
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
function editTextBox( e ){
if (navigator.appName == "Microsoft Internet Explorer"){
e = window.event;
key = e.keyCode;
}
else if (navigator.appName == "Netscape"){
key = e.which;
}
if ( key == 13 ){
SelectedElement.innerHTML = TextInput.value;
SelectState = false;
}
else if ( key == 27 ){
SelectedElement.innerHTML = CellText;
SelectState = false;
}
}
/* var attrName = "":
var attrValue = "";
if ($('#test1')
{
attrName= "editField01";
attrValue = $(#test1).val();
}
if ($('#test2')
{
attrName= "editField02";
attrValue = $(#test2).val();
}
if ($('#test3')
{
attrName= "editField03";
attrValue = $(#test3).val();
}
var values = '{"' + attrName + '":' + attrValue + '}';
$.ajax({
url: serverUrl + "/abc/contract/" + poolId,
async: false,
type: "PUT",
data: JSON.stringify(values),
dataType: 'json',
processData: false,
contentType: 'application/json',
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
error: function(err) {
alert("Failed to update the attribute");
htmlErrorDialog(err.responseText);
}
});*/
function showResponse(json) {
if(json.success){
// handle successful response here
alert("user input from column sent successfully!");
} else {
// handle unsuccessful response here
alert("user input fail to send. Please try again");
}
}
</script>
</body>
</html>
You're not actually passing the json data to showResponse:
success: showResponse(json) {
// TODO: What info is returned in the data structure?
showResponse;
},
Pass it along as so, and make sure that json is an actual object and that you don't need to parse it first:
success: function(json) {
// check that json is an actual object via an alert
// alert(json);
showResponse(json);
},
EDIT: Okay after a lot of working around, I have a simple test case for making the fields editable. Please note it uses jquery, and comments are inline:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<!-- Date: 2011-05-10 -->
</head>
<body>
<form>
<table border="1">
<thead>
<tr>
<th>Contract Number</th>
<th>Current Status</th>
<th>Sale Balance Amount</th>
<th>Interest Rate</th>
<th>Discount</th>
</tr>
</thead>
<tbody>
<tr>
<!-- The "identifier" class makes it so we have an id
to pass to our ajax script so we know what to change -->
<td class="identifier">00123</td>
<td class="editable">A30</td>
<td class="editable">$1,500.00</td>
<td>3.99 %</td>
<td>140</td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
// bind our event handler to all td elements with class editable
$('td.editable').bind('click', function() {
// Only create an editable input if one doesn't exist
if(!$(this).has('input').length) {
// Get the text from the cell containing the value
var value = $(this).html();
// Create a new input element with the value of the cell text
var input = $('<input/>', {
'type':'text',
'value':value,
// Give it an onchange handler so when the data is changed
// It will do the ajax call
change: function() {
var new_value = $(this).val();
// This finds the sibling td element with class identifier so we have
// an id to pass to the ajax call
var cell = $(this).parent();
// Get the position of the td cell...
var cell_index = $(this).parent().parent().children().index(cell);
// .. to find its corresponding header
var identifier = $('thead th:eq('+cell_index+')').html();
//ajax post with id and new value
$(this).replaceWith(new_value);
}
});
// Empty out the cell contents...
$(this).empty();
// ... and replace it with the input field that has the value populated
$(this).append(input);
}
});
</script>
</body>

Resources