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);
});
Related
I'm trying to get some value over my server using jquery's $.get method and store the result in an object.
What I'm doing is running my function inside a loop:
function renderTabelScheduledEmploye(employees) {
$('#containerDataStaff').empty();
let record = '';
let count = 1;
if (employees.length > 0) {
$.each(employees, function(key, value) {
getFromServerScheduleCount(employees[key].schedule_employee_id);
console.log(scheduleCountData);
record += '<tr>';
record += '<td>' + count + '</td>';
record += '<td>( ' + employees[key].emp_kode + ') - ' + employees[key].emp_full_name + '</td>';
record += '<td>' + scheduleCountData[0].work + '</td>';
record += '<td>' + scheduleCountData[0].offDay + '</td>';
record += '<td>' + scheduleCountData[0].leave + '</td>';
record += '<td>' + scheduleCountData[0].shiftCount + '</td>';
record += '<td>Set Shift</td>';
record += '</tr>';
count++;
});
}
$('#containerDataStaff').append(record);
}
Then I create a function to retrieve JSON data from my server using the $.get function, then store the data result to an object that has been declared:
var scheduleCountData = new Object();
function getFromServerScheduleCount(schedule_employee_id) {
let url = `{{ url('/departement/schedule/manage/schedule/count') }}`;
url = url + '/' + schedule_employee_id + '/get';
let data = {};
$.get(url, function(data) {
let obj = JSON.parse(data);
data.work = obj.work;
data.dayOff = obj.dayOff;
data.leave = obj.leave;
data.shifts = obj.shifts;
scheduleCountData.new = data;
})
}
I can see in the console that the object has filled with the data
[object success to fill][1]
But when i try to access in code like this
scheduleCountData[0]
and log the result to to the console, it shows undefined.
This little bit frustrating for me. I hope someone can help me. Thanks for community.
EDIT :
Sorry i miss
i try to call that object with code like this
scheduleCountData.new
but still undefined on console
Seems youre not waiting for the load to finish before trying to use the data:
// This has a get call, which is async (takes time to load)
getFromServerScheduleCount(employees[key].schedule_employee_id);
// The script will continue, without waiting for the load to finish, so can be empty
console.log(scheduleCountData);
I would suggest adding a callback, like this:
getFromServerScheduleCount(employees[key].schedule_employee_id, function(scheduleCountData) {
console.log(scheduleCountData);
});
function getFromServerScheduleCount(schedule_employee_id, callback) {
$.get(url, function(data) {
// ...
callback(data);
});
}
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
I have a problem with JSON data: I want make news feed via JSON URL, but the information not showing in HTML.
$(function() {
var entries = [];
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '<div class="panel-body"><h3 class="lead">${title}</h3>';
html += '<time datetime="${published}">';
html += '<span class="glyphicon glyphicon-time"></span> ';
html += '<span class="month">${monthName}</span> ';
html += '<span class="day">${day}</span>, ';
html += '<span class="year">${year}</span></time></div>';
$('#ticker').html
},
<div id="ticker"></div>
You could do something like this:
<script>
$(document).ready(function() {
var dmJSON = "http://www.stellarbiotechnologies.com/media/press-releases/json";
$.getJSON( dmJSON, function(data) {
var html = '';
// loop through all the news items, and append the
// title and published date to the html variable.
for(var i = 0; i < data.news.length; i++){
html += '<div>';
html += data.news[i].title
html += '<br>';
html += data.news[i].published
html += '</div>';
}
// append all the html variable to the ticker div.
$("#ticker").append(html);
});
});
</script>
This will loop through the news node, and get the title and the published date and then append them to the page (an element with the id of ticker.
This is my response from AJAX call
{"screen":[{"screen_name":"SCR1","screen_id":"1"},{"screen_name":"SCR2","screen_id":"2"},{"screen_name":"SCR3","screen_id":"3"},{"screen_name":"SCR4","screen_id":"4"},{"screen_name":"SCR5","screen_id":"5"},{"screen_name":"BIGSCR","screen_id":"6"}]}
success: function(response) {
var jsondata = JSON.stringify(response);
console.log(jsondata);
var html = '';
for (var i = 0; i < jsondata.screen.length; i++) {
var screenName = jsondata.screen[i].screen_name;
var screenId = jsondata.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
}
But I keep on getting
Uncaught TypeError: Cannot read property 'length' of undefined at for loop
Try this: It Works. As smooth as silk: (See comment for explanation)
<select id="SCname"></select>
<script>
$.ajax({
dataType: 'json',
//This JSON datatype returns a json encoded response
url:"api/test.php",
//This is the URL From where you fetch the JSON Data
success: function(response){
//Since the response array object has a single array element "screen", we make it myArray
myArray = response["screen"];
console.log(myArray);
//We get six Objects in myArray.
//Thsese are Arrays of your six screens . Now Using Loops
var html = '';
for (var i = 0; i < myArray.length; i++) {
// Each element is inside DOuble Array like: myArray[0]["screen_name"]
var screenName = myArray[i]["screen_name"];
var screenId = myArray[i]["screen_id"];
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
//Check your console ouput
console.log(html);
}
});
</script>
JSON.stringify(object) returns a string. You want a JSON.parse(string) – which returns an object. Alternatively, if your response is already an object, then you don't have to parse it at all:
success: function(jsonData) {
var html = '';
for (var i = 0; i < jsonData.screen.length; i++) {
var screenName = jsonData.screen[i].screen_name;
var screenId = jsonData.screen[i].screen_id;
html += '<option value="' + screenName + '">' + screenId + '</option>';
}
$('#SCname').append(html);
You don't want to stringifybut to parse. Correct it must be:
var jsondata = JSON.parse(response);
But keep in mind that jQuery possibly is already parsing the JSON for you.
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>');
});