Why I am having problems with my output using html/jquery/php - php

Problem no 1 Why my table do not align?
Problem no 2 Why everytime I click my Warrior List at the nav the output goes like this
Here's my js
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
success: function(data) {
$('#listWarriors').append(data);
}
});
}
Here's my html
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</table>
</article>
And heres my php
foreach($result as $names){
$warriors['wname'] = $names['warrior_name'];
$warriors['wtype'] = $names['warrior_type'];
echo '<tr>
<td>'.$warriors['wname'].'</td>
<td>'.$warriors['wtype'].'</td>
</tr>';
}

the result is appended under the </table>
try change your ajax success to :
$('#listWarriors table').append(data);
for number2, im affraid it's truncated by the container (#listWarriors)..
check your css of that id if the width is fixed or not...make it wider as you please

The way you have your jQuery, you are appending the content to the '' tag, and not to the table.
This is what happens when each item is appended, with the way its setup (I added a thead tag by the way. Will come in handy once you start styling your table)
This is the output when things are appended, and why its rendering wrong.
<article id="listWarriors">
<h1>Warrior List</h1>
<table>
<thead>
<tr>
<th colspan="2">Warriors</th>
</tr>
<tr>
<td>Warrior Name</td>
<td>Warrior Type</td>
</tr>
</thead>
</table>
<tr>
<td>the wname</td>
<td>the wtype</td>
</tr>
</article>
With that said modify your jquery to
$('#listWarriors table').append(data);
By the way,
How many items are you wanting to append. If you will make multiple ajax calls and append things one at a time, I would recommend getting the data through JSON. Let me know, if I can help
AS DISCUSSED IN COMMENTS SINCE YOU WANT TO GET MULTIPLE ITEMS JSON IS THE WAY TO GO. You can pass data using JSON this way
**The php (Im sure you already have the query already done but here it is just in case) **
// Make a MySQL Connection
$query = "SELECT * FROM example";//Your query to get warriors from db
$result = mysql_query($query) or die(mysql_error());
$myWarriorsArray = array();//Where you will store your warriors
while($row = mysql_fetch_array($result)){
$myWarriorsArray[] = $row;
//This stores all keys for each iteration
/*//This is teh same as the following commented code
$myWarriorArray['warrior_name'] = row['warrior_name'];
$myWarriorArray['warrior_type'] = row['warrior_type'];
*/
}
echo json_encode($myWarriorsArray);//This will return a json object to your ajax call
The Javascript
function getWarriors() {
$.ajax({
url: 'display_warrior.php',
dataType : 'json',
success: function(data) {
var toAppend = '';
alert(data);
//console.log(data);//Uncomment this to see the returned json data in browser console
for(var i=0;i<data.length;i++){//Loop through each warrior
var warrior = data[i];
toAppend += '<tr>';
toAppend += '<td>'+data[i]['warrior_name']+'</td>';
toAppend += '<td>'+data[i]['warrior_type']+'</td>';
toAppend += '</tr>';
}
$('#listWarriors table').append(toAppend);
}
});
}

Related

How to ajaxify a PHP function that does SQL in the backend?

I have broken down my problem to provide a concise example with no overhead.
Yet enough to give you an idea.
I have a simple index.php
<?php
include 'myClass.php';
?>
<html>
<head></head>
<body>
<div> <?php myClass->printTable(); ?> </div>
</body>
</html>
The function returns an entire table filled with data that is being prepared in the backend.
<?php
function printTable()
{
// printing static table header
echo ' <table class="table" style="zoom: 0.75;">
<thead class="thead-dark">
<tr>
<th scope="col">Date</th> // current date
<th scope="col">Order Number</th> // an int
<th scope="col">Current Value</th> // an int
</tr>
</thead>
<tbody>
';
$result = mysqli_query($this->link, "SELECT * FROM `someData`");
while ($row = mysqli_fetch_assoc($result))
{
$orderNumber = $row['orderNumber'];
$currentValue = $row['currentValue'];
$date = $this->getDate($orderNumber); // member function that returns a timestamp from the database
//printing actual table
echo ' <tr>
<td>'. $date .'</td>
<td>'. $orderNumber .'</td>
<td>'. $currentValue .'</td>
</tr>
';
}
echo ' </tbody>
</table>
';
}
?>
The data I'm querying from my database is constantly changing. I want a "live" view on the frontend. I know this is done by using Ajax. But I don't understand how to do it. I looked up different resources, although none of them were actually specific enough in this approach.
On a high level: You need a PHP file ("endpoint", e.g. 'localhost/data.php') returning only the HTML code from printTable. You then use JavaScript (e.g. jQuery - $.ajax, you can lookup how it works in detail) to fetch the contents of this page each n seconds and insert into your page.
I was looking for broad or unspecific way to get some data from the backend and display it within a div on my page.
The solution was to create a separate PHP (fetch.php) file that echoes only the data I need to display within my div
from my page which contains my div I'd do the following:
<div id="result"></div>
<script>
function load_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('#result').html(data);
}
});
}
load_data()
</script>
Inside fetch.php I can do whatever I want, including querying my database and store the values in a variable which will be echoed at the end. This response (echo) from fetch.php will then be displayed inside my div.
Similarly, I could also specify a .txt inside the ajax function (url:"sometext.txt")
The contents of the .txt could also be displayed inside my div this way. My lack of understanding of how this works made it really difficult to understand.
Additionally, I have added a function to refresh the contents (or response) every second.
If I would echo time() from fetch.php it would automatically increment without page reload inside my div
setInterval(function(){
load_data()
}, 1000);

Hello i'm trying to do multiple sorting using php mysql where i'm searching and then sorting the data

i'm printing a table in php where data is coming from mysql now i'm creating functionalities like searching and sorting so when i click on sort it sorts the data and when i click on search i get searched data now the problem is i want to perform sorting on searched data like for example i sorted the data and then i searched for words starting with a i.e i got results like adam,azan,anand so i want to perform resorting on these searched data and get data as adam,anand,azan
my approach is:
<?php
if(isset($_GET['search_btn'])){
$search=$_GET['search'];
$result=GetWords(mysqli_escape_string($conn,$search));
}
/*if(isset($_GET['q'])){
$id=$_GET['q'];
$result=GetWordsById($id);
}*/
if(isset($_GET['sort'])){
$sort=$_GET['sort'];
}
if(isset($_GET['sort'])){
if($sort=="asc"){
$result=SortContent();//Here Get Sort Content is a function calling Store Procedure SortContent which is working at first sorting
}
if($sort=="desc"){
$result=SortContent2();
}
}
else{
$result=GetAdminWords();
}
if(mysqli_num_rows($result)>0)
?>
<thead>
<tr>
<th>Word</th>
<th>Meaning</th>
<th>Synonym</th>
<th>Antonym</th>
</tr>
</thead>
<?php
while($row=mysqli_fetch_array($result)){
?>
<tbody>
<tr>
<td><?php echo $row['word'];?></td>
<td><?php echo $row['meaning'];?></td>
<td><?php echo $row['synonym'];?></td>
<td><?php echo $row['antonym'];?></td>
<td><i class="fa fa-edit"></i> <a onClick="javascript: return confirm('Please confirm deletion');" href="view.php?id=<?php echo $row['id'];?>"><i class="fa fa-trash"></i></a> </td>
</tr>
</tbody>
<?php
}?>
and i'm talking in context of large amount of data i hope i have made myself clear and if possible how can i implement ajax using mysqli
You will need to trigger an event in JavaScript, which in turn will use your HTML search input, which is then sent to the server, where a query will be executed and the results returned (as HTML) to the JavaScript code, and finally placed back on the page. At least this is how I solve my ajax searches...
So the flow could be something like:
Input -> JavaScript event -> ajax -> result -> page
Here is some code that might get you started, though I haven't tested i myself:
HTML:
<input type="text" id="my_search_input">
<div id="my_search_result"></div>
JS (jQuery):
var $inputField = $( "#my_search_input" );
var $result = $( "#my_search_result" );
$inputField.on('keyup', function(){ //triggered when a pressed key is lifted
var searchTerm = $inputField.val();
$.ajax({
url:"/mySearch.php",
method:"post",
data:{searchTerm:searchTerm},
success:function(response){ //response contains the data from mySearch.php
var parsedResponse = JSON.parse(response);
var resultHtml = parsedResponse.html; //this is the array key of what the PHP script returns
$result.append(resultHtml);
}
});
});
PHP
$searchTerm = $_POST['searchTerm']; //$_POST['searchTerm'] is what we defined in data:{... in the ajax call
// here is where you need to retrieve data from your database
// the db result needs to be processed into HTML and assigned to a variable
$html = "<div>My result based on data</div>";
return json_encode(['html' => $html]);

Can't remove table tr properly in each loop using jquery

my for loop is creating this at run time using jquery
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_0"></tr>
<tr id="auctionLocation_1"></tr>
<tr id="auctionLocation_1"></tr>
<tr id="auctionLocation_1"></tr>
and I'm removing it using jquery each loop and my code is
function testing() {
var current = 0;
$("#user").each(function() {
$("#user").find("tr[id='auctionLocation_"+current+"']").remove();
current++;
});
}
OR
function testing() {
$("#user").each(function(i, v) {
$("#user").find("tr[id='auctionLocation_"+i+"']").remove();
});
}
its only remove 0 index not 1 index so how I could do it?
thats my creating code
var counterForLocationsField = 1;
var auctionCompanyLocationArray = data.auctionCompanyLocationArray;
for(var auctionCompanyLocationLoop = 0; auctionCompanyLocationLoop < auctionCompanyLocationArray.length; auctionCompanyLocationLoop++) {
var completeTr = "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location Name "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationName"]+"</td> <td>Location Address "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationAddress"]+"</td></tr>";
completeTr += "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location City "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationCity"]+"</td> <td>Location State "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationState"]+"</td></tr>";
completeTr += "<tr id='auctionLocation_"+auctionCompanyLocationLoop+"'><td>Location Zipcode "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationZipcode"]+"</td> <td>Location Phone "+counterForLocationsField+"</td><td>"+auctionCompanyLocationArray[auctionCompanyLocationLoop]["auctionLocationPhone"]+"</td></tr>";
$(completeTr).insertBefore("#lastRow");
counterForLocationsField++;
}
As you select the id user, the loop only loops once. Ids are unique.
You can use the starts with selector.
$("tr[id^='auctionLocation_']").remove();
No loop needed. If you want to loop use $("tr[id^='auctionLocation_']").each().
Do not use same ids for different elements. Id must be unique in the page.
Use class instead, like:
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_0"></tr>
<tr class="auctionLocation_1"></tr>
<tr class="auctionLocation_1"></tr>
<tr class="auctionLocation_1"></tr>
And when you want to remove them, just do the above, without loops:
$('tr.auctionLocation_0').remove()

how to access the returned php variable using ajax, as a php variable in the view

i am in this situation,
//view
$.ajax({type: 'POST',
url: base_url+"home/display_info/"+patient_id,
async: false,
success: function(data){
//alert(data);// alert was working
}
});
//controller
function display_info($id)
{
$document= $this->document_model->getDocumentOfPatient($id);
print_r($document);
}
in this i am getting the data as an array from the controller, and i want to get the data to a php array variable to build a table(html) with that array,but stuck here, is there any way to set a table(html) with this returned data variable, can i access the variable <?php echo $document['document_id'];?> like this in the view.
Try this
First you create table in your view page. Table id name foo and use to create table row and append to the html table
Sample code is given below
<scrit type="text/javascript">
$.ajax({type: 'POST',
url: base_url+"home/display_info/"+patient_id,
async: false,
success: function(data){
var table = '<tr><td>' + data['patient_id'] + '</td><td>' + data['document_id'] + '</td><td>' + data['document_date'] + '</td><td>'+ data['insert_user_id']+ '</td></tr>';
$('#poo > tbody').append(table);
}
});
</script>
<table id="poo" style="margin:10px 0px 0px 0px;" width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td><strong>Product id</strong></td>
<td><strong>Doc id</strong></td>
<td><strong>Date</strong></td>
<td><strong>userid</strong></td>
</tr>
</thead>
<tbody>
</tbody>
</table>
PHP is a server-side language. If you want to use PHP data in your view, you need to convert it to a client-side language like Javascript.
For example, in your display_info controller, you could return some JSON, using PHP's json_encode to convert a PHP array made of useful data for your view. Output it with the application/json content-type header.
In this kind of situation I used to make table in controller itself and assign it to variable.
So you can get that table in View as AJAX Response. Then its very simple to assign response to
inner HTML of resource Id where its required to display.
Does the data correctly ?
var obj = jQuery.parseJSON(data);
use JSON in the form of.I hope the right understand

JSON array to an HTML table and display the data inside td tag

I have json array return as bellow
{"id":16,"minutes":146}
{"id":17,"minutes":137}
{"id":18,"minutes":123}
{"id":22,"minutes":84}
I'm trying to render above json array inside table tbody td which json array id's equal to td id's and display the minutes inside td tag
for example json id :16 minute:146 and display it in <td id="16">146</td>
<table>
<thead>
<tr>
<th>op</th>
<th>Minutes</th>
</tr>
</thead>
<tbody>
<tr>
<td>op1</td>
<td id="16">0</td>
</tr>
<tr>
<td>op2</td>
<td id="17">0</td>
</tr>
<tr>
<td>op3</td>
<td id="18">0</td>
</tr>
<!--....and goes on -->
</tbody>
</table>
js
$.ajax({ url: statUrl, type: 'POST',
data: {
begin: begin,
end: end
},
success: function(data){
}
});
Your JSON is invalid it should only represent one object, a valid version of what you have will be
[{"id":16,"minutes":146},
{"id":17,"minutes":137},
{"id":18,"minutes":123},
{"id":22,"minutes":84}]
If your data IDs directly correspond to already existing DOM element IDs then it should be rather easy:
for (var i = 0; i < data.length; i++) {
$('#' + data[i].id).text(data[i].minutes);
}
This is using jQuery ofc.
you can use json_decode($json, true) in php to convert the json to an array then loop over it's elements and build your table.
If you want to do it client side, I think you must create table, tr and td elements manually and populate them. ExtJS has ready grid for this.
Server side is easier.
I created a jsFiddle here: http://jsfiddle.net/5pKjW/11/
As Musa stated, the JSON you posted is not valid, it should be an array containing all the objects.
The code following is basically what you need to do inside the success callback, just use data instead of result.
What I do is creating a table, appending a row for every element of the array and then appending the whole table to an element of the DOM.
var result = [{"id":16,"minutes":146},{"id":17,"minutes":137},{"id":18,"minutes":123},{"id":22,"minutes":84}];
var $table = $('<table><thead><tr><th>op</th><th>Minutes</th></tr></thead>'),
$tbody = $('<tbody>').appendTo($table),
i;
for (i = 0; i < result.length; i++){
$tbody.append('<tr><td>op' + (i+1) + '</td><td id="' + result[i].id + '">0</td></tr>');
}
$table.appendTo('#container');
As T.J. Crowder commented, a valid HTML4 id attribute can't start with a digit. If I were you, I would prefix it with a string (<td id="prefix' + result[i].id + '">0</td>).
MrOBrian suggested to use a rendering engine. Maybe for a simple case like this, and if you don't need a rendering engine elsewhere, it's an overkill, but that's absolutely something worth considering, if you need something more complicated in the future.
as suggested fixed json array to
{
"25":72.3833,
"17":116.3167,
"16":25.75,
"34":28.3333,
"29":136.8831,
"19":40.9166,
"32":43.6,
"22":83.9001
}
and js
$.getJSON(statUrl, {begin: begin, end: end}, function(data) {
$.each(data, function(key, val) {
$('#op_' + key).text(Math.ceil(val));//also fixed td id
});
});
so got the result as expected.
thanks for your time.

Categories