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.
Related
I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});
To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/
i am learning on how to parse json using jquery
PHP
foreach($cars as $car)
{
$output['carID'][] = $car->carID;
$output['carName'][] = $car->carName;
}
echo jsonEncode($output);
JSON
{"carID":["1","2"],"carName":["BMW","Mercedez Benz"]}
My javascript
$.getJSON('/cars.php', { carID: carID }, function(data) {
$.each(data, function(i,item) {
for(j=0; j < item[item.carName]; j++) {
console.log(item[item.carName][j]);
}
});
});
I think my code is entirely wrong because its not working.
how can i get the value inside of ["1","2"] ?
Thanks for the help.
It's not the "value of 1" that you're looking for. It's the value at index 0, which happens to be "1".
["1","2"] is the value of carID, and it is an array.
Try accessing it this way:
alert(item.carID[0]); // will alert "1"
alert(item.carID[1]); // will alert "2"
As I know, array indexes start from "0" in many languages, so you need something like this to get array values in your code;
var data = {"carID":["1","2"],"carName":["BMW","Mercedez Benz"]};
$.each(data.carID, function(key, val){
var i = 0, id;
while(id = val[i++]) console.log(id);
});
// or just simply use
console.log(data.carID[0]);
I'm printing a <ul> of array $_SESSION['words'] in PHP.
// PHP print new words as links
echo '<ul id="wordlist">';
foreach($_SESSION['words'] as $word => $description) {
echo '<li id="wordlist">' . $word . '</li>';
}
The array is simple - words are stored as keys and the descriptions for words will be values, e.g.
array(5) { ["word1"]=> int(1) ["word2"]=> int(2) ["word3"]=> int(3) ["word4"]=> int(4) ["word5"]=> int(5) }
I plan to manipulate items in the array by selecting a $word and adding a $description and adding it to the array, so I'm thinking I'll use jQuery to do it.
My question is: if I create a JSON array from this PHP array, can I print it out in the same way and manipulate it? I encoded it with $myJSON = json_encode($_SESSION['words']); but I'm already stuck attempting to print out the keys/values from the JSON! Thanks...
You can use $.parseJSON:
var json = $.parseJSON('your json');
alert(json.word1);
alert(json.word2);
If your JSON data is available via a URL, you can use $.getJSON
You description indicates to me that you are not using JSON in any way, other than to use PHP's JSON encoding function. It sounds like you are encoding your PHP associative array into a JSON string and then writing that string into your HTML output. If this is the case, then your JSON is really a JavaScript object.
So let's assume your resulting markup is this:
<script>
// Using a global here, which is not good,
// but this is an example.
var myWordList = {"word1":1,"word2":2,"word3":3};
</script>
<ul id="wordlist">
<li id="word1">1</li>
<li id="word2">2</li>
<li id="word3">3</li>
</ul>
Notice that my id attribute values are unique. You used the same id attribute value multiple times; that is invalid markup. Also, I kept the markup in each list element simple for this example (just text).
So, given this markup, we could write the following JavaScript:
<script>
// Update our wordlist object with some descriptions
myWordList.word1 = {
"value": myWordList.word1,
"description": "This is word 1."
};
myWordList.word2 = {
"value": myWordList.word2,
"description": "This is word 2."
};
myWordList.word3 = {
"value": myWordList.word3,
"description": "This is word 3."
};
// Now lets update the unordered list with jQuery
for (var i = 1; i < 4; i += 1) {
$('#word' + i).html(myWordList['word' + i].description);
}
</script>
In this JavaScript, I first update the myWordList values by assigning a new object to each value. These new objects have two properties: a value property that is assigned the old myWordList.word# value, and a new description property that describes the word. Next, I update the unordered list by replacing the word values with the word descriptions.
Edit:
If you want to loop over the properties in the object, you can do this:
for (var key in myWordList) {
if (myWordList.hasOwnProperty(key)) {
console.dir(myWordList[key]);
}
}
if not used to $.each method, may also try old array loop:
$.ajax({
url: '',
dataType: 'json',
success: function(arrayData) {
var i,max=arrayData.length;
for(i=0;i<max;i++){
var rowItem = arrayData[i];
try{
console.log(rowItem.attr1);
}catch(ex){
alert(ex);///in case data is not complete
}
});
}
});
if you already have the JSON string , say strJson = '[{attr1:"hello"},{attr1:"world"}]';
var tmp = 'var data = '+strJson;
///so you got : var data = [{attr1:"hello"},{attr1:"world"}]
eval(tmp);/// execute the above line
alert(data.length + "first item:"+data[0].attr1);
You need to get that JSON via AJAX and the
$.ajax({
url: '',
dataType: 'json',
success: function(response) {
$.each(response, function(key, val) {
console.log(key); // word1, word2, word3...
console.log(val); // 1, 2, 3...
....
});
}
});
I have a php page that returns json like this:
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$rows[] = $row;
}
print json_encode($rows);
When I run the php page I get back something like:
[{"phone":"1234567"},{"phone":"1234567"}]
This is my jquery code:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(response) {
$.each(response, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
});
I got that from another SO question. This will give me my keys and value in the alert. This was just for me to make sure everything works. I have searched but cannot figure out how to just get one value. Say I wanted the name, what do I put? I have tried:
success: function(response) {
var obj = $.parseJSON(response);
alert( obj.phone );
}
But since it is multiple rows it won't work unless I have, and it also fails when I have one row like this:
echo json_encode(array("phone" => "123")
How do I get a single value from a row?
How do I iterate through multiple rows and only get one of the column values?
The response variable is an array of objects. To access a single index in your response variable:
var phone = response[0].phone;//replace `0` with the index you want
If you end-up iterating through your response in a loop make sure to do it like this for the best performance:
var len = response.length;
for (var i = 0; i < len; i++) {
console.log(response[i].phone);
}
Check-out this jsperf to see how much faster this type of loop is than for(i in array): http://jsperf.com/for-in-tests
The response JSON is an array. To get the first phone number, retrieve the first object through response[0], then get the property using .phone:
success: function(response) { //response = array, when using dataType:"JSON"
alert(response[0].phone);
}
Replace 0 with any number between 0 and response.length to get the corresponding phone property.
Javascript:
for (var i; i < response.length; i++) {
console.log(response[i].phone);
}