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++;
}
Related
I have data coming from MySql, answered from this:
How to SQL query parent-child for specific JSON format?. Basically I query it using JSON_OBJECT() which produces the result:
results <-- The column name
{"projects": "project_name": "project 1", [2nd layer stuff]} <-- the row
Awesome. MySql did the json thing for me. I make an ajax call to a PHP function to get this onto the web server.:
myPhpFunction () {
//some usual PDO code
echo json_encode($query_result);
}
On JS, I make a jQuery ajax call:
var ajaxRequest =
$.ajax({
type: 'post',
url: '../includes/ajax.php',
data: 'action' : 'myPhpFunction',
dataType: 'json'
});
ajaxRequest.done(function(data) {
//$.each(data[0].results.projects, function(key, val){
//I want to access each stuff in the object here
//}
$('#ph-projects').append(JSON.stringify(data)); //testing it out
}
The problem I'm having is by this time, my object data outputs like this:
{ "results": "{...}" }
results value is a string because of those double quotes!
This is driving me crazy. Am I missing a step to prevent this from happening?
The json_encode() is working fine as it is providing the result as a JSON object as suggested by your question({ "results": "{...}" }). And JSON_OBJECT() in PDO returning a string is fine as the name JSON suggests, its JavaScript Object Notation in a humanly readable format.
You can do on the server side:
json_encode(['results'=> json_decode($query_result['results'])]);
or on client side,
function(data){
data.results = JSON.parse(data.results);
// Your json data here
}
I am getting data in a php file from db as
while ($row=mysqli_fetch_row($result))
{
printf ("beacon id : %s \n",$row[2]);
printf ("beacon uuid :(%s)\n",$row[3]);
}
now i want to append that data in table and show in JQueryUI Dialog box like this
In ajax success form i tried to create hardcore table and get data
success: function(response){
for (var i = 0; i < 3; i++) {
var row = $('<tr></tr>').appendTo(mytable);
for (var j = 0; j < 3; j++) {
$('<td></td>').text("text1").appendTo(row);
}
}
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
it is working fine
///////////////
when I tried to get to get my data in table its not working
I tried
success: function(response){
var table = $("#table tbody");
$.each(response, function(idx, elem){
table.append("<tr><td>"+elem.id+"</td></tr>");
});
$('<table></table>').appendTo("#dialog");
$("#dialog").dialog("open");
}
but it is not working ,
console.log is coming like
what can i modify to display data ?
You're not appending the table with data, instead you're creating a new empty table element and appending it.
Edit:
You also can't loop over a string (which is the ajax response). If you output the html in php things will be simpler. This is also untested but hopefully you get the idea.
php:
while ($row = mysqli_fetch_row($result)) {
printf("<tr><th>beacon id :<th> <td>%s</td><tr>", $row[2]);
printf("<tr><th>beacon uuid :<th> <td>(%s)</td><tr>", $row[3]);
};
js:
success: function (response) {
if (response) {
var table = $("#table tbody");
table.append(response);
table.appendTo("#dialog");
$("#dialog").dialog("open");
}
}
First, I would adjust your PHP so that it is sending back JSON data. The data you are sending back now is just text. It will not be read as an Object by JS.
PHP
$beacon = array();
while ($row=mysqli_fetch_row($result)){
$beacon[] = array("id" => $row[2], "uuid" => $row[3]);
}
header('Content-type:application/json;charset=utf-8');
echo json_encode($beacon);
See: Returning JSON from a PHP Script
This creates an array of arrays. The resulting page should be something like:
[
{
"id": "Beacon00UUID::fda50693-a4e2-4fb1-afcf-c6eb07647825",
"uuid": "(Beacon00RSSI::-69)"
},
{
"id": "Beacon01UUID::2f234454-f491-1ba9-ffaf-000000000001",
"uuid": "(Beacon01RSSI::-53)"
},
{
"id": "Beacon02UUID::b9407f30-f5f8-466e-aff9-25556b57fe6d",
"uuid": "(Beacon02RSSI::-75)"
},
{
"id": "Beacon04UUID::00000000-0000-0000-0000-000000000000",
"uuid": "(Beacon04RSSI::-88)"
},
]
This will allow your jQuery to collect the content as JSON. In your success callback, you can handle this better. this is also assuming you have dataType: "json" elsewhere in your AJAX call.
jQuery
success: function(response){
var $tbl = $("<table>");
$.each(response, function(key, val){
var $row = $("<tr>").appendTo($tbl);
if(key % 2 == 0){
$row.addClass("even");
} else {
$row.addClass("odd");
}
var $cell = $("<td>").html(val.id).appendTo($row);
});
$("#dialog").html($tbl.prop("outerHTML")).dialog("open");
}
Now, if your data was coming back with a key of beacon id, you would need to call this exactly. For example, it would not be elem.id, it would have to be elem['beacon id'] to call the right index in the object. You can't use the dot notation that includes a space in the index name. Bare that in mind when naming your indexes.
There is a subtle difference with $.each() and .each(), the former is designed for arrays and objects, with a key and value pair and the latter designed for jQuery objects, with an index and element pair. nothing wrong with what you did, just explaining why you might use one over the other.
Hope this helps. Let me know if something is not clear.
I have 3 different JSON objects I want to concatenate and send over to a PHP file with jQuery AJAX. I can retrieve the JSON object in the PHP file, but cannot figure out how to loop through the results.
Here's what I have so far:
//my 3 JSON objects:
var json_obj_1{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
var json_obj_2{
"test4_key":"test4_val"
}
var json_obj_3{
"json_arr":[
{
"test1":"test2",
"test3":"test4"
}
]
}
//concat these to send over to the PHP file:
var my_json_obj = json_obj_1.concat(json_obj_2);
//I found if I didn't stringify obj_3 they didn't concatenate for some reason
my_json_obj = my_json_obj.concat(JSON.stringify(json_obj_3));
//my_json_obj now looks like this:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Based on this question: Sending JSON to PHP using ajax, I don't stringify the final JSON object.
Here's the AJAX call to the PHP file:
$.ajax({
url: 'my_php_file.php',
data: {my_json_data: my_json_obj},
type: 'POST',
async: false,
dataType: 'json',
cache:false,
success:function(data, textStatus, jqXHR){
console.log('AJAX SUCCESS');
},
complete : function(data, textStatus, jqXHR){
console.log('AJAX COMPLETE');
}
});
This is what it looks like when retrieved in my PHP file:
echo $_POST['my_json_data'];
//outputs:
{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
}
{
test4_key: test4_val
}
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}
Here's where I run in to problems. I want to be able to loop through this in a foreach. From what I have read (php: loop through json array) I have to decode the JSON object. However when I do this and loop through the results I get: " PHP Warning: Invalid argument supplied for foreach() ".
Even if I stringify the JSON object before sending it over to the PHP file I get the same problem. I have been banging my head against a brick wall for hours with this. Any help will be massively appreciated.
Thanks in advance.
Solved:
I was going wrong when concatenating my JSON objects following this question: Merge two json/javascript arrays in to one array. Instead I just put them together like so:
my_json_obj = '['+json_obj_1+','+json_obj_2+', '+JSON.stringify(json_obj_3)+']';
I then use json_decode in my PHP file which works a treat. http://json.parser.online.fr/ was invaluable in debugging my dodgy JSON. A great tool for JSON beginners.
You should be stringifying the whole object, try the following:
var my_json_obj = json_obj_1;
$.each(json_obj_2, function(key,value){
my_json_obj[key]=value;
});
$.each(json_obj_3, function(key,value){
my_json_obj[key]=value;
});
Ajax request:
data: {my_json_data: JSON.stringify(my_json_obj)},
PHP:
print_r(json_decode($_POST['my_json_data']));
As you say you need to decode the JSON, but your JSON is not well formed so I think the decode function is failing which causes the foreach error. There needs to be a , between objects, there's missing quotes around test4_val and it needs to be inside a singular object/array
You can check your JSON is wellformed at:-
http://json.parser.online.fr/
I think you want it to look more like:-
[{
"test1_key":"test1_val",
"test2_key":"test2_val",
"test3_key":"test3_val"
},
{
"test4_key": "test4_val"
},
{
"json_obj_3":[
{"test1":"test2","test3":"test4"}
]
}]
I've been working on this for quite a while, and I've read TONS of posts on SO trying to figure out how I need to do this, and I can't seem to get it to work. I'm thinking it must be some aspect of the way I've coded things. So downvote away, but hopefully some kind soul will help me out.
I've tested using jsonlint, which comes back valid. I'm getting a response from the server with the values, I just can't seem to get anything in the browser other than when I just alert(response);. I need to be able to access the value of "cat_id_PK" and the other elements separately to loop through and display them in html table cells.
JSON:
{
"income": [
{
"cat_id_PK": 14,
"cat_name": "test1",
"cat_amount": "100.00"
},
{
"cat_id_PK": 15,
"cat_name": "test2",
"cat_amount": "200.00"
},
{
"cat_id_PK": 34,
"cat_name": "test3",
"cat_amount": "300.00"
},
"expense": [
{
"cat_id_PK": 14,
"cat_name": "tes41",
"cat_amount": "400.00"
},
{
"cat_id_PK": 15,
"cat_name": "test5",
"cat_amount": "500.00"
},
{
"cat_id_PK": 34,
"cat_name": "test6",
"cat_amount": "600.00"
}
]
}
PHP
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
JQUERY
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
});
"I've tested using jsonlint, which comes back valid."
No it doesn't, not for the JSON you've shown which has an error: it is missing a closing ] after the } and before the comma on the line before "expense" : .... But perhaps that's just a typo in your question given that you're generating the JSON with json_encode() (which wouldn't produce an error like that).
" I just can't seem to get anything in the browser other than when I just alert(response);"
So you are getting a value of some sort back then.
" but if I just alert response[0], it will return just the first character of the JSON array."
Yes, that's because response is a string - the raw string containing JSON, where what you want is to parse that string to get an object. Except that you don't have to do this manually because jQuery will do it automatically once you add dataType:"json" to your $.ajax() options.
"I actually was missing the datatype on this one, but even after adding it in, no matter what I try, I'm getting [Object:Object] or undefined. I'm literally doing nothing more than alert(response);"
Once you add the dataType:"json" the response parameter will be an object, which when you try to alert will correctly display as [object Object]. If you use console.log(response) then in your browser's console you'd see the actual object. You'd get undefined if you try to access a property that doesn't exist.
"I need to be able to access the value of cat_id_PK and the other elements separately to loop through and display them in html table cells."
Your response object has two properties, income and expenses, both of which are arrays of object. So use response.income to access the first array of objects, and response.expenses to access the second array of objects. The first income item is response.income[0] and the property you asked about is response.income[0].cat_id_PK. So you can use a for loop, or use $.each() to iterate over the array and do something with each .cat_id_PK property:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "json",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
var tr = $("<tr></tr>");
// using traditional for loop for income items
for(var i = 0; i < response.income.length; i++) {
$("<td></td>").text(response.income[i].cat_id_PK).appendTo(tr);
}
tr.appendTo("#idOfTableHere");
var tr = $("<tr></tr>");
// use equivalent jQuery $.each for expense items
$.each(response.expenses, function(i, v) {
$("<td></td>").text(v.cat_id_PK).appendTo(tr);
});
tr.appendTo("#idOfTableHere");
});
The code I've shown creates new td elements in each loop, appending them to new table rows, and then after each loop the new row is appended to a table that I've assumed already exists on your page with id="idOfTableHere".
try this you miss dataType:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: "display_categories", cur_month:cur_month},
dataType:"json",
});
request.done(function(response){
//for each element put values in <td></td> tags.
});
I'm pretty unfamiliar with JSON, as I haven't used it too much and I'm trying to learn some of it.
So I have an ajax request that gives me this: [{"palvelu_id":"1","palvelu_nimi":"Meikkikoulutus","palvelu_kuvaus":"Kuvaus","palvelu_hinta":"10"}]
And I'm trying to use jQuery.parseJSON to use it on a page.
var palveluData = $.parseJSON(d);
$("#ajanvarausInfo").html(palveluData.palvelu_kuvaus+"<br>"+palveluData.palvelu_hinta);
But I get undefined as answer, what am I doing wrong here?
You should get the first element of the array:
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>...");
If the array has more than 1 element you should iterate through the array, you can use jQuery $.each() utility function.
EDIT::
Wow, looks like ive kept the window open for to long before replying -.-
You have an outter array there, so you need to take that into account ( your php side might be not correct )
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>"+palveluData[0].palvelu_hinta);
Usually you not need that when properly setting everything up
$.ajax ({
url: 'myurl',
type: 'POST',
data: { key_value pairs here },
dataType: 'json',
success: function(response){
$("#ajanvarausInfo").html(response.palvelu_kuvaus+"<br>"+response.palvelu_hinta);
});
});
On the php side
$response = array(
"palvelu_id" => "1",
"palvelu_nimi" => "Meikkikoulutus",
"palvelu_kuvaus" => "Kuvaus",
"palvelu_hinta" => "10"
);
echo json_encode($response);