Im fetching data from mysql db and putting it in json format.
fetch.php file:
echo $json; outputs the below to the console.
[{"id":"1","emp_no":"1111","first_name":"1fname","last_name":"1lname","dept_name":"1dept"},{"id":"2","emp_no":"2222","first_name":"2fname","last_name":"2lname","dept_name":"2dept"},{"id":"3","emp_no":"3333","first_name":"3fname","last_name":"3lname","dept_name":"3dept"},{"id":"4","emp_no":"4444","first_name":"4fname","last_name":"4lname","dept_name":"4dept"},{"id":"5","emp_no":"5555","first_name":"5fname","last_name":"5lname","dept_name":"5dept"},{"id":"6","emp_no":"6666","first_name":"6fname","last_name":"6lname","dept_name":"6dept"},{"id":"7","emp_no":"7777","first_name":"7fname","last_name":"7lname","dept_name":"7dept"},{"id":"8","emp_no":"8888","first_name":"8fname","last_name":"8lname","dept_name":"8dept"},{"id":"9","emp_no":"9999","first_name":"9fname","last_name":"9lname","dept_name":"9dept"}]
My controller looks like this:
.controller('fetchController', function ($scope, $http) {
$http.get("fetch.php")
.success(function (data) {
$scope.user = data;
console.log($scope.user);
});
$scope.user = data.data; Some suggested this but I get an undefined when I console.log($scope.user);
When $scope.user = data; console.log($scope.user); shows the same json output as above.
I then want to put this into my html table:
<table>
<tr>
<th>ID</th>
<th>Number</th>
<th>First</th>
<th>Last</th>
<th>Depart</th>
</tr>
<tr ng-repeat="x in user track by $index">
<td>{{x.id}}</td>
<td>{{x.emp_no}}</td>
<td>{{x.first_name}}</td>
<td>{{x.last_name}}</td>
<td>{{x.dept_name}}</td>
</tr>
But im getting no data returned to my page... Data is returned when I hardcode some json data but not when reading from the PHP query. Any ideas why?
.controller('fetchController', function ($scope, $http) {
$http.get("fetch.php")
.success(function (data) {
$scope.user = [{
"id": "1",
"emp_no": "1111",
"first_name": "1fname",
"last_name": "1lname",
"dept_name": "1dept"
}, {
"id": "2",
"emp_no": "2222",
"first_name": "2fname",
"last_name": "2lname",
"dept_name": "2dept"
}];
console.log($scope.user);
});
Returns:
Edit: Ive added more detail to the post so hopefully someone can see where the problem lies.
The problem is your "connected to db" output. You must remove that line from your PHP file and the rest should work as expected.
echo $json looked good because it is valid json, but since you had previously output text in your PHP script, the JSON decoding in Angular is breaking. If you look at the output you posted from the console, you see the "connected to db" text prefixing the JSON that you want in your application. That text prefix forces the output from PHP to be invalid.
Related
I know this is basic but i don't know what else i can do. So i need your help. Ill tell you what happened.
The story is that i have a database request and I want to json encode the data from that request and use it through a javascript file ($.ajax or $.json).
the data i need from that request are two values. Latitude and longitude. but when i receive the json_encode from php and put it in the console log or an alert it displays undefined instead of the "double precision"(because the json string).
Ill show you the code.
the php
<?php
$dbconn3 = pg_connect
("host= localhost port=5432 dbname=EmergenciesResponse user=postgres password=asdf");
$query1=pg_query
("select latitude, longitude from emergency where id_emergency=5");
$arreglo=array();
while($reg=pg_fetch_assoc($query1)){
$arreglo[]=$reg;
}
echo json_encode($arreglo);
pg_close($dbconn3);
?>
Then the .js code
$.ajax({
url: 'consulta2.php',
data:{
},
method: 'POST',
dataType:'json',
success: function(data)
{
alert("latitude:"+data.latitude+"longitude:"+data.longitude);
}
});
As I said when I do an alert instruction the output prints undefined but the string of the php is correct. Sorry if its very easy but I don't know what to do about the undefined value
thx for your time.
Your PHP returns an array of objects. The response will look like this (without pretty print):
[
{
"latitude": 0.000,
"longitude": 0.000
},
{
"latitude": 1.000,
"longitude": 2.000
},
{
"latitude": 3.000,
"longitude": 4.000
}
]
However, in JS you are treating is as an object.
You would understand what the problem is if you simply opened your consulta2.php file and looked at the response.
There can be two causes:
id_emergency is not unique. Then, your PHP is good, but in JS you need to iterate through the array:
$.ajax({
url: 'consulta2.php',
data:{
},
method: 'POST',
dataType:'json',
success: function(data)
{
$.each(data, function() { // <-------
alert("latitude:"+this.latitude+"longitude:"+this.longitude);
});
}
});
You will get from 0 to many alerts, one for every pair of coordinates.
id_emergency is unique. Then, your JS is good, but in PHP you do not need to form an array. It should be as simple as:
$query1=pg_query("select latitude, longitude from emergency where id_emergency=5");
//$arreglo=array(); // don't need an array
$reg = pg_fetch_assoc($query1); // only 1 object
echo json_encode($reg); // encode the object, but not an array
pg_close($dbconn3);
As this is the single object, you will get only one alert.
I think there is a problem in your while loop, I think you are overwriting the same index in the loop, you should be increment the index at each iteration.
var counter = 0;
while($reg=pg_fetch_assoc($query1)){
$arreglo[counter]=$reg;
counter++;
}
I have a weird problem with parsing a JSON response coming from php source (symfony2). This is probably something very trivial but I'm not very skilled in javascript so have lost many hours on this already.
I have a serialized php-array in my db, which I unserialize and then convert to JSON.
$response->setContent(json_encode(unserialize($onderdeel->getArticles())));
On the client I just use jQuery to parse the json data.
$.ajax({
......
success: function(data){
articleObject = jQuery.parseJSON(data);
}
});
However this gives me some weird results, some of the values are set to undefined while they should have a value. However some of the values are ok.
This is the raw result I get from the php script before it get's parsed:
{
"onderdeel":{
"onderdeel_id":"1546",
"onderdeel_type":"overgordijnen160",
"onderdeel_naam":"",
"onderdeel_opmerkingen":"",
"berekend_prijs":"0",
"status":"",
"active_artikel_id":"0",
"naam_ruimte":"",
"opmerkingen":""
},
"artikels":[
{
"ruimte":"",
"opmerkingen":"",
"korting":"",
"berekend_aantal_banen":"2",
"aantal_banen_zelf_ingegeven":"",
"berekend_hoeveelheid":"400",
"berekend_multiplicator":"1.9",
"berekend_valide":"",
"berekend_prijs_met_korting":"0.00",
"berekend_prijs":"20040040.00",
"stap2":{
"valide":"valide",
"hoogte":"100",
"breedte":"100",
"banen":"stel",
"stof":{
"id":"9",
"naam":"AGRA",
"modelnummer":"123456",
"stofbreedte":"140.00",
"rapporthoogte":"100.00",
"kleur":"nul",
"prijspermeter":"100.00",
"wasvoorschriften":"COOL WASH COOL IRON",
"stock":" "
},
"railtype":{
"id":"7",
"naam":"rails type 1",
"modelnummer":"RT-2",
"stock":"200.00 stuks",
"rapporthoogte":"null",
"prijspermeter":"null",
"wasvoorschriften":"null"
}
},
"maakwijze":{
"status":"",
"maakwijze_type":"lint",
"plooi":"",
"retour_plooi":"",
"cm_plooi":"",
"hoofdje":"100",
"berekende_string":"LINT > gewone voering",
"voering_string":"gewone voering",
"voering":{
"voering_id":"",
"voering_prijs":"",
"voering_onderdeel":"",
"voering_type":""
},
"voering_aan":"true",
"confectie":{
"confectie_id":"2",
"confectie_prijs":"10000000.00",
"confectie_zoom":"25.31",
"confectie_onderdeel":"OG < 160",
"confectie_type":"LINT > gewone voering"
},
"valide":"valide",
"loodjes":"loodjes"
},
"prijs":{
"prijs_valide":"",
"prijs_korting":"",
"prijs_plaatsing":"",
"prijs_berekend_voor_artikel":"",
"prijs_berekend_voor_artikel_met_korting":"",
"prijs_berekend_stofprijs":"40000",
"prijs_berekend_confectieprijs":"20000000",
"prijs_berekend_prijslood":"40",
"prijs_berekend_voering":"0",
"prijs_railtype_prijs":""
}
}
],
"onderdeel_naam":"",
"onderdeel_opmerkingen":""
}
However after I parse it this is the result:
For example artikels.0.maakwijze.maakwijze_type is set to undefined while in the raw json it is set to 'lint'.
The weird thing is that if I just copy the raw json to the chrome console and parse it with the same function jQuery.parseJSON('copied text') all values are ok
I also replaced the jQuery.parseJSON with the standard JSON.parse , but this gave me the same result
Any ideas what causes this?
Thanks!!
On the client I just use jQuery to parse the json data.
$.ajax({
......
success: function(data){
articleObject = jQuery.parseJSON(data);
If your server is returning Content-Type: application/json, data will already be a parsed object. You don't want to parse it again.
Without the jQuery.parseJSON(data), it works for me (source).
I am trying to dynamically fetch the data from a PhP module, load it as JSON data into javascript and use this data to generate a Pie chart using HighCharts. The Pie chart is generating properly when I am using some static data but not loading when I am parsing JSON data and feeding that as input to the Highchart series object. I am sure this is something to do with the formatting of data while inputting to Highcharts but I am not able to figure that out for sometime now :( So thought would just reach out to you guys . I have attached the code here and the sample json output generated by the php module for your reference.
Sample JSON input generated from PhP module : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]. Need to parse this JSON input and feed as input to my HighCharts series object to generate a pie-chart showing "html" and "css" as pie-slices.
Any guidance would be appreciated.
Thanks.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Top Skills Analytics</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="highcharts.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2" align="center"><u><b><font size="4">Top Skills Analysis</font></b></u>
</td>
</tr>
<tr>
<td>
<div id="container" style="height: 500px; width: 500px; margin-bottom: 1em;"></div>
</td>
</tr>
</table>
<script type="text/javascript">
// Creates the HighChart using the dynamically generated data from PhP module
function loadCharts() {
// Parses the JSON data and returns an array of an array
var result = [];
// json from php is like : [{"skill":"html","count":"158"},{"skill":"css","count":"134"}]
$.getJSON('test.php', function (json) {
$.each(json, function (i, entry) {
result.push(entry.skill, entry.count);
});
});
//result = [["html",158],["css",134]]; --> this works
var options1 = {
"series": [{
"name": "Jobs",
"type": "pie",
"sliced": true,
"data": result, // works when populated with static value like [["html",158],["css",134]]
"pointWidth": 15,
"color": "#C6D9E7",
"borderColor": "#8BB6D9",
"shadow": true,
}],
"title": {
"text": "Top Skills Analytics"
},
"legend": {
"layout": "vertical",
"style": {
"left": "auto",
"bottom": "auto",
"right": "auto",
"top": "auto"
}
},
"chart": {
"renderTo": "container"
},
"credits": {
"enabled": false
}
};
var chart1 = new Highcharts.Chart(options1);
}
// Load the charts when the webpage loads for the first time
$(document).ready(function () {
loadCharts();
});
</script>
</body>
It works with static data because the count is an int
["html",158]
And it doesn't work with dynamic data because it returns a string count
{"skill":"html","count":"158"}
Notice the double quotes around the second code line?
You need to either cast your string to an int in php or in javascript before passing it to highcharts
And another thing, if you run the code highcharts should complain with an error
Uncaught Highcharts error #14: www.highcharts.com/errors/14
If you visit the link it basically says the same thing about strings.
There is another thing wrong with the code
[["html",158],["css",134]]
As you can see here we have an array of arrays and when we run your code with string to int parsing we get
["html", 158, "css", 134]
Notice the problem? We have an array of four elements.
What you need to do is:
result.push([entry.skill, entry.count]);
Push an array of two elements to the result variable and don't forget that count must be an int
Try this,
result.push([entry.skill, parseInt(entry.count)]);
I have this AJAX:
$.ajax({
url : get_base_url() + 'update',
type : 'POST',
async : false,
data : json_positions,
dataType : 'html',
success : function(data) {
console.log(data);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log('error:');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown)
}
});
data sent is:
json_positions
which is a string like this:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
I want to decode json_positions using json_decode() in a PHP page but it seem that tdata is not sent to the php page because when i try to:
print_r($_POST);
it returns an empty array using console.log(data).
Well your code is okay, no need to change anything. But it's how you pass your data.
data sent is: json_positions which is a string like this: ...
You should not pass it like string. It should be an object like you defimed it:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
Make you sure you pass an object, not string, e.g. don't add any quotes around it etc. Then it's going to work fine.
EDIT
As per jQuery documentation for $.ajax data parameter:
dataObject, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your data should be a query string or an object.
In your case I recommend to use object. Like with this code:
var json_positions = {
new_positions: []
};
$.each(result, function(key, value) {
var value_splitted = value.split('-');
json_positions.new_positions.push({
id: value_splitted[1],
position: key
});
});
Since you are sending json data, you need to define the appropriate content type:
contentType: 'application/json'
Also, change the dataType to json if you are expecting json data back:
dataType : 'json'
$_POST only contains key value pair stuff. Your POSTed JSON is in $_HTTP_RAW_POST_DATA.
As it stands, I have some JQuery along these lines -
ph=function(i){
$.each(i,function(po){
id=po.id;url="/"+id;t=$('<div id='+ id +' class=entry></div>');
t.html('<div class=hx>'+ po.author +'</div><div class=b>'+ po.body +'</div>');
t.prependTo($("#modpskx"));
t.hide();
t.slideDown("slow");});};
function mtoxps(){
mid=$("#xsodl").val();
id=$("#modpskx > div:first")[0].id;
if(id==""){id=0}
$.ajax({
url:'/widgets/live.php',
data:{'id':id,'mid':mid},
type:'post',
dataType:'json',
cache:false,
success:function(b){ph(b);}});}
setInterval("mtoxps()", 10000);
The JSON data sent back to the browser by the server is as follows:
[{
"author": "NiX",
"timestamp": "2009-12-20 21:35:32",
"id": "194",
"mig_id": "3",
"body": "Cows.",
"ip": ""
}]
This - every 10 seconds - successfully requests any new results. Unfortunately, the "ph" variable (what is used to return and display the result(s)) isn't properly parsing the returned output. Instead, it displays all the variables as undefined, resulting in the next request to send the server an "undefined" variable, as well.
Are there any suggestions as to why this isn't functioning?
Try:
$.each(i, function(index, po){
instead of
$.each(i, function(po){
The callback for the each function is at the bottom of this page.