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 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 am a jQuery beginner and hope someone can help me with this and also provide me some explanations.
I have an Ajax call that returns a JSON encoded string with two values for each item, an itemID and an itemVal - an example looks as follows (using console.log):
console.log(data) result:
string(225) "[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"},...]"
The number of items here varies but if an itemID is listed than there is always a corresponding itemVal.
itemID is a unique integer, itemVal is plain text.
Everything works so far but here comes my problem:
For each itemID here I have to do something with the corresponding itemVal, e.g. say just log it to the console or alert it for testing.
I know there are various approaches for this like jQuery.each, $.each, for, foreach etc. but since I just started recently I am not sure how I can iterate through this resp. how I can select the single itemIDs from it.
I tried different approaches, incl. $.parseJSON(data) which failed and it seems the problem is that my input before being decoded is a two-dimensional array instead of a one-dimensional one (I hope I am using the right terms here) which caused them to either return an error or to alert every single character of my string.
Update - failing example as per the answer below
$.ajax({
type: "post",
url: "ajax.php",
cache: "false",
data: {
node: 'fetchCountries',
itemIDs: itemIDs // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
Update 2 - My PHP:
case "fetchCountries":
$intval_itemIDs = array_map("intval", $_POST["itemIDs"]);
$itemIDs = implode(",", $intval_itemIDs);
$stmt = $conn->prepare("SELECT itemID, en FROM Countries WHERE itemID IN(" . $itemIDs . ") ORDER BY itemID");
$stmt->execute();
$result = $stmt->get_result();
while($arrCountries = $result->fetch_assoc()){
$countries[] = array("itemID" => $arrCountries["itemID"], "itemVal" => $arrCountries["en"]);
}
var_dump(json_encode($countries));
break;
Expected outcome (for testing):
console.log("China");
console.log("France");
console.log("Germany");
// ...
Can someone help me with this ?
Many thanks,
Tim
You have a JSON string representing an Array, which you are parsing into an actual Array. Then you are looping through the array, pushing each element into a new Array (arr).
Perhaps there is some confusion. Hopefully this will shed some light.
// Considering the following JSON string:
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
// You can create an Array from this like so:
var theArray = JSON.parse(data);
// Now you have an array with each item being an `object`
// with an "itemId" and an "itemVal". You can loop through
// this array and look at each object like so:
theArray.forEach(function (obj) {
console.log(obj.itemID + ': ' + obj.itemVal);
});
WhistleBlower, I have tested your code on my browser. It worked. Why don't you use header("Content-type :application/json"); too. So, you will not have to parse your JSON string.
var data = '[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}]';
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
You're not parsing a string, you're parsing an already-parsed object
just use it directly
var data=[{"itemID":1,"itemVal":"China"},{"itemID":2,"itemVal":"France"},{"itemID":3,"itemVal":"Germany"},{"itemID":4,"itemVal":"Italy"},{"itemID":5,"itemVal":"Poland"},{"itemID":6,"itemVal":"Russia"},{"itemID":7,"itemVal":"USA"}];
$.each(data,function(key,value){
console.log(value.itemVal);
});
or/
var arr = JSON.parse(JSON.stringify(data));
$.each(arr, function (key, value) {
console.log(value.itemVal);
});
Update 1:
I think so your php file like
<?php
$array = array( array( 'itemID' => 1, 'itemVal' => 'India'), array( 'itemID' => 2, 'itemVal' => 'usa'), array( 'itemID' => 3, 'itemVal' => 'china'), array( 'itemID' => 4, 'itemVal' => 'uk'));
echo json_encode($array);
//[{"itemID":1,"itemVal":"India"},{"itemID":2,"itemVal":"usa"},{"itemID":3,"itemVal":"china"},{"itemID":4,"itemVal":"uk"}]
?>
your script should be
$.getJSON( "your.php", function( data ) {
console.log(data);
$.each(data, function (key, value) {
console.log(value.itemVal);
});
});
OR
$.ajax({
type: "post",
url: "your.php",
cache: "false",
dataType: 'json',
data: {
node: 'fetchCountries',
itemIDs: youval // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(JSON.stringify(data));
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
OR
$.ajax({
type: "post",
url: "your.php",
cache: "false",
dataType: 'json',
data: {
node: 'fetchCountries',
itemIDs: youval // a list of integers
},
success: function(data){
console.log(data);
$.each($(data),function(key,value){
console.log(value.itemVal);
});
}
});
As simple as this!
$.each($(data),function(key,value){
console.log(value.itemVal); //place alert if you want instead of console.log
});
iterate through the obtained result and get itemVal value of each item
DEMO HERE
UPDATE
Add dataType option to your ajax and return type from php should be json and I hope you are doing that!
$.ajax({
type: "POST",
url: "ajax.php",
cache: "false",
dataType:'json', //Add this
data: {
node: 'fetchCountries',
itemIDs: itemIDs // a list of integers
},
success: function(data){
console.log(data);
var arr = JSON.parse(data);
$.each($(arr),function(key,value){
console.log(value.itemVal);
});
}
});
and return from your php should be echo json_encode(result);
Thanks to everyone for the help with this.
Since all other approaches made sense to me but still failed I did some more research on this and finally found what was causing this.
The issue was indeed on the PHP side and the accepted answer on the following post did the trick - since I added this to my PHP everything else on the JS side is working fine and I don't even need the dataType: "JSON" there:
dataType: "json" won't work
As per this post the solution for my case is the following - kudos to Jovan Perovic:
<?php
//at the very beginning start output buffereing
ob_start();
// do your logic here
// right before outputting the JSON, clear the buffer.
ob_end_clean();
// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>
Thanks again.
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);
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.