Angular Display Data From Array - php

I am new to angularJS and has very few knowledge on javascript.
I am trying to retrieve data from database by using the $http.post method. below is what I get from the .php file.
[{
"ticketid": "1484637895",
"categoryid": "1",
"subcategoryid": "2",
"ciphonenum": "01814149028",
"calldescription": "The customer wanted to know all the SKU of Bashundhara Baby Diaper and he requested to inform him through the mail.",
"ccrreply": "CCR sent him all SKU of Diaper including the M.R.P.",
"ccraction": "N\/A",
"output": "N\/A",
"remarks": "N\/A",
"contactinfoname": "MD.Masud",
"ciaddress": "Banani,DOHS\nDhaka."
}]
Here is what my php file looks like
<?php
$data = json_decode(file_get_contents("php://input"));
require 'db-config.php';
$ticketid = $data->id;
$sql = "SELECT t.ticketid, t.categoryid, t.subcategoryid, td.ciphonenum, td.calldescription, td.ccrreply,
td.ccraction, td.output, td.remarks, ci.contactinfoname, ci.ciaddress FROM ticketdetails td
INNER JOIN tickets t on t.ticketid = td.ticketid
INNER JOIN contactinfodetails ci ON ci.ciphonenum = td.ciphonenum WHERE t.ticketid = '$ticketid'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
} else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
?>
Below is the function in angularjs which generate the post request
$scope.showTicket = function() {
var id = $routeParams.id;
$http.post('api/showTicket.php',{'id':id}).then(function(response){
$scope.ticket = response.data;
console.log($scope.ticket);
});
};
I want display only the ticketid and calldescription from the array but whenever I assign value like
$scope.ticketid = $scope.ticket.ticketid;
it says undefined variable. Please help....

Your JSON is an array of objects, and not an object.
So instead of doing $scope.ticketid = $scope.ticket.ticketid, try:
$scope.ticketid = $scope.ticket[0].ticketid;
As your array only contains one object, it is probably the solution...

Related

AngularJS ng-repeat not showing data in table

I have a problem with output from MySQL
getCustomers.php is
$query="select distinct c.ancestry, c.trusted from members c order by c.id";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$arr = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = json_encode($row);
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
and controler code:
app.controller('customersCrtl', function ($scope, $http, $timeout) {
$http.get('ajax/getCustomers.php').success(function(data){
$scope.list = data;
$scope.currentPage = 1; //current page
$scope.entryLimit = 100; //max no of items to display in a page
$scope.filteredItems = $scope.list.length; //Initially for no filter
$scope.totalItems = $scope.list.length;
});
$scope.setPage = function(pageNo) {
$scope.currentPage = pageNo;
};
$scope.filter = function() {
$timeout(function() {
$scope.filteredItems = $scope.filtered.length;
}, 10);
};
$scope.sort_by = function(predicate) {
$scope.predicate = predicate;
$scope.reverse = !$scope.reverse;
};
});
Problem is that i get from MySQL this format (e.g.):
["{\"ancestry\":\"12865794218\",\"trusted\":\"128\"}"]
but expectable is:
[{"ancestry":"1286794218","trusted":"126"}]
so, if I write constants in data it works perfectly fine
$scope.list = [{"ancestry":"1286794218","trusted":"126"}];
Thanks for any help.
You're double-encoding your response. The backslashes are there because the second application of json_encode escapes the double quotes in the output of the first one. Remove the json_encode from inside your while loop.
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$arr[] = $row; // don't encode here
}
}
Then just encode it once afterward (as you already are.)
$json_response = json_encode($arr);
I think you need to use header('Content-Type: application/json'); in your php code, so that the server responds with a JSON content type.
There is also a duplicate json_encode in your code, inside your while loop so you're doing duplicate json encoding, hence the unexpected output
use JSON.parse() on your response. JSON.parse docs

Insert new array to php json

I tried to push a new array value to JSON
$var=array("code"=>"100");
$sql = SELECT order as orderID, pub as orderCode from cart
while ($row = mysql_fetch_assoc ($sql) {
$var[] = $row;
}
echo '{"status":'. json_encode($var).'}';
I want push this string to the JSON array above
$string = array("total"=>"3000");
and my script displays like this:
{
"status":{
"code":"100",
"0":{
"total":"3000"
},
"1":{
"orderID":"16",
"orderCode":"14290290685322"
},
"2":{
"total":"3000"
}
}
}
and I want var total inside like this:
**////////blablabla
"1":{
"orderID":"16",
"orderCode":"14290290685322",
"total":"3000"
}
*///blablba
Add $var[] = array("total"=>"3000"); just before you encode to JSON
$var=array("code"=>"100");
$sql = SELECT order as orderID, pub as orderCode from cart
while ($row = mysql_fetch_assoc ($sql) {
$row['total'] = '3000' ;
$var[] = $row;
}
echo '{"status":'. json_encode($var).'}';

$.each() loop through json not looping

i have an ajax call that gets back json i am trying to send the items returned to specific input text id's.
This is the ajax:
$.ajax({
url: "php/myfirstfile.php",
type: "POST",
data: $("#frameroof").serialize(),
cache: false,
dataType: "json",
success: function (json) {
$.each(json, function () {
$.each(json, function (key, value) {
/// do stuff
$('#' + key ).val(value);
});
});
}
});
This is what is returned: [{"a-frame":"100"}][{"vertical":"350"}]
it looks im getting 2 arrays when i need one to loop over. Im not sure.
Here is the php
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
$results = array();
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
//dump all data from associative array converted from query result
echo (json_encode($results,true));
$result->free();
}
}
}
}
$short_connect->close();
I believe your problem is pretty simple. Inside of your loop you're initializing the results array and you're outputting it. This causes a new results array to be created, serialized to JSON, and outputted for every iteration of the loop. Thus what you're sending the browser is not JSON, but several chunks of JSON all run together.
This is the basic idea of what you need to be doing:
<?php
// Initialize the output data
$results = array();
foreach($something as $a_something) {
$results[] = do_something_to($a_something);
}
//Serialize and send the output data
echo (json_encode($results,true));
Rearranging your code with that pattern in mind produces this (which ought to work for you, and will return an empty array to the browser if your if conditions aren't met or the query doesn't return anything):
<?php
// Initialize the output data
$results = array();
if(isset($_POST["cart"])){
$frameArray = ($_POST["cart"]);
if(is_array($frameArray)){
foreach($frameArray as $row){
$catalogue = $row['catalogue'];
$certification = $row['certification'];
$catagory = $row['catagory'];
$subcatagory = $row['subcatagory'];
$length = $row['length'] ;
$sql = "SELECT `price` AS '$subcatagory' FROM `products` WHERE `catalogue_id` = '$catalogue' AND `certification` = '$certification' AND `catagory` = '$catagory' AND `sub_catagory` = '$subcatagory' AND `length` = '$length' ";
$result = $short_connect->query($sql);
if (($result) && ($result->num_rows > 0)) {
//convert query result into an associative array
while ($row = $result->fetch_assoc()) {
//Add to the output data
$results[] = $row;
}
$result->free();
}
}
}
}
$short_connect->close();
//Serialize and send the output data
//dump all data from associative array converted from query result
echo (json_encode($results,true));

Formatting json data to work in Flot

Is there anyway to convert this json data:
[
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
]
to like this:
{
"data": [[1999, 3.0], [2008, 0.9]]
}
Check type of values ("3.0" and 3.0, string and integer).
I am having hard time to figure this out, or is it even possible.
This is how I get the json data:
I have "data" table in my database where are "year" and "value" columns, I get them from database like:
$sql = mysql_query("SELECT * FROM data");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$encodedJson = json_encode($rows);
$encodedJson = json_encode($rows);
print $encodedJson;
I am trying to create a graph from my data, and json data must be formated properly to work in Flot.
All help is appreciated!
You could map your array of objects into an multidimensional array:
var mapped = originalData.map(function (obj) {
return [ parseInt(obj.year, 10), parseFloat(obj.value) ];
});
var newData = {
data: mapped
};
Possible solution
var a = [
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
];
var b = [];
$.each(a, function(_index, _item){
var c = [_item["year"], _item["value"]];
b.push(c);
});
console.log(b)
try this.
PHP:
$sql = mysql_query("SELECT * FROM data");
$rows = $sql->results_array();
$return_args = array();
foreach($rows as $row){
$tmp[0] = $row['year'];
$tmp[1] = $row['value'];
array_push($return_args,$tmp);
}
$encodedJson = json_encode($return_args);
print $encodedJson;

jQuery $.post not returning JSON data

I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.

Categories