I have a php file that shows all the user details in table form. On click of edit, I am want to set something from DB to local storage using javascript.
So to show a table of users I am doing the following:
<table cellspacing="0">
<tr>
<th>ID</th>
<th>Name</th>
<th>View</th>
<th>Edit</th>
</tr>
<?php
$count=1;
$sel_query="Select * from user_details ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) {
?>
<tr>
<td align="center"><?php echo $count; ?>
<td align="center"><?php echo $row["docname"]; ?>
<td align="center">View</td>
<td align="center">Edit</td>
</tr>
<?php $count++; } ?>
</table>
The above shows the records in the table perfectly.
Now when edit is clicked, I call a javascript function. (This is called before I click on edit? I am not sure why?)
<script type="text/javascript">
function handleLinkClick (e) {
e.preventDefault ();
var id = e.target.href.split ("?").pop ();
var key = <?php echo add(id);?>
console.log(key);
localStorage.setItem ("myKey", key);
//window.location.href = e.target.href;
}
</script>
Now from javascript function, I am trying to call a PHP function a variable is sent from javascript to PHP function to fetch corresponding records details and return that data to javascript, below is the PHP function:
function add($id){
$sel_query="select * from user_details where id=$id";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result))
{
$key = $row["rawText"];
echo $key;
}
return $key;
}
?>
I don't see any results. I am not sure why I am not getting any results? Can some give me the right syntax or correct me?
Thanks!
Related
I have some code where the intended purpose is a user typing into a search bar. Upon searching, a table should display with records closely related to the search phrase. In my case, I have all the code set up, but I am not getting any table being shown upon searching.
I have many lines commented out and those are some of the fixes and things I have messed around with that I thought would fix this.
The Search function code - search.php
$name = $_POST['name'];
$sql = "SELECT * FROM ProfessorsOrStaff where Name LIKE '%".$name."%'";
//echo $sql;
$data = array();
$result = $conn->query($sql);
//echo json_encode($result);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Name'];
array_push($data, $row);
}
} else {
//array_push($data);
echo "no data";
exit;
}
//array_push($data, {"msg":'success'});
echo json_encode($data);
$conn->close();
?>
Partial code of file that displays the search bar and javascript
<div id="message" style="text-align: center">
<p>There are no results.</p>
</div>
<table class="table" id="result_table" hidden="hidden">
<thead class="thead-dark">
<th>Name</th>
<th>Phone Number</th>
</thead>
<tbody id="body">
<tr>
<!--<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>1</td>-->
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$("#search").click(function(){
var text = $("#name").val();
$.post('search.php', {name: text}, function(data){
console.log(data);
//$name = $_POST['name'];
if(data != "no data" ){
console.log("here");
var obj = JSON.parse(data);
//$("#result_table").setAttr('hidden');
$('#result_table').removeAttr('hidden');
$("#message").hide();
var html = '';
for(var i = 0 ; i < obj.length; i ++ ){
console.log(obj[i]);
html += '</td><td>'+obj[i].Name+'</td><td>'+obj[i].PhoneNumber+'</td></tr>';
}
$('#body').html(html);
}
else{
$('#result_table').attr("hidden","hidden");
$("#message").show();
}
});
})
The code is a bit messy. To clarify,
The search.php can be found here-https://codeshare.io/a3wdmD
Other file with javascript- https://codeshare.io/G8838A
Table layout -https://imgur.com/a/14SsvLS
EDIT1- After finding out the request was not being made, I switched some stuff around and was able to make it not correctly call the search.php file. Now I am getting the wrong results from this. It is bringing me to a new page and displaying the contents of all my records in that table, as a plain text format. I was trying to make it so once the search button was pressed, a table of results appeared right below the search bar. The links to the full code have been updated to show the current state of the code.
I have created a loop which contains a dropdown list and input field.
What I need is:
When I select a value from dropdown list of Fruit Genres, the Unit Price field will display value come from database. I did all of these, but could not display value to the Unit Price field.
Here is my code:
View page:
<div class="table-responsive">
<table class="table table-hover" id="item-tbl">
<thead>
<tr>
<th class="text-center">Fruit Type</th>
<th class="text-center">Fruit Genres</th>
<th class="text-center">Qty</th>
<th class="text-center">Unit Price</th>
<th class="text-center">Sub Total</th>
</tr>
</thead>
<tbody>
<?php for($i=1; $i<=3; $i++){ ?>
<tr style="">
<td><?php echo $this->Form->input('fruit_type_id', ['options'=>$fruit_types, 'empty'=>'Select Fruit Type', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_type_id]']); ?></td>
<td><?php echo $this->Form->input('fruit_genre_id', ['options'=>$fruit_genres, 'empty'=>'Select Fruit Genre', 'label'=>false, 'name'=>'detail_orders['.$i.'][fruit_genre_id]', 'class'=>'fruit_genre']); ?></td>
<td><?php echo $this->Form->input('quantity', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][quantity]', 'class'=>'quantity', 'id'=>'quantity_'.$i]); ?></td>
<td><?php echo $this->Form->input('price', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'price', 'id'=>'price_'.$i]); ?></td>
<td><?php echo $this->Form->input('sub_total', ['type'=>'text', 'label'=>false, 'name'=>'detail_orders['.$i.'][price]', 'class'=>'sub_total']); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var priceId = $(this).closest('tr').find('.price').attr('id');
// alert(priceId);
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// $(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
$(priceId).val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
OrdersController.php
public function getFruitById($id){
$this->viewBuilder()->layout('ajax');
$this->loadModel('FruitGenres');
$item = $this->FruitGenres->get($id);
if (!empty($item)) {
$response['code'] = 200;
$response['message'] = 'DATA_FOUND';
$response['data'] = $item;
}else{
$response['code'] = 404;
$response['message'] = 'DATA_NOT_FOUND';
$response['data'] = array();
}
$this->set('response', $response);
$this->set('_serialize', ['response']);
}
I have got the expected data to the javascript console. but could not pass the data to the input field.
I have tried:
$(this).closest('tr').find('.price').val(returnData.response.data.unit_price);
instead of
$(priceId).val(returnData.response.data.unit_price);
into the ajax success function, but it did not worked.
if I add a static id like the following:
$('#price_1').val(returnData.response.data.unit_price);
then it works.
Can anyone please help me? I am stuck on it.
I am using cakephp 3 for my project.
priceId is a value like price_1 without #. To make it a selector by id - prepend it with #:
$("#" + priceId).val(returnData.response.data.unit_price);
You can even simplify your code:
// you get id of the found element so as to find this element again
// you can store founded element instead of it's id
var priceDiv = $(this).closest('tr').find('.price');
// in success callback:
priceDiv.val(returnData.response.data.unit_price);
You can select the element directly instead of getting its ID and select with another jQuery call.
Another thing to note - this in the submit callback refer to the callback function itself, not the element.
$(document).ready(function() {
$(".fruit_genre").on('change' , function() {
var fruitGenreId = +$(this).val();
var $price = $(this).closest('tr').find('input.price'); // Get the element
$.ajax({
type: "GET",
url: baseURL+"orders/getFruitById/"+fruitGenreId+".json",
beforeSend: false,
success : function(returnData) {
if(returnData.response.code == '200'){
console.log(returnData.response.data.unit_price);
// Use $price directly as a jQuery object
$price.val(returnData.response.data.unit_price);
};
}
})
}).trigger('change');
});
I want to delete an object on my database through my own admin page. The way it works is simple: when I click the delete button in the row corresponding with the object, the JS code will grab the "id" attribute of the object and pass it to PHP to perform sql delete query. Although the console showed nothing, my code didn't work. Would you mind taking a glance at my code and find out what's wrong with it? I'm using PHP 7. All neccessary libraries is included. Thank you very much!
Here are my code:
HTML:
<table>
<thead>
<th>ID</th>
<th>Name</th>
</thead>
<tbody>
<?php
include("../connect.php");
$sql = "select * from tbl";
$query = mysqli_query($connect,$sql);
while($data = mysqli_fetch_assoc($query)) {
?>
<tr>
<td class="data-id">
<?php echo $data['id'] ?>
</td>
<td>
<?php echo $data['name'] ?>
</td>
<td>
<img src="delete.png" class="delete-button">
</td>
</tr>
<?php } ?>
</tbody>
</table>
JS:
$(document).ready(function() {
$('.delete-button').click(function() {
var id = $(this).parent().siblings('.data-id').text();
$.ajax({
type: 'post',
url: 'http://localhost/myproject/delete.php',
data: {
"id":id
}
});
});
});
PHP delete.php
<?php
include("../connect.php");
if(isset($_POST["id"])) {
$id = $_POST["id"];
$sql = "delete from tbl where id=".$id;
$query = mysqli_query($connect,$sql);
}
?>
PHP connect.php
<?php
$connect = new mysqli("localhost","root","","db");
mysqli_set_charset($connect,'utf8');
?>
Your delete query syntax is wrong. It should be like below,
$sql = "delete from tbl where id=".$id;
Remove '*' from the query
Update: There are 2 more errors in your code & hopefully these corrections might fix your issue
Issue 1: Since your sending text inside a TD as id, it sends the id along the spaces in the HTML. So trim your value. Here is your query,
$sql = "delete from tbl where id=".trim($id);
Issue 2: This might be a typo error. '$connnect' variable should be '$connect' in connect.php file.
It seems that $(this).parent().siblings('data-id').text();
Should be $(this).parent().siblings('.data-id').text();
Missing the dot (.) in the class name.
In your actual code please `` for reserved mysql name
Change to below code :
$sql = "DELETE FROM `tbl` WHERE `id`='$id'";
Ideally, In my database table, I have username, name, location, email.
Now I have a table in my view.php where it returns value from the database.
Table header consists of name, username, and more info where name and username comes directly from the database while more info will have a button for each row. When the button is clicked, it should display location and email in a pop up.
Question: How can I retrieve location and email of a user when the button is clicked specifically?
Example:
user1, joe doe, [button] -> user1 location, user1#email.com
user2, jay doe, [button] -> user2 location, user2#email.com
Codes: p.s. code includes pagination.
controller.php
function pagination() {
$config = array();
$config['base_url'] = base_url() . "controller/pagination";
$total_row = $this->model->record_count();
$config["total_rows"] = $total_row;
$config["per_page"] = 8;
$config['uri_segment'] = 3;
/* $config['use_page_numbers'] = TRUE; */
$config['num_links'] = $total_row;
$config['cur_tag_open'] = ' <a class="current">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = '<span aria-hidden="true">»</span>';
$config['prev_link'] = '<span aria-hidden="true">«</span>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->model->fetch_data($config["per_page"], $page);
$str_links = $this->pagination->create_links();
$data["links"] = explode(' ', $str_links);
// View data according to array.
$this->load->view("view-employees", $data);
}
model.php
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
view.php
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data->username; ?></td>
<td><?php echo $data->name; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data->location;
echo $data->email;
?>
</button>
</td>
</tr>
You could write a Codeigniter-controller which will return email and location
Then you write Javascript-functions which will call this controller to retrieve the data asJSON-Data
Both, writing a controller which returns JSON and an example how to call this controller from JS can be found here:
Code Igniter - How to return Json response from controller
Try like this..
MODEL:
public function record_count() {
return $this->db->count_all('users');
}
public function fetch_data($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
}
}
return false;
}
View:
<tr>
<th>username</th>
<th>name</th>
<th>more</th>
</tr>
<tr>
<?php foreach ($results as $data) { ?>
<td><?php echo $data['username']; ?></td>
<td><?php echo $data['name']; ?></td>
<td>
<button type='button' class='btn'>
<?php echo $data['location'];
echo $data['email'];
?>
</button>
</td>
<?php } ?>
</tr>
I'm a really beginner in the ajax domain, and I really need help.
In fact I have done a query to receive some data from a database.
Here on the header I have:
<script type="text/javascript">
<?php if(isset($_GET['p']) AND $_GET['p']=='create_dossier') {?>
function writeInDiv(text){
var objet = document.getElementById('code_client');
objet.innerHTML = text;
}
function ajax()
{
var xhr=null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "ajaxclient.php?code_client=<?php echo $_GET['code_client'] ; ?>", false);
xhr.send(null);
writeInDiv(xhr.responseText);
setInterval("ajax()",5000);
}
<?php }?>
</script>
on the page ajaxclient.php I have the following code:
<?php require_once('Connections/localhost.php'); ?><?php mysql_select_db( $database_localhost ); ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
</head>
<body>
<table width="100%" border="0" id="box-table-a">
<tr>
<th scope="col" width="15%">CODE CLIENT</th>
<th scope="col" width="15%">RAISON SOCIALE</th>
<th scope="col" width="55%">ADRESSE </th>
<th scope="col" width="15%">ACTION</th>
</tr>
<?php
$code_client=$_GET["code_client"];
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
{?>
<tr>
<td><?php echo $donnees['code_client'] ; ?></td>
<td><?php echo $donnees['raison_sociale'] ; ?></td>
<td><p align="left"> <?php echo $donnees['rue'].'<br>'.$donnees['complement1'].'<br>'.$donnees['complement2'].'<br>'.$donnees['code_postal'].' - '.$donnees['ville'].'<br>'.$donnees['pays'] ; ?></p></td>
<td><a href="index.php?p=create_dossier2&code_client=<?php echo $data['code_client'] ; ?>"><img src="images/001_18.gif" width="24" height="24" /></td>
</tr>
<?php }
?></table>
</body>
</html>
The page called create_dossier.php contain:
<form action="#" method="get"><fieldset>
<legend>CRÉANCIER</legend>
<br />
<label>Raison sociale:</label><input type="hidden" name="p" value="create_dossier" /> <input type="text" name="code_client" onkeypress="form.submit()" /></fieldset><p align="center"><input type="submit" name="enreg" value="Chercher !" /></form>
What I would like is to display the data without sending the page and the thing is that it always send the form before returning any data. For that I do not need ajax.
I really do not know what wrong and how to correct it.
You should returning the result of query as XML or JSON and filling the tables with XML in calling file.
This is an example php.file (Need to convert to PDO)
require("dbinfo.php");
// Get parameters from URL
$code_client=$_GET["code_client"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($host, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$sql="SELECT * FROM `client` INNER JOIN `adresse_client` ON `client`.`code_client` = `adresse_client`.`code_client` WHERE `client`.`code_client`='".$code_client."'";
if (mysql_errno() <> 0)
{
echo mysql_error(),'<br>',$sql,'<br>';
die();
}
$result=mysql_query($sql);
while($donnees=mysql_fetch_assoc($result))
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
$node = $dom->createElement("client");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("'code_client'", $row['code_client']);
//$newnode->setAttribute("xxx", $row['xx']); list all other
}
}
echo $dom->saveXML();
?>
in fact, you should prevent form submitting like this:
onclick="return doSomeAction();"
function doSomeAction() {
// create XHR object
// send data
// handle response
return false;
}
doSomeAction() = ajax() in your case
don't forget to return false