json data parsing with jquery and HTML - php

i am trying to parse json data from remote URL using Jquery. My data is in below format:
[
{
"UserId": "5",
"Name": "Syed",
"Lat": "23.193458922305805",
"Long": "77.43331186580654",
"EmailId": "syedrizwan#ats.in",
"LocationUpdatedAt": ""
},
{
"UserId": "98",
"Name": "Michael Catholic",
"Lat": "23.221318",
"Long": "77.42625",
"EmailId": "michaelcatholic#gmail.com",
"LocationUpdatedAt": ""
}
]
i have checked the data in json lint and it says it is correct data format. when i try to run it on my HTML page , it returns a blank page. My HTML code is a below:
<html>
<head>
<title>Jquery Json</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results.Name);
});
});
</script>
</head>
<body>
</body>
</html>
I am trying to retrieve names from the json string

results is an array of items, so you have to consider which item you want.
Normally, you'd go over the array in a loop, in a fashion similar to that:
$.getJSON('http://localhost/fbJson/json.php', function(results){
for(var i = 0; i < results.length; i++) {
console.log(results[i].Name);
}
});

There is an array of objects, you can reach them directly by using the index
$.getJSON('http://localhost/fbJson/json.php', function(results){
document.write(results[0].Name);
});
If you wish to iterate over the array you can use $.each and pass the results into it
$.each(results, function(key, val) {
document.write(val.Name);
});

Your json format is correct.
Use this code to access name in first row array:
document.write(results[0].Name);

Related

appending $.ajax response to Jquery UI dialog box in table format

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.

live search with jquery, ajax, json, php

I am looking for a live search solution or jquery autocomplete using ajax to take data from a file (later from db)
Let's say i have this php file with data:
[
{ID: "1", "Name": "User 1"},
{ID: "2", "Name": "User 2"},
{ID: "3", "Name": "User 3"},
{ID: "4", "Name": "User 4"}
]
I found on the web this code it works but it scanns only wikipedia, how can i make is to scann my php file? http://jsfiddle.net/TzQJP/
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>Comperio Super Simple Instant Search</title>
</head>
<body>
<h1>Search Wikipedia!</h1>
<br />
<input id="searchterm" />
<button id="search">search</button>
<div id="results"></div>
<script>
$("#searchterm").keyup(function(e){
var q = $("#searchterm").val();
$.getJSON("http://en.wikipedia.org/w/api.php?callback=?",
{
srsearch: q,
action: "query",
list: "search",
format: "json"
},
function(data) {
$("#results").empty();
$("#results").append("<p>Results for <b>" + q + "</b></p>");
$.each(data.query.search, function(i,item){
$("#results").append("<div><a href='http://en.wikipedia.org/wiki/" + encodeURIComponent(item.title) + "'>" + item.title + "</a><br>" + item.snippet + "<br><br></div>");
});
});
});
</script>
<div style="position:absolute;bottom:0;right:0;text-align:right">
Fergus McDowall 2012<br>
<br>
</div>
</body>
</html>
By change "http://en.wikipedia.org/w/api.php?callback=?" path to your PHP file path you can accomplish it. Make sure that your JSON result it correctly formatted and a valid one.
Don't just take code snippets from the internet and use it. At least get an idea what it does. It may help you to extend the code as you want.
Why not use: http://jqueryui.com/autocomplete/
example from the same website:
$(function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C"
];
$( "#tags" ).autocomplete({
source: availableTags //OR path to your PHP script
});
});
and you can have path to your PHP script instead of availableTags in source that returns
echo json_encode($array_of_items);
If you still want to use the code you provided, make sure you do echo json_encode($array); on your PHP script since response ajax is expecting should be type of json

Issue with highchart data display when parsing JSON data

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)]);

Transferring data from MySQL to javascript

I am a newbie to MySQL.
I want to transfer data from MySQL table to javascript.
I want to create a multidimensional array in javascript using the table in MySQL.
This multidimensional array is to be used in other functions for calculation.
Is there any way to do it using PHP or JSON?
Read records from your database table in PHP page and Create JSON And send it to Javascript. JSON can hold any level of hierarchical data.
A sample JSON may looks like this
[
{
"Customers": [
{ "Name": "Steve", "ID": "A12" },
{ "Name": "Mark", "ID": "A22" }
]
}
]
JsonLint is a useful tool when working with JSON data. It can validate JSON.
If you want to populate the javascript data on initial page load, you can do something like:
<?php
// get stuff from DB
$array_from_db = ... // some value determined via MySQL queries
?>
<script type="text/javascript">
var db_array = <?php echo json_encode($array_from_db); ?>
</script>
<?php
// more PHP stuff
This should work
<?php
var query=mysql_query("SELECT fields FROM table WHERE condition");
while($obj=mysql_fetch_array($query)){
arr[]=$obj
}
$array=json_encode($arr);
?>
<script type="text/javascript">
var db_array = <?php echo $array; ?>
</script>

JQuery AJAX access data sent with php

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.

Categories