After some hours dealing with it, i'll be specific.
I'm trying to pass data from a table on angular (view), to the controller, the controller call to a factory and it last make an http request to a .php file.
It isn't so hard as it seems.
This is the error i'm getting
}
Trying to get property of non-object on line 6
It's my .php file (to get a simple select query)
// Including database connections
require_once '../../db/database_connections.php';
// Fetching and decoding the inserted data
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * from repartidor WHERE id_repartidor = '$data->codigo'"; //THIS is **line 6**
$result = mysqli_query($con, $query);
$arr = array();
$row = mysqli_fetch_assoc($result);
$arr[0] = $row;
// Return json array containing data from the databasecon
echo $json_info = json_encode($arr[0]);
?>
However, after debugging it for a while, the query and the response of the .php file does work (i prove it replacing the '$data->codigo' with the value).
I think the problem is that the data is not reaching or is incorrectly being decoded.
Factory code:
obtenerItem: function(item){
return $http.post("http://localhost/sgzena/php/repartidor/repDetail.php", item);
} //THERE is an update
Controller code:
$scope.actualizarItem = function (item) {
repartidorFactory.obtenerItem(item) //aca iba ID
.then(function (response) {
var modal = abrirModal(response.data);
modal.result.then(function(result) {
guardarRepartidor(result);
});
});
}
View code:
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Cod.</th>
<th>Nombre</th>
<th>Telefono</th>
<th>
<em class="glyphicon glyphicon-cog" tooltip-placement="top" uib-tooltip="Acciones"></em>
</th>
</tr>
</thead>
<tbody ng-repeat="item in repartidores">
<tr class="odd gradeX">
<td>{{item.id_repartidor}}</td>
<td>{{item.nombre}}</td>
<td>{{item.telefono}}</td>
<td>
<a class="btn btn-default glyphicon glyphicon-edit " tooltip-placement="bottom" uib-tooltip="Editar Repartidor" data-toggle="modal" ng-click="actualizarItem(item)"></a>
<a class="btn btn-default glyphicon glyphicon-trash " tooltip-placement="bottom" uib-tooltip="Eliminar Repartidor" ng-click="eliminarItem(item)"></a>
</td>
</tr>
</tbody>
</table>
These are the lines which i modified and the code started to work:
old:
$data = json_decode(file_get_contents("php://input"));
$query = "SELECT * from repartidor WHERE id_repartidor= '$data->codigo'";
Solved:
$data = json_decode(file_get_contents("php://input"));
$id_repartidor = mysqli_real_escape_string($con, $data->id_repartidor);
$query = "SELECT * from repartidor WHERE id_repartidor= '$id_repartidor'";
Related
I am trying to display database records to my console in json format but i can't see why my request in json format is not being displayed on my console. There is no error also to guide me where i made a mistake. can someone help me. I use the MVC framework for writing my code. I want to retrieve horse names based on race number from the race table in the database.
here is my home.php
<div class="box-body">
Start creating your amazing application!
<table class="table table-bordered table-striped dt-responsive tables" width="100%">
<thead>
<tr>
<th style="width:10px">#</th>
<th>id</th>
<th>Race Number</th>
<th>Horse Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$users = ControllerUsers::ShowallUsersCtr();
foreach ($users as $key => $value) {
echo '
<tr>
<td>'.($key+1).'</td>
<td>'.$value["id"].'</td>
<td>'.$value["racenumber"].'</td>
<td>'.$value["horsename"].'</td>';
echo '<td>
<div class="btn-group">
<button class= "btn btn-primary btnAddRace" RaceNumber="'.$value["racenumber"].'" data-toggle="modal" data-target="#editUser">Add Horse - Race 1</button>
</div>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
here is my javascript file code named users.js
$(document).on("click", ".btnAddRace", function(){
var RaceNumber = $(this).attr("RaceNumber"); // capture the race number from database to the console
console.log("RaceNumber",RaceNumber);
var data = new FormData();
data.append("RaceNumber",RaceNumber);
$.ajax({
url: "ajax/users.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(answer){
console.log("answer", answer); // bring from the database whatever we asked for
}
});
});
And here is my Ajax file users.ajax.php
<?php
require_once "../controllers/users.controller.php";
require_once "../models/users.model.php";
class AjaxUsers{
public $RaceNumber;
public function ajaxEditUser(){
$item = "racenumber";
$value = $this->RaceNumber; // value what is selected from the table
$answer = ControllerUsers::ctrShowUsers($item, $value); // ask for the controller to show me the race table
echo json_encode($answer);
}
}
if (isset($_POST["RaceNumber"])) { // if the variable race number comes with information, we can execute all of this
$edit = new AjaxUsers();
$edit -> RaceNumber = $_POST["RaceNumber"];
$edit -> ajaxEditUser();
}
here is my user controller and model methods
static public function ctrShowUsers($item, $value){
$table = "race";
$answer = UsersModel::MdlShowUsers($table, $item, $value);
return $answer;
}
static public function MdlShowUsers($table, $item, $value){
$stmt = Connection::connect()->prepare("SELECT * FROM $table WHERE $item = :$item");
$stmt -> bindParam(":".$item, $value, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetch();
$stmt -> close();
$stmt = null;
}
Database Picture is here
enter image description here
I want to refresh the jquery datatable every 3 seconds. I already done this but I have pagination issues. When I execute the code the pagination is gone so all the data is display without pagination.
Here is my code:
<div id="timexx">
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
<?php
include('../dist/includes/dbcon.php');
$query=mysqli_query($con,"SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC")or die(mysqli_error());
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
?>
<tr>
<td>
<?php echo $id;?>
</td>
<td>
<?php echo $name;?>
</td>
</tr>
<?php }?>
</table>
</div>
And this is my javascript code:
$(document).ready(function() {
setInterval(function() {
$('#timexx').load(location.href + " #timexx>*", "")
}, 3000);
});
I would recommend using an ajax data source along with ajax.reload(). In fact, the docs page I linked there has an example of just what you are after.
For your markup you can simply create the table and header:
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
</table>
Then initialize datatables with ajax data source, declare your columns and start the loop:
$(document).ready( function () {
var table = $('#example1').DataTable({
"ajax" : 'http://example.com/table_data.php',
"columns" : [
{ "data" : "id" },
{ "data" : "name" )
]
});
setInterval(function () {
// the second argument here will prevent the pagination
// from reseting when the table is reloaded
table.ajax.reload( null, false );
}, 3000);
});
Now you need a web page at the endpoint declared for your ajax data source http://example.com/table_data.php that spits out the table data as a json. There are a few ways this can be structured, but my preference is to use the data property as the docs state:
the data parameter format shown here can be used with a simplified DataTables initialisation as data is the default property that DataTables looks for in the source data object.
With this objective, your php script might look something like this:
include('../dist/includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC") or die(mysqli_error($con));
$results = [];
while ($row=mysqli_fetch_array($query)) {
$results['data'][] = [
'id' => $row['id'],
'name' => $row['name']
];
}
echo json_encode($results);
Side note, mysqli_error() expects a single argument which should be your connection resource.
I ran into an issue for which I cannot find the answer, I rarely ask questions here, but I am rather stumped. Any assistance shall be appreciated.
This is the PHP that receives the Ajax call.
<?php
session_start();
$_SESSION["my_data"] = $_POST['action'];
$DB_HOSTNAME = 'localhost';
$DB_USERNAME = 'username';
$DB_PASSWORD = 'password';
$link2 = mysqli_connect($DB_HOSTNAME,$DB_USERNAME,$DB_PASSWORD) or die('Unable to establish a DB1 connection');
mysqli_select_db($link2, '$DB_USERNAME');
$orderQuery = mysqli_query($link2, "SELECT * FROM table WHERE id='".$_SESSION['my_data']."'");
$orderQuery = mysqli_fetch_assoc($orderQuery);
$orderInfo = "
<table class='table table-striped'>
<tbody>
<tr>
<td>#: </td>
<td>". $_SESSION['my_data'] ."</td>
</tr>
<tr>
<td> Full name: </td>
<td>". $orderQuery['firstname'] . " " . $orderQuery['lastname'] ."</td>
</tr>
<tr>
<td> Address: </td>
<td> ". $orderQuery['shipping_address_1'] ."<br> ". $orderQuery['shipping_city'] . " " . $orderQuery['shipping_zone'] . " " . $orderQuery['shipping_postcode'] ." </td>
</tr>
<tr>
<td> Card Expiry Date Month: </td>
<td> 08 </td>
</tr>
</tbody>
</table><br>
";
echo $orderInfo/* . $_POST['action']*/; ?>
And this is the script that makes the call.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var myWindow;
function myFunction() {
myWindow = window.open('', '_blank');
myWindow.document.write("<link rel='stylesheet' type='text/css' href='stylesheet.css'>");
var orderNum;
orderNum = document.getElementsByClassName('summary_value')[0].innerHTML;
orderNum = orderNum.replace("#", "");
$.ajax( { type : 'POST',
data : {'action':orderNum},
url : 'process.php',
success: function ( data ) {
myWindow.document.write( data );
},
error: function ( xhr ) {
alert( "error" );
}
});
myWindow.document.write("<br>");
myWindow.document.write(document.getElementById("payInfor").innerHTML);
}
</script>
<button onclick='myFunction()' class="btn btn-default">Print Pay Info</button>
It could be a simple issue, but I can't see it.
I know the Ajax is working because it displays some of the information ($_SESSION['my_data']), so I am thinking it's something with my SQL statements, but the syntax looks correct.
At first glance i think that mysqli_select_db($link2, '$DB_USERNAME'); here is the error.
it must be mysqli_select_db($link2, $DB_USERNAME); or mysqli_select_db($link2, $DB_NAME);
mysqli_select_db() expects parameter one to be the connection and parameter two to be the database name. In your case you are passing '$DB_USERNAME'. So your code will look to connect to database named '$DB_USERNAME' because of the single quotes. Change it to the database name instead. Either $DB_NAME or 'database_name' should work. While in development mode, try enabling error_reporting(E_ALL) to catch errors like this.
try to replace this mysqli_fetch_assoc with mysqli_fetch_array
and ($link2, "SELECT * FROM table WHERE id='".$_SESSION['my_data']."'")
with ($link2, "SELECT * FROM table WHERE id=".$_SESSION['my_data']."")
note: remove single quote (' ') for id
I've having some issue with the Javascript. I have a table that shows the basic information of the customer when an employee conduct a search base on the customer name. When the employee clicks on "View Sales History" the hidden table row of the particular customer's sales history will appear.
I've have no problem displaying the sales history of all the customer's returned from the search when I change the css display to "table-row". However it would only display the first customer's sales history whenever I hide the table row and include the javascript to display the hidden row.
This is what I've tried doing so far, hopefully someone can help me out here.
while($row = mysql_fetch_assoc($result)) {
$id = $row["id"];
$cfname = $row["f_name"];
$clname = $row["l_name"];
$cemail = $row["email"];
$ccompany = $row["company_name"];
$year = $row["year"];
$product = $row["product"];
$employee = $row["employee"];
$status = $row["status"];
echo '<tr>
<td>'.$cfname.' '.$clname.'</td>
<td>'.$cemail.'</td>
<td>'.$ccompany.'</td>
<td> <h4 id="vsalesHistory" onclick="vsalesHistory()">View Sales History</h4></td>
</tr>';
echo '<thead id="salesHistoryHead">
<tr>
<th>Date of Sales</th>
<th>Type of Product</th>
<th>Previous Sales Manager</th>
<th>Job Status</th>
</tr>
</thead>';
echo '<tr id="salesHistory">
<td>'.$year.'</td>
<td>'.$product.'</td>
<td>'.$employee.'</td>
<td>'.$status.'</td>
</tr>';
}
echo '</table>';
and this is my JS script
function vsalesHistory(){
var e = document.getElementById('salesHistoryHead');
var f = document.getElementById('salesHistory');
if(e.style.display == 'table-row'){
e.style.display = 'none';
}else{
e.style.display = 'table-row';
}
if(f.style.display == 'table-row'){
f.style.display = 'none';
}else{
f.style.display = 'table-row';
}
}
You are creating multiple rows with the same ID, which is not a good idea. Instead, use the row ID to create unique iDs, like:
echo '<thead id="salesHistoryHead' . $id . '">
<tr>
<th>Date of Sales</th>
<th>Type of Product</th>
<th>Previous Sales Manager</th>
<th>Job Status</th>
</tr>
</thead>';
echo '<tr id="salesHistory' . $id . '">
<td>'.$year.'</td>
<td>'.$product.'</td>
<td>'.$employee.'</td>
<td>'.$status.'</td>
</tr>';
Then pass the ID with the button action, e.g.
<td> <h4 id="vsalesHistory" onclick="vsalesHistory(' . $id . ')">View Sales History</h4></td>
If $id is a string, you would need to quote it in the call to vsalesHistory.
Now you can use the ID in your Javascript to pick the single right set of information.
For example:
function vsalesHistory(id){
var e = document.getElementById('salesHistoryHead'+id);
var f = document.getElementById('salesHistory'+id);
...
I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.