Use jquery to get jsondata - javascript

I want to use .getJSON to get data from server. The data can get, but it can not display in page.
js code:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});
});
html code:
<button id="jsondata" name="jsondata" accesskey="g">GetData</button>
<div id="datashow"></div>
The data I got from server display in fire bug:
{"name":"Tom","sex":"male","tel":"456","email":"sdfd#15.com"}

The json parameter for success function should already be parsed as JSON, so loop with a normal loop:
$(function(){
alert(1);
$("#jsondata").bind("click",function()
{
var data = "action=getdata";
alert(2);
$.getJSON("Guess.php",data, function(json)
{
alert(3);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
for(var i in json) {
str += '<tr><td>' + i.name + '</td><td>' + i.sex + '</td><td>' + i.tel + '</td></tr>';
}
str += '</table>';
$("#datashow").append(str);
});
});
});

Try this: (There is no need to loop with $.each)
$(function () {
$("#jsondata").bind("click", function () {
var data = "action=getdata";
$.getJSON("Guess.php", data, function (json) {
var str = '<table><tr><td>日期</td><td>1#铸机产量</td><td>2#铸机产量</td></tr>';
str += '<tr><td>' + json.name + '</td><td>' + json.sex + '</td><td>' + json.tel + '</td></tr>';
str += '</table>';
$("#datashow").append(str);
});
});
});

Try the following code.
$.getJSON("Guess.php",data, function(json) {
// Convert json reponse object to array
json = $.makeArray(json);
var str = '<table><tr><td>Name</td><td>1#Sex</td><td>2#Tel</td></tr>';
$.each(json,function(i,v){
str += '<tr><td>'+v.name+'</td><td>'+v.sex+'</td><td>'+v.tel+'</td></tr>';
});
str += '</table>';
$("#datashow").append(str);
});
});

Related

i want to seperate a function into a multiple function jquery/ajax

I have a JavaScript file that has an Ajax function which calls a JSON file from an online server to extract it's data and interpret it in to a generated table... I want to separate the generate link, generate date, identify the car plate type/country into multiple functions that can be called by the ajax function.
// table of the server's data from JSON file
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:3737/anpr?nb=0",
type: "GET",
dataType: "json",
success: function(data) {
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += '<div class="serial">' + value.id + '</div>';
// identifie the car plate type/country fron json data
var plateType = value.plateType
if (plateType == "1") {
detection_data += '<div class="country">Tunisie TN</div>';
} else if (plateType == "2") {
detection_data += '<div class="country">Tunisie RS</div>';
} else if (plateType == "3") {
detection_data += '<div class="country">Tunisie GOV</div>';
} else if (plateType == "4") {
detection_data += '<div class="country">Lybie</div>';
} else if (plateType == "5") {
detection_data += '<div class="country">Algerie</div>';
} else {
detection_data += '<div class="country">Autre</div>';
}
detection_data += '<div class="visit">' + value.plateNumber + '</div>';
// generate date from json data
detection_data += '<div class="percentage">' + value.date.substr(8, 2) +
'/' + value.date.substr(5, 2) + '/' + value.date.substr(0, 4) +
' ' + value.date.substr(11, 2) + ':' + value.date.substr(14, 2) + ':' + value.date.substr(17, 2) + '</div>';
// generate link
detection_data += '<div>' + '<a class="img-pop-up" href="http://127.0.0.1:3737/anpr/snapshot?year=' + value.date.substr(0, 4) +
'&month=' + value.date.substr(5, 2) + '&day=' + value.date.substr(8, 2) +
'&&hour=' + value.date.substr(11, 2) + '&minute=' + value.date.substr(14, 2) + '&second=' + value.date.substr(17, 2) +
'&plate=' + value.plateNumber.split(" ").join("_") + '&platetype=' + value.plateType + '">link to picture</a>' + '</div>';
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I tried to make your code more modular and readable. Here's what I could come up with. I am posting only relevant sections of your code to be concise.
NOTE: This is just a recommendation,I have not tested the below code.
var detection_data = '';
// generating the table to interpret the json data
$.each(data, function(key, value) {
detection_data += '<div class="table-row">';
detection_data += getPlateIDHTML(value.id);
// identifie the car plate type/country fron json data
detection_data += getPlateTypeCountryHTML(value.plateType);
// Plate number
detection_data += getPlateNumberHTML(value.plateNumber);
// generate date from json data
detection_data += getDetectionDateHtml(value.date);
// generate link
detection_data += getSnapshotLink(value.date, value.plateNumber, value.plateType);
detection_data += '</div>';
});
$('#detection_table').append(detection_data);
Below are my functions
String.prototype.format = function () {
var a = this, b;
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a; // Make chainable
};
function parseStringAsJSDate(date_as_string) {
return new Date(date_as_string);
}
function getPlateIDHTML(id) {
var plate_id_html = '<div class="serial">%s</div>';
return plate_id_html.format(id);
}
function getPlateNumberHTML(plateNumber) {
var plate_number_html = '<div class="visit">%s</div>';
return plate_number_html.format(plateNumber);
}
function getPlateTypeCountryHTML(plateType) {
var plateTypeCountry = {
"1": "Tunisie TN",
"2": "Tunisie RS",
"3": "Tunisie GOV",
"4": "Lybie",
"5": "Algerie",
};
var plate_type_country_html = '<div class="country">%s</div>';
if(plateType in plateTypeCountry) {
return detection_data_html.format(plateTypeCountry[plateType]);
} else {
return detection_data_html.format("Autre");
}
}
function getDetectionDateHtml(captured_date_as_string) {
var date_of_capture_html = '<div class="percentage">%s/%s/%s %s:%s:%s</div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
return date_of_capture_html.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds());
}
function getSnapshotLink(captured_date_as_string, plateNumber, plateType) {
var snapshot_link = "http://127.0.0.1:3737/anpr/snapshot?year=%s&month=%s&year=%s&day=%s&hour=%s&minute=%s&second=%s&plate=%s&platetype=%s";
var snapshot_link_html = '<div><a class="img-pop-up" href="%s">Link to picture</a></div>';
var captured_date = parseStringAsJSDate(captured_date_as_string);
var snapshot_link = snapshot_link.format(captured_date.getDate(), captured_date.getMonth()+1, captured_date.getFullYear(), captured_date.getHours(), captured_date.getMinutes(), captured_date.getSeconds(), plateNumber.split(" ").join("_"), plateType);
return snapshot_link_html.format(snapshot_link);
}
Below is a brief explanation of each function
String.prototype.format: This is an equivalent of the old-school printf in C. I find variable-substitutions of the sort '<div class="serial">'+ id +'</div>' inter-mingling HTML with JavaScript very difficult to read. And therefore this.
parseStringAsJSDate: I assume that your API is under your control. I recommend you to modify the date format to ISO8601 so that it can be parsed by JavaScript as a Date. Your substr function again affects readability.
getPlateIDHTML & getPlateNumberHTML: Simple functions that just use the format function to embed the passed variables into the HTMLs to show ID and plate number.
getPlateTypeCountryHTML: I used a Python object here to reduce the number of ifs and else ifs.
getDetectionDateHtml & getSnapshotLink: I have tried to parse the date as a JavaScript date and this eliminates the substrs. Moreover, the use of format simplifies these functions further.
Let me know your suggestions on this. Suggestions/Criticism from Stack's gurus are more than welcome :)
UPDATE
Please check my updated format function. I sourced it from this excellent answer. Apologies, the earlier one was just copy-pasted, I should have tried it. Please just the format function to the one that's indicated and let me know

javascript $_GetJSON from .php file

I have a PHP file (GenerateJson.php) that uses json_encode to produce JSON data from my database, I know I can have that same PHP file write to a .json file but if I do that the written JSON will only contain the data from the last time the GenerateJson.php the requested and I want to javascript to be able to access live data on the fly
currently my code is is this:
$('#search').keyup(function() {
var searchField = $('#search').val();
var myExp = new RegExp(searchField, 'i');
$.getJSON('Generated.json', function(data) {
var output = '<ul class="searchresult1">';
$.each(data.data, function(key, val) {
if ((val.artists.Artist.search(myExp) != -1)) {
var ArtistURL = "music/abArtist.php?artist=" + encodeURIComponent(val.artists.Artist);
output += '<li>';
output += '<h2>' + val.artists.Artist + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('#update1').html(output);
});
});
When I replace "Generated.json" with "GenerateJson.php"
This javascript don't work anymore...
What is a good and simple fix? to get this to work with "GenerateJson.php" and how?
Thanks!
If you want to get the JSON data dynamically from PHP you can try the following
$.ajax({
dataType: 'json',
url: 'GenerateJson.php',
done(function( data ) {
var output = '<ul class="searchresult1">';
$.each(data.data, function(key, val) {
if ((val.artists.Artist.search(myExp) != -1)) {
var ArtistURL = "music/abArtist.php?artist=" + encodeURIComponent(val.artists.Artist);
output += '<li>';
output += '<h2>' + val.artists.Artist + '</h2>';
output += '</li>';
}
});
output += '</ul>';
$('#update1').html(output);
});

acess variable url in ajax

guys i am trying to make variable url to pass it to ajax call ..i know it is dummy but i cant find a solution and it doesnt work .. here is my code
function GridLibrary(fileName) {
this.fileName = fileName;
}
GridLibrary.prototype = {
set_fileName: function(fileName){
this.fileName = fileName;
},
get_fileName: function(){
return this.fileName;
}
};
GridLibrary.prototype.display = function() {
$.ajax({
url : get_fileName(),
error : function(that, e) {
console.log(e);
},
success : function(data) {
var table = "<table>";
$.each(data, function(index, MyList) {
table += '<tr><td>' + MyList.id + '</td><td>' + MyList.name
+ '</td><td>' + MyList.age + '</td><td>'
+ MyList.feedback + '</td><tr>';
});
table += '</table>';
$('body').append(table);
}
});
};
You can load a URL from an external source that is not your problem.
Use the 'this' keyword to fix your problem;
url : this.get_fileName()
get_fileName() is not a function because it's a property on GridLibrary.prototype
you have to use this.get_fileName()

Printing HTML Attritbutes with jquery in a loop

i try to loop trough Objects in a Database (parse.com) and would like to print these results with attributes from Bootstrap. I'm a beginner and don't understand why it's not possible how i did it. i know there is .attr() but i don't get it how i can use this in my example.
This is my code:
var Insider = Parse.Object.extend("Insider");
function getPosts() {
var query = new Parse.Query(Insider);
query.find({
success: function(results) {
var output = "";
for (var i in results) {
var name = results[i].get("name");
var catego = results[i].get("cate");
var imageurl = results[i].get("image");
var tpp = results[i].get("tipp");
output += "<ul class="media-list">";
output += "<li class="media">";
output += "<div class="media-left">";
output += "<a href="#">";
output += "<img id = "two" class="media-object"
alt="...">"
output += "<h4>+ + name + "</h4>";
output += "</a>"
output += "</div>"
}
$("#list").html(output);
},
error: function(error){
console.log("Query error:" + error.message);
}
});
}
getPosts();
});
Any help much appreciated!

Can't return only usernames from json data fetched through a php page

I am able to get json data from an external php page and print it on the JavaScript console. But these are in the form objects. The following is the data I recieved on my console:
[{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}]
How can I extract only username and turn it into an ordered list. (ol)
This is what I have done so far:
$(document).ready(function (e) {
$('#delete').click(function (e) {
var jsonData = getResultsInJson(username);
jsonData.success(function (data) {
var output = "<ol>";
for (var i in data) {
output += "<li>" + data.username + "</li>";
}
output += "</ol>";
$('#placeholder').html(data);
console.log(data.username);
});
});
});
This is getResultsInJson():
function getResultsInJson(sql) {
return $.ajax({
url: 'commands.php',
data: 'results=' + sql,
dataType: 'json'
});
}
when you use the for(x in y) format, x is the key, and y is the array or object. Since i is just the key, you need to use it as one:
for (var i in data) {
output += "<li>" + data[i].username + "</li>";
}
Do you need them in alphabetically?
Try something like this:
$(document).ready(function() {
var json = [{"id":"1","username":"iammuneeb","password":"4297f44b13955235245b2497399d7a93","name":"Mirza Muneeb"},{"id":"2","username":"iamfaiz","password":"4297f44b13955235245b2497399d7a93","name":"Faiz"}];
var usernames = new Array();
$.each(json, function(index, object) {
usernames[index] = object.username;
});
var sorted = usernames.sort();
var output = '';
$.each(sorted, function(index, value) {
output += '<li>' + value + '</li>';
});
$('#placeholder').html('<ol>' + output + '</ol>');
});

Categories