In this code I am getting posts from database in table, table displays posts in three columns, now I want to add some jQuery to limit the number of rows and add a button which on clicking appends few rows to table I am not a professional programmer may be something like slice should be used to limit number of rows.
$sql = "SELECT * FROM posts";
$query = $db->prepare($sql);
$query->execute();
<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div>id</div>
<div>title</div>
<div>body</div>
<div>date</div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper
?>
</table>
HTML
Create your table (You can also create dynamically)
<table id='posts'>
<tbody></tbody>
</table>
<button id='load-more-entries'>Load</button>
JavaScript
Create a variable for keeping track of what result you are on. What the index of the last result you grabbed.
Grab the elements by id. attach listener to button so when you click you load more results. Take a look at AJAX documentation. It is very simple and short.
var index = 0;
var load, table;
load = document.getElementById('load_more_entries'),
table = document.getElementById('posts');
load.addEventListener('click', function(e){
processAjaxRequest({
type: 'get',
url: "posts.php?index="+index,
success: function(xmlhttp){
var results = JSON.parse(xmlhttp.response);
for(var i = 0; i < results.length; ++i){
var row = table.insertRow();
var cell = row.insertCell(cell_index);
//increment index according to how many results you
grab so next time you grab the next results
index++;
}
},
error: function(xmlhttp){
//Handle error
}
});
});
/*
this function here it is a a wrapped AJAX
it will call php file below and run it. It will fetch the results
form database and return them to you in form of a string. You need
to parse it JSON.parse() to turn it into an array
*/
function processAjaxRequest(object){
var xmlhttp = new XMLHttpRequest() ||
new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4){
if(xmlhttp.status === 200){
object.success(xmlhttp);
}else{
object.error(xmlhttp);
}
}
}
xmlhttp.open(object.type, object.url, true);
xmlhttp.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
xmlhttp.send(object.args);
};
PHP
This file is called by processAjaxResquest
$posts = array();
while($post = mysqli_fetch_assoc($sql)){
$posts[] = $post;
}
echo json_encode($posts);
?>
*NOTE I have not tested the code there maybe a couple of thing I may have left of. However, this should be enough to get you started. I got the same kind of answer when I had this question. Also, note that there is also more things you need to be aware of; like checking the variables inside PHP file are set before you do anything.
Related
This is my current plan:
Clicking on a row selects or gets the id of the row, then this id is passed to a delete script most likely via AJAX or an HTTP request. The problem I have is how to identify the row from the click using "this" this as in show below:
$( this ) {
// get id and send to delete script
}
I have echoed out the rows so that I have the id row
<?php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR.'dbconnect.php');
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$query = "SELECT COUNT(*) FROM entries";
if ($result = $link->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
if($row[0]==0){
echo "There are no entries.";
}else {
$query2 = "SELECT id,saying,date,thumbs_up,comments FROM entries ORDER by ID ASC ";
if (($result = $link->query($query2))) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo
'<div class="container" align="center"">'.
'<div class="entry-container" align="left">'.
$row[1]." ".
'</div>'.
'<div class="x" align="center">'.
'<button class="red" name="remove" onclick="remove_entry();">remove entry'.
' '.
$row[0].
'</button>'.
'</div>'.
'</div>'.
'<br>'
;
}
}
}
}
/* free result set */
$result->close();
}
?>
remove_entry(); doesn't do anything yet, presumably it will send the id to the delete script which then removes the row using the DELETE command
<script type="text/javascript">
function remove_entry() {
var answer = confirm("Delete this entry?")
if (answer){
//some code
}
else{
//some code
}
}
</script>
What is the most direct and effective / efficient way to do this?
I would even prefer not to show id, just use a simple x for the delete button, I echoed the id so that I had it to use to identify the row to be deleted.
Using jQuery can do :
HTML
<div class="entry-container" align="left" id="'.$row[0].'">
JS
$(function(){
$('button.red').click(function(){
var $row = $(this).closest('.entry-container'),
rowId = $row.attr('id');
$.post('/path/to/server', {id: rowId}, function(resp){
if(resp =='ok'){
$row.slideUp(function(){ $row.remove() });
}
});
});
});
Then remove your inline onclick
In PHP receive the id with $_POST['id'] and validate it before passing to db query
For starters, don't use 2 SQL queries. Just do the one you use to get data and, if it has no rows, give a different output.
Use semantic markup like so:
'<button type="button" class="remover" id="entry-' . $row[0] . '">remove this entry</button>'
Then in your jQuery, use something like this:
$(function() {
$('.entries').on('click', '.remover', function() {
var eId = this.id.replace(/^\D+/, '');//since IDs should not start with a number
$.post(
'/your/delete/endpoint/',
{
id: eId
},
function(data) {
if (data.ok) {//sending JSON responses are easier to debug and you can add to them later without breaking things
//remove row
}
else {
//display error message
}
}
);
});
});
The second parameter to on() makes it a delegated event, which means you can add new items to an existing set, with the same remover markup, and the new remove buttons will also work.
I have a problem with my queries at my MySQL database. I have to represent some variables in a graph.
So far I have
JavaScript that reads what variables I have to represent and POST with Ajax
PHP code to handle the POST
My PHP code has a POST function that does a query with inner joins depending if my variables are in the same table or not. This query obtains a table with datetime and all the variables. This POST function works well, I tested it.
The problem is when I want to represent more than 4 variables. If I want to represent 5 variables, I can represent less than 97,000 rows. If I want to represent 6 variables, I can represent less than 86,000 rows (each time I add a variable I lose around 11,000 rows).
My javascript code
jQuery.extend({
llamada: function() {
var result=null;
$.ajax({
type:'POST',
async: false,
dataType: 'json',
url:"includes/mysql.php",
data: { tarea:'ejecutarQuery',
table: varNames,
columna: varLocations
},
success: function(respuesta){
alert(respuesta);
/*result=respuesta;*/
}
});
return result;
}
});
var myServerData = $.llamada();
The post function in mysql.php
if($_POST["tarea"]=="ejecutarQuery"){
$columnas = $_POST["columna"];
$tablas = $_POST["table"];
$tablacolumna = array();
$frasecolumnas="";
for($j=0;$j<count($columnas);$j++){
$tablacolumna[$j]=$tablas[$j].".".$columnas[$j];
if($j==0){
$frasecolumnas=$tablacolumna[0];
}
else{
$frasecolumnas=$frasecolumnas.",".$tablacolumna[$j];
}
}
$tablasdiferentes= array();
$tablasdiferentes[0]=$tablas[0];
$contador=0;
for($j=1;$j<count($tablas);$j++){
for($i=0;$i<count($tablasdiferentes);$i++){
if($tablas[$j]==$tablasdiferentes[$i]){
break 1;
}
if($i==$contador){
$tablasdiferentes[$i+1]=$tablas[$j];
$contador++;
}
}
}
$frasetablas="FROM ".$tablas[0]." ".$tablas[0]." ";
$fraseError =" where ".$tablas[0].".ErrorBit=0";
for($j=1;$j<count($tablasdiferentes);$j++){
$frasetablas=$frasetablas."inner join ".$tablasdiferentes[$j]." ".$tablasdiferentes[$j]." on ".$tablas[0].".datetime=".$tablasdiferentes[$j].".datetime ";
$fraseError =$fraseError." and ".$tablasdiferentes[$j].".ErrorBit = 0";
}
$sql="SELECT ".$tablas[0].".datetime,".$frasecolumnas." ".$frasetablas.$fraseError.";";
$rawdata=getArraySQL($sql);
echo json_encode($rawdata);
}
method getArraySQL
function getArraySQL($sql){
$conexion = conectarBD();
mysql_set_charset('utf8',$conexion);
if(!$result = mysqli_query($conexion, $sql)) die(mysql_error);
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result,MYSQL_NUM))
{
$time = $row[0];
$date = new DateTime($time);
$row[0] = $date->getTimestamp()*1000;
$rawdata[$i] = $row;
$i++;
}
desconectarBD($conexion);
return $rawdata;
}
I think that the problem may be that the while loop does not finish depending on the number of variables. I suppose it is because of the array's memory size.
Can anybody help me?
I would like to get a better performance for my scripts where the user is able to Create/Read/Update/Delete (CRUD) data.
Currently I send a request after every action and refresh the overview page. Example:
Add
<table>
<tr>
<td>Item 1</td>
<td>
Edit
Delete
</td>
<table>
-
<?php
// script.php -> action=delete
$error = true;
if ($this->database->query("DELETE FROM items WHERE id = :id", array("id" => $_GET["id"]))) {
$error = false;
}
// forward back
header("Location: script.php?error=" . $error);
?>
I don't like it and would like to change it.
What do you think about this:
Loading items (JSON) via AJAX
only modify the items array
collect the updated and deleted items
update and delete onUnload/windowClose
Result: less server requests
Pseudocode:
<script>
var items = null; // items
var items_deleted = null; // items, marked to delete
var items_updated = null; // items, marked to be updated
// builds the html table
function build_html_table() {
// sort the items
items = sortTheItems(items);
html = "<table>";
for (i = 0; i < items.length; i++):
html += '<tr id="'+items[i].id+'">';
html += '<td>'+items[i].name+'</td>';
html += '<td>';
html += 'Edit';
html += 'Delete';
html += '</td>';
html += "</tr>";
endfor;
html += "</table>";
$("#table").html(html);
}
// on clicking the delete-link
$(".delete").click(function() {
// get id
id = $(this).parent().parent().attr("id"); // id of <tr>
// delete item (temp)
for (i = 0; i < items.length; i++)
if (items[i].id == id)
unset(items[i]);
endfor;
// mark for deleting
items_deleted.push(id);
// re-build table
build_html_table();
});
// on clicking the edit-link
$(".edit").click(function() {
// get id
id = $(this).parent().parent().attr("id");
// get the item to edit
item = null;
for (i = 0; i < items.length; i++):
if (items[i].id == id)
item = items[i];
endfor;
// fill the save-form
$("#save_dialog [name='id']").val(item.id);
$("#save_dialog [name='name']").val(item.name);
$("#save_dialog [name='content']").val(item.content);
// open save-form in a dialog
$("#save_dialog").dialog();
});
// on clicking the add link
$(".add").click(function() {
// reset the save-form
$("#save_dialog [name='id']").val("");
$("#save_dialog [name='name']").val("");
$("#save_dialog [name='content']").val("");
// open save-form in a dialog
$("#save_dialog").dialog();
});
// save form
$("#save_form").onSubmit(function() {
id = $(this).find("[name='id']");
if (!id) {
// real add, getting the new id
$(this).ajaxForm({
onSuccess: function(responseText, $form) {
item.id = responseText; // script.php?action=save returns the last inserted/updated ID
item.name = $form.find("[name='name']");
item.content = $form.find("[name='content']");
// add the added item
items.push(item);
});
} else {
// temp. update
// update the old entry
for (i = 0; i < items.length; i++):
if (items[i].id == item.id) {
items[i].name = $(this).find("[name='name']").val();
items[i].content = $(this).find("[name='content']").val();
// mark this item to update
items_updated[items[i].id] = items[i];
}
endfor;
}
// re-build table
build_html_table();
});
// doc ready
$(function() {
// get the items data (json)
items = getJSON("items_json.php");
// build table
build_html_table();
});
// on window close/unload (or after $x minutes)
$.unload(function() {
// real delete
ajaxRequest("script.php?action=delete&ids=", items_deleted);
// real update
ajaxRequest("script.php?action=update", items_updated);
});
</script>
Add
<div id="table">loading...</div>
<div id="save_dialog" class="hidden">
<form action="script.php?action=save" method="POST" id="save_form">
<input type="hidden" name="id"/>
Name: <input type="text" name="name"/><br/>
Content: <textarea name="content"></textarea><br/>
<input type="submit"/>
</form>
</div>
What do you think about my idea? What could I do better? Are there good jQuery-plugins to get this job done easily?
Thanks in advance!
Note: It's just pseudo-code!
A big helper is using data- attributes to save parsing other attributes to get things like ID, or action which you have hardcoded in url( keep there for no JS in page) but helpful to access it in handlers also.
/* "data-arbitraryName" can be read using jQuery `data()` method*/
html += '<tr id="'+items[i].id+'" data-id="'+items[i].id+'">';
/* add common class to "controls"*/
'Edit';
/* can now combine a lot in one click handler*/
$('#tableParent').on('click', '.crud_btn', function(e){
var $btn=$(this), $row=$btn.closest('tr'), row_id= $row.data('id');
/* data() method reads "data-" attributes*/
var thisAction=$(this).data('action')
/* create data object to send*/
var dataToServer={/* this data always sent*/
action: thisAction,
id: row_id || 'add';
}
/* additional data as needed based on "action"*/
if( thisAction == 'add'){
$.extend( dataToServer, someFormData);
}
/* use direct file url, if GET, jQUery will append search string from dataToServer object*/
$.getJSON('script.php', dataToServer, function(response){
if( response.success ){
/* psuedo update method*/
updatStoredData( response, action);
/* success handling based on "action"*/
if(thisAction=='delete'){
$row.remove();
}
}
})
return false;
})
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
I have the following ajax.js, which I must use:
var xmlRequest = null;
function ajax(url, parametersArray, callbackFunction, fcnVars) {
if (xmlRequest != null) {
if (xmlRequest.readyState == 2 || xmlRequest.readyState == 3) {
xmlRequest.abort();
xmlRequest = null;
}
}
if (parametersArray == null)
parameters = "";
else
parameters = formatParameters(parametersArray);
if (window.XMLHttpRequest)
xmlRequest = new XMLHttpRequest();
else
xmlRequest = new ActiveXObject("MSXML2.XMLHTTP.3.0");
xmlRequest.open("POST", url, true);
xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
if (xmlRequest.responseText) {
callbackFunction(xmlRequest.responseText, fcnVars);
}
}
}
xmlRequest.setRequestHeader("Content-length", parameters.length);
xmlRequest.setRequestHeader("Connection", "close");
xmlRequest.send(parameters);
}
function formatParameters(parameters) {
var i = 0;
var param = "";
for (index in parameters) {
if (i==0) {
param += index+"="+urlencode(parameters[index]);
} else {
param += "&"+index+"="+urlencode(parameters[index]);
}
i++;
}
return param;
}
function urlencode(clearString) {
clearString = encodeURI(clearString);
clearString = clearString.replace('&', '%26');
return clearString;
}
and I have the following mysql table:
CREATE TABLE `dictionary` (
`word` varchar(64) NOT NULL,
PRIMARY KEY (`word`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
on the end, here is my search page:
<div id = "search">
<form id="searchform" method="post">
Search for Word:
</select>
<input type="text" id="search_term" name="search_term" />
<input type="submit" id="cmdSearch" value="Search" />
</form>
<div id="search_results"></div>
</div>
Now, I have to create a php function which will return an array with the words found in the table, using the above ajax.js
Results should be shown within the search_results div using ajax.
Of course, I will need a javascript code as well.
Anyone can help me to start to build this? I have done similar things with jquery,but now I must use this script, and I have no other way to do it.
Goal is to display the results in the php page without refresh.
Any help will be deeply appreciated
Update:
Here is my php code:
<?php
// add encoding here
header("Content-Type: text/html; charset=iso-8859-7");
// include the database connection here
include 'config.php';
include 'openDb.php';
function findWords(){
// sanitaze the user input
$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysql_escape_string($term);
// query the database. one fileld only, so nothing to optimize here
$sql = "SELECT word FROM dictionary WHERE word like '%$term%'";
$result = mysql_query($sql);
// set the string variable
$string = '';
// if resulta are found then populate the string variable
if (mysql_num_rows($result) > 0){
while($row = mysql_fetch_object($result)){
// display the results here in bold and add a new line or break after each result
$string[] = "<b>".$row->user_name."</b><br/>\n";
}
} else {
// if no results are found, inform the visitors...
$string[] = "No matches!";
}
// output the string
return $string[];
Here is the javascript:
<script type='text/javascript'>
ajax("findWord.php", {id:search_term}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:search_term});
</script>
You will have to rely on the ajax function which lets you access whatever it loaded in the callback function:
callbackFunction(xmlRequest.responseText, fcnVars);
And ajax explains how it should be called itself:
ajax(url, parametersArray, callbackFunction, fcnVars)
Even though parametersArray should actually be an object ({index:value, i1:v2,...}) rather than an array ([val1, val2,...]). fcnVars can be an object containing anything that you want passed on to the callback function.
This should work:
ajax("add_page.php", {id:535}, function(result,params) {
alert("result for ID: "+params.id+"\n\n"+result);
}, {id:535});