I want to use AJAX to show a form when a user clicks on record to edit it.
I know and capable of using AJAX.
But now i want to call a method of a class in PHP. And thats where im stuck.
Below some code sample of my controller:
public function start() {
$users = $this->usersmodel->getAllUsers();
$firstRow = new HtmlTableFirstRow();
$table = new HtmlTable($users,$users,$firstRow);
$table->setCss('table1');
echo $table->show();
}
public function editRecord() {
$recordId = $this->getFirstParameter();
$user = $this->usersmodel->getUserById($recordId);
$tableId = $this->fieldModel->getTableIdByName('users');
$inputs = $this->fieldModel->getFields($tableId);
$collection = new Fieldcollection($inputs);
foreach($collection as $inputs) {
for($i = 0; $i < count($inputs); $i++) {
foreach($user as $userInfo) {
$inputs[$i]->setValue($userInfo[$i]);
}
}
}
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
}
As you can see i have 2 functions, start which shows all the records. And when a user clicks on editrecord a form will show.
I want to show the form in a popup, without a page refresh.
What is the best way to handle this?
You can make a page for manage ajax requests like this:
server.php :
if(isset($_GET['request'])){
switch($_GET['request']){
case 'get-form' :
$userId = $_GET['userId'];
$form = new Form($collection);
$form->setLabels();
$form->setCss('form1');
echo $form->show();
break;
}
}
in client page you can send ajax request & get their result via jquery :
client.html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<table>
<tr data-userId="1">
<td>User 1</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="2">
<td>User 2</td>
<td><button class="edit">Edit Record</button></td>
</tr>
<tr data-userId="3">
<td>User 3</td>
<td><button class="edit">Edit Record</button></td>
</tr>
</table>
<div class="popup">
</div>
</body>
<script src="jquery.js"></script>
<script src="ajax.js"></script>
</html>
ajax.js :
(function(){
$('.popup').hide();
$('.edit').on('click',function(){
var userId = $(this).parent().parent().data('userId');
$.get('server.php',{request : 'get-form' , userId : userId},function(form){
$('.popup').empty().append(form).fadeIn();
});
});
})();
I hope this helps you
Related
Im trying to read data from my database to my view in my application in the web browser. Problem is that I can't get any data to show. The data is shown in the console, so it's connecting to the database but somehow it doesn't print the data in the view.
Data is showing in console but not in view
playerDetails.php
include 'database_connections.php';
$sql = "SELECT idPlayer, PlayerName, PlayerEmail, PlayerPassword,
PlayerTeam FROM Players";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
} else {
echo "0 results";
}
mysqli_close($conn);
echo json_encode($data);
angular-script.js (Controller)
var crudApp = angular.module('crudApp',[]);
crudApp.controller('DbController', function ($scope, $http) {
$http.get("DatabaseFiles/playerDetails.php")
.then(function (response) {$scope.players = response.data;
console.log(response.data)
});
});
HTML
<!doctype html>
<html ng-app='crudApp'>
<head>
<title>Crud app</title>
<script src="js/jQuery/jquery.min.js"></script>
<script src="lib/angular/angular.min.js"></script>
</head>
<body>
<div ng-controller="DbController">
<table >
<tr>
<th>Player ID</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
<th>Team</th>
</tr>
<tr ng-repeat="players in Players | orderBy:'-created'">
<td>{{players.idPlayer}}</td>
<td>{{players.PlayerName}}</td>
<td>{{players.PlayerEmail}}</td>
<td>{{players.PlayerPassword}}</td>
<td>{{players.PlayerTeam}}</td>
</tr>
</table>
</div>
<script src="js/angular-script.js"></script>
</body>
SOLVED
Im not sure what caused the problem but I created a new database and a new project and did the following changes to my PlayerController.js (former "angular-script.js") and index.html
PlayerController.js
var app = angular.module('crudApp', []);
app.controller('mainController', function($scope, $http) {
$http.get('PlayerRead.php').then(function(response) {
$scope.users = response.data;
console.log(response.data);
});
});
HTML
<!doctype html>
<html >
<head>
<title>Crud app</title>
<script
src="https://ajax.googleapis.com/ajax/libs/
angularjs/1.6.4/angular.min.js"
></script>
</head>
<body ng-app="crudApp" ng-controller="mainController">
<table>
<tr>
<th>Player ID</th>
<th>Name</th>
<th>Email</th>
<th>Team</th>
</tr>
<tr ng-repeat="user in users track by $index">
<td>{{user.PlayerID}}</td>
<td>{{user.PlayerName}}</td>
<td>{{user.PlayerEmail}}</td>
<td>{{user.PlayerTeam}}</td>
</tr>
</table>
<script src="PlayerController.js"></script>
</body>
Make it as below line, as it is case sensitive.
<tr ng-repeat="player in players | orderBy:'-created'">
<td>{{player.idPlayer}}</td>
<td>{{player.PlayerName}}</td>
<td>{{player.PlayerEmail}}</td>
<td>{{player.PlayerPassword}}</td>
<td>{{player.PlayerTeam}}</td>
</tr>
It should be players in players | orderBy:'-created'
How can i run search function? i cant display the any result with this code and i don't know how to handle this class and function.. i'm a newbie with this kind of code..please review my codes....thanks!!!
<?php
$txtsearch = $_POST['txtsearch'];
class BlogController{
public function search($txtsearch){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$txtsearch' ";
$result = $mysqli->query($display_query);
}
}
if(isset($_POST["btnsearch"])){
echo BlogController::search();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
Create New Blog<br>
<form action="function.php" method="post">
<input text-align:right type="text" name="txtsearch" placeholder="search">
<input type="submit" name="btnsearch" value="Search">
<table border="1" width="60%" cellpadding="2" cellspacing="0">
<thead>
<tr>
<th width="5%">ID</th>
<th width="20%">Title</th>
<th width="20%">Author</th>
<th width="40%">Content</th>
<th width="15%">Action</th>
</tr>
</thead>
<tbody>
<?php while($blog = $result->fetch_object()): ?>
<tr>
<td><?php echo $blog->id?></td>
<td><?php echo $blog->title?></td>
<td><?php echo $blog->author?></td>
<td><?php echo $blog->content?></td>
<td>
Edit
<a class ="btn_del" href="delete.php?blog_id=<?php echo $blog->id;?>">Delete</a>
</td>
</tr>
<?php endwhile?>
</tbody>
</table>
<script type="text/javascript">
$(function(){
$(".remove-btn").on('click',function(){
var is_confirm = confirm("Do you want to delete record?");
if(is_confirm){
window.location = $(this).attr('href');
}
return false;
});
});
</script>
</form>
</body>
</html>
Try this :
class BlogController{
public $txtsearch;
function __construct($search) {
$this->$txtsearch = $search;
}
public function search(){
$mysqli = new mysqli("localhost","root","","sample_db");
$display_query = "SELECT * FROM `tb_blogs` WHERE id='$this->$txtsearch' ";
$result = $mysqli->query($display_query);
return $result;
}
}
Create an instance and then call the function search
$myclass = new BlogController($_POST['txtsearch']); //pass value to the construct function
print_r($myclass->search()); // will return an array
I am trying to incorporate a code that will allow me to assign a class to a table that is "hoverme" then once a user hovers over that cell, it then does an ajax query to using the data-attribute with the information stored in there to a google search.
here is a mock up table:
<table>
<thead>
<tr><td>Test</td><td>Name</td></tr>
</thead>
<tbody>
<tr><td data-info="Samsung NP200A5B" class="hoverme">ABC123</td><td>Test Name</td> </tr>
</tbody>
</table>
Once a user hovers over the name abc123 it should show a pic above it of what is in the data-info tag.
I am not sure of how the jquery is going to work nor do i know if this is even going to work because everything is generated from a MySQL database.
here is my php code:
<?php
$qry = "SELECT * FROM `assets` WHERE cust_id='$custID'";
$rs = mysqli_query($mysqli,$qry) or die("Error: ".mysqli_error($mysqli));
if(mysqli_num_rows($rs) > 0)
while($rowa = mysqli_fetch_array($rs)) {
echo '
<tr>
<td>'.$rowa['asset_tag'].'</td>
<td>'.ucwords ($rowa['type']).'</td>
<td>'.ucwords ($rowa['vendor']).'</td>
<td>'.ucwords ($rowa['model']).'</td>
<td>'.ucwords ($rowa['platform']).'</td>
<td>'.ucwords ($rowa['location']).'</td>
<td>'.ucwords ($rowa['status']).'</td>
<td>'.ucwords ($rowa['user']).'</td>
<td><a data-toggle="modal" href="#myModal" id="'.$rowa['id'].'">View</a></td>
<td>Edit</td>
<td>'?> <?php if($rowa['del_flag'] == 0){ echo' Delete'; }else{ echo 'Undo Delete'; }?> <?php echo '</td>
<td><span class="glyphicon glyphicon-qrcode"></span></td>
</tr>'.PHP_EOL;
}else
echo "
<tr>
<td>No assets found</td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr> ".PHP_EOL;
?>
One last thing i should mention is i am using Jquery's DataTable.
This can be through the Google Image Search API, but with the daily usage limit (or pay $5 per 100 search).
See: https://developers.google.com/image-search/
Even using this API, you cannot ensure that the every searched image matches as the one you expecting to show in your page.
Sample API:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Search API Sample</title>
<script src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('search', '1');
var imageSearch;
function addPaginationLinks() {
// To paginate search results, use the cursor function.
var cursor = imageSearch.cursor;
var curPage = cursor.currentPageIndex; // check what page the app is on
var pagesDiv = document.createElement('div');
for (var i = 0; i < cursor.pages.length; i++) {
var page = cursor.pages[i];
if (curPage == i) {
// If we are on the current page, then don't make a link.
var label = document.createTextNode(' ' + page.label + ' ');
pagesDiv.appendChild(label);
} else {
// Create links to other pages using gotoPage() on the searcher.
var link = document.createElement('a');
link.href="/image-search/v1/javascript:imageSearch.gotoPage("+i+');';
link.innerHTML = page.label;
link.style.marginRight = '2px';
pagesDiv.appendChild(link);
}
}
var contentDiv = document.getElementById('content');
contentDiv.appendChild(pagesDiv);
}
function searchComplete() {
// Check that we got results
if (imageSearch.results && imageSearch.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('content');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = imageSearch.results;
for (var i = 0; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var title = document.createElement('div');
// We use titleNoFormatting so that no HTML tags are left in the
// title
title.innerHTML = result.titleNoFormatting;
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src="/image-search/v1/result.tbUrl;"
imgContainer.appendChild(title);
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
}
// Now add links to additional pages of search results.
addPaginationLinks(imageSearch);
}
}
function OnLoad() {
// Create an Image Search instance.
imageSearch = new google.search.ImageSearch();
// Set searchComplete as the callback function when a search is
// complete. The imageSearch object will have results in it.
imageSearch.setSearchCompleteCallback(this, searchComplete, null);
// Find me a beautiful car.
imageSearch.execute("Subaru STI");
// Include the required Google branding
google.search.Search.getBranding('branding');
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="branding" style="float: left;"></div><br />
<div id="content">Loading...</div>
</body>
</html>
I have a form which contains a dropdown box, when the value is changed the form uses jQuery and ajax to produce a table. The table contains data based on the value of the dropdown box and also links.
My initial script which is where the dropdown box is and where the table is added is:
<?php require_once('/connections/db.php');
mysql_select_db($database_db, $db);
$query_weeks = "SELECT WeekNo, WeekName FROM tbl_weeks ORDER BY WeekNo ASC";
$weeks = mysql_query($query_weeks, $db) or die(mysql_error());
$row_weeks = mysql_fetch_assoc($weeks);
$totalRows_weeks = mysql_num_rows($weeks);
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form name="form1" method="post" action="">
<select id="weekselect" name="week">
<?php
do {
?>
<option value="<?php echo $row_weeks['WeekNo']?>"><?php echo $row_weeks['WeekName']?></option>
<?php
} while ($row_weeks = mysql_fetch_assoc($weeks));
$rows = mysql_num_rows($weeks);
if($rows > 0) {
mysql_data_seek($weeks, 0);
$row_weeks = mysql_fetch_assoc($weeks);
}
?>
</select>
</form>
<div id="mydata"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#weekselect').change(function(){
var week= $('#weekselect option:selected').val();
//pass val to php
$.post('test2.php',{week: week}, function(data) {
//do something with the data
$('div#mydata').html(data);
});
});
});
</script>
</body>
</html>
The script produces the dropdown from the mysql db and creates a listener for it, when the select is changed the value of the select is passed to the test2.php using jquery. the data returned is added to div #mydata
Test2 which produces the table is as follows
<?php
if (!isset($_SESSION)) {session_start();}
include('session.php');
require_once('Connections/dbc.php');
$open_week=$_SESSION['MM_OpenWeek'];
$week_selected=$_POST['week'];
$season=$_SESSION['MM_Season'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
echo '<p>Week selected: '.$week_selected .'<p>';
echo '<p>Open Week: '.$open_week .'<p>';
if ($week_selected>=$open_week) {
echo '<p>Week Open<p>';
} else {
echo '<p>Week Closed<p>';
}
//create recordset of fixtures for the week selected
$sql="SELECT * FROM q_games_stats WHERE WeekNo =".$week_selected . " and Season=". $season ." and at='Home' ORDER BY WeekNo ASC";
$rec_games=mysqli_query($dbc,$sql);
//create table using the recordset
?>
<div id="data_table">
<table class="table" align="center">
<th class="th" width="80px">Match Date</th>
<th class="th" width="150px">Home Team</th>
<th class="th" width="40px">Score</th>
<th class="th" width="150px">Away Team</th>
<th class="th" width="150px">Link</th>
<?php
while ($row=mysqli_fetch_array($rec_games))
{
?>
<tr class="tr">
<td class="td"><?php echo $row['MatchDate']?></td>
<td class="td"><?php echo $row['TeamName']?></td>
<td class="td"><?php echo $row['Score']?></td>
<td class="td"><?php echo $row['OppName']?></td>
<td class="td">Link</td>
</tr>
<?php
}
?>
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (){
// listen to change in monthselect
$('#data_table a').click(function(){
alert("link clicked");
});
});
</script>
</body>
</html>
This produces the table, which includes links. There is an event listener of the links in the table, which when I click produces an alert.
What I want to do is instead of an alert being produced when clicking a link is for the table to reproduce, the reason for this is when the user clicks a link it will run a script which will change the underlying data in the table and therefore the table will need to be refreshed.
Is there I way I can do this, or is there a better way to do what I want to do?
i have a html table that displays values from the database. I have a javascript that enables me to edit this data but then i cant figure out how to save it back to the database using php. i found some information that i should use xmlhttprequests but i have no idea on how to do this. Any suggestions? Your help is highly appreciated. Code below;
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript"><!--
function edit_input(obj) {
var is_checked = obj.checked;
while (obj.tagName!='TR')
obj = obj.parentNode;
var td = obj.getElementsByTagName('TD');
var len = td.length;
if (!is_checked) {
for (var i=0; i<len; i++)
if (td[i].className=='editable')
td[i].innerHTML = td[i].firstChild.value;
} else {
var input;
for (var i=0; i<len; i++)
if (td[i].className=='editable') {
input = document.createElement('INPUT');
input.value = td[i].innerHTML;
td[i].innerHTML = '';
td[i].appendChild(input);
}
}
}
--></script>
</head>
<body>
<table border="1">
<tr>
<th width="56">Branch ID</th>
<th width="75">Branch Name</th>
<th width="75">Branch Personnel</th>
<th width="105">Branch Headquaters</th>
<th width="50">Edit</th>
</tr>
<?php
$result = mysql_query($query );
while ($row= mysql_fetch_array($result)) { ?>
<tr>
<td class="editable"><?php echo $row['branchid'];?></td>
<td class="editable"><?php echo $row['branchname'];?></td>
<td class="editable"><?php echo $row['branchpersonnel'];?></td>
<td class="editable"><?php echo $row['branchhq'];?></td>
<td><input type="checkbox" onclick="edit_inpu(this);">Edit</td>
</tr>
<?php } ?>
<tr><td><input type="submit" name="editbranch" class="button2" value="Update"/></td></tr>
</table>
</body>
</html>
If using jQuery is not a problem, maybe using something like JEditable is a solution. When you click on a cell in a table, it turns into a textfield, and when pressing enter or leaving focus, it makes a webrequest to the server, where you can make the changes.
See for example this jsfiddle script. It's really easy to use. The only other thing you would need to do is to give the table cells an id, which gets sent to the page you are saving it too.
Have your script fire off an Ajax request through XMLHttpRequest to a PHP script that saves the values back to the database.
The URL could be something like this: updatetable.php?row=0&col=0&data=1234
You could use jquery, is very popular.
you have to download the lib and include-it on the header
http://code.jquery.com/jquery-1.7.min.js
and here it's how you use a ajax request with jquery:
http://api.jquery.com/jQuery.ajax/
The url param is your location to send the values to save them like the post.