Is there a getJSON sucess function? - javascript

I have a getJSON function that looks like below:
$.getJSON("jsonStats.php?action=segment", function(json) {
//Loop over each of the values in the jSON response to make the table.
var tableSegments = '',
counter = 1;
$.each(json, function(key, value) {
tableSegments += '<tr>';
tableSegments += '<td></td>';
tableSegments += '<td>'+counter+'</td>';
tableSegments += '<td>'+value['name']+'</td>';
tableSegments += '<td>'+value['y']+'</td>';
tableSegments += '</tr>';
counter++;
});
$('#segmentTable').empty().append(tableSegments);
});
The issue that I am running into is that its running the each statement/creating the table before it even gets the data. Is there a way to make it wait until it actually has the jSON data before doing that part?

You can use the done callback (jquery.getjson reference) :
$.getJSON('jsonStats.php?action=segment')
.done(function(json)
{
//Loop over each of the values in the jSON response to make the table.
var tableSegments = '',
counter = 1;
$.each(json, function(key, value)
{
tableSegments += '<tr>';
tableSegments += '<td></td>';
tableSegments += '<td>'+counter+'</td>';
tableSegments += '<td>'+value['name']+'</td>';
tableSegments += '<td>'+value['y']+'</td>';
tableSegments += '</tr>';
counter++;
});
$('#segmentTable').empty().append(tableSegments);
})
.fail(function(jqxhr, textStatus, error)
{
var err = textStatus + ', ' + error;
console.log( 'Request Failed: ' + err );
});

Figured it out..
value['name'] and value['y']
need to be value[0] and value[1]
I had the headers as text/javascript on accident this morning so the response was an object, changed it to application/json and thats what made those values change.

Related

Dynamically populate <td> from return of a function

I want to dynamically update the contents of cells but only if data for those cells exists in the database.
What I have tried is to add a call to the addDataIfPres function, from the appropriate each time it is dynamically generated, in the hope that it would be populated with the returning data from the function: either some data if it exists for that student, or 'blank' if it does not.
But, this is not working. How can I call the addDataIfPres function, each time an HTML cell is created, and populate it with the returning value?
function makeEditTableHTML(studentArray, groupID) {
return populateDB(groupID, function(data) {
// Data from AJAX POST
console.log(data);
function addDataIfPres(col, student, data) {
for(var j=0; j < data.length; j++) {
if ((student == data[j][0]) && (col == 1)) {
res = data[j][1];
}
else {
res = "";
}
}
return res;
}
var result = "<table id='dataEditTableid' class='stripe' border=1><thead><tr><td><b>ID</b></td><td><b>Student Email</b></td><td><b>Group ID</b></td><td><b>Target</b></td><td><b>SEN</b></td><td><b>Disadvantaged</b></td></tr></thead>";
result += "<tbody>";
for(var i=0; i < studentArray.length; i++) {
result += "<tr>";
result += "<td>"+studentArray[i][1]+"</td>";
result += "<td>"+studentArray[i][0]+"</td>";
result += "<td>"+groupID+"</td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(1, this.id, this.innerHTML, "+groupID+")'>+ addDataIfPres(1, this.id, data) +</td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(2, this.id, this.innerHTML, "+groupID+")'></td>";
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(3, this.id, this.innerHTML, "+groupID+")'></td>";
result += "</tr>";
}
result += "</tbody></table>";
dataTable.innerHTML = result;
$(document).ready(function() {
$('#dataEditTableid').DataTable({
});
});
return result;
});
}
You don't actually call the function because the code is still part of the string (missing quotation marks to denote the end of the string).
Try this:
result += "<td id=" + studentArray[i][1] + " contenteditable='true' onBlur='saveToDB(1, this.id, this.innerHTML, "+groupID+")'>" + addDataIfPres(1, this.id, data) + "</td>";

JS: Live search not working with spaces between two query

performing this search operation on JSON data, it works show filter data when enter term in search bar but it works only with one term as soon as I add space and other term it shows nothing, what am I doing wrong? Also it takes time to filter data around 14000 records are in JSON file
$(document).ready(function() {
$('#selectterm').change(function() {
var sterm = $(this).val();
$.ajax({
type: "GET",
url: "/fee/get/" + sterm,
success: function(res) {
if (res) {
$('#txt-search').keyup(function() {
var searchField = $(this).val();
if (searchField === '') {
$('#filter-records').html('');
return;
}
var output = '<div class="row">';
var count = 1;
$.each(res, function(key, lol) {
if ((lol.strm.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.subject_cd.toLowerCase().indexOf(searchField.toLowerCase()) != -1) ||
(lol.catalog_nbr.toLowerCase().indexOf(searchField.toLowerCase()) != -1)) {
output += '<table class="table">';
output += '<thead>';
output += '<tr>';
output += '<th scope="col">Term</th>';
output += '<th scope="col">Subject</th>';
output += '<th scope="col">Catlog Nbr</th>';
output += '</tr>';
output += '</thead>';
output += '<tbody>';
output += '<tr>';
output += '<td>' + lol.strm + '</td>';
output += '<td>' + lol.subject_cd + '</td>';
output += '<td>' + lol.catalog_nbr + '</td>';
output += '</tr>';
output += '</tbody>';
output += '</table>';
if (count % 2 == 0) {
output += '</div><div class="row">'
}
count++;
}
});
output += '</div>';
$('#filter-records').html(output);
});
}
}
});
});
});

Reading Json Data in Javascript / php (Format issue)

I have this code which reads the json data below (This code works well):
var data = [{"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end":"2011-10-29T14:15:00.000+10:00", "title":"Meeting"}];
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.title + '</li>';
});
Ive now changed the data (see below) and for some reason it's not working
var data = {"users":[{"firstname":"peter","lastname":"tosh"},{"firstname":"mike","lastname":"Marsh"}]}
var output = '';
$.each(data, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
I know the data format is slightly different ... I'm I forgetting something?
$.each(data.users, function(index, value){
output += '<li>' + value.firstname + '</li>';
});
try this
Although your code is in javascript and not PHP. The problem is that you're having an array inside of an array. So on the first loop your only getting users and not firstName or something like that. Fix:
var data = {"users":
[
{"firstname":"peter","lastname":"tosh"},
{"firstname":"mike","lastname":"Marsh"}
]
}
var output = '';
$.each(data, function(i, users){
$.each(users, function(index, value) {
output += '<li>' + value.firstname + '</li>';
});
});

parse error from ajax call

I have written some ajax code using an open source library to do jquery pagination.
when the page first loads, it properly queries and displays the first 25 records from my database. But all subsequent requests fail with a parse error.
I can't see anything different between the formatting of data in the first page vs. other pages.
I've tried to use JSON Lint but none of my json passes, even the query for page 1.
My json data looks like this:
"[{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"and the final update\",\"number\":\"72212\",\"updatedname\":\"28112\",\"createdname\":\"conversion script\",\"user\":\"28507\",\"position\":\"1\",\"device_id\":\"2\",\"user_id\":\"2\",\"password\":\"Wh16dteaR\",\"updateddatetime\":\"2013-10-07 15:14:28\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\"Bauer\",\"number\":\"72787\",\"createdname\":\"conversion script\",\"user\":\"28509\",\"position\":\"2\",\"device_id\":\"4\",\"user_id\":\"4\",\"password\":\"EHVOzIx1\"},{\"createddatetime\":\"2013-09-10 17:56:54\",\"description\":\" Woosly\",\"number\":\"72822\",\"createdname\":\"conversion script\",\"user\":\"28510\",\"position\":\"3\",\"device_id\":\"5\",\"user_id\":\"5\",\"password\":\"IP8rsdOE\"}]"
And then I use the parseJSON method to convert the above string into an object.
Here's the main routine that makes the ajax call and parses:
$.ajax({
url: mypath + '?startpos=' + page_index * items_per_page + '&numberofrecordstograb=' + items_per_page + '&viewtype=json',
dataType: 'json',
success: function(data){
data = $.parseJSON(data); //converting to a javascript object vs. just string...
if (data !=null) {
for(var i=0;i<data.length;i++){
var deviceobj = data[i];
newcontent = newcontent + "<TR>";
newcontent=newcontent + '<TD>';
//add EDIT hyperlink
if ($("#editdevicesettings").val() == "true") {
var temp = $("#editlinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]) + ' ';
}
//add DELETE hyperlink
if ($("#deletedevice").val() == "true") {
var temp = $("#deletelinkpath").val();
newcontent=newcontent + temp.replace("xxx",deviceobj["device_id"]);
}
newcontent=newcontent + '</TD>';
newcontent=newcontent + '<TD>' + deviceobj["number"] +'</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["user"] + '</TD>';
newcontent=newcontent + '<<TD>' + deviceobj["password"] + '</TD>';
if (deviceobj["name"]) {
newcontent=newcontent + '<TD>' + deviceobj["name"] + '</TD>';
}
else {
newcontent=newcontent + '<TD> </TD>';
}
newcontent=newcontent + '<TD>' + deviceobj["description"] + '</TD>';
newcontent = newcontent + "</TR>";
}// end for
// Replace old content with new content
$('#Searchresult').html(newcontent);
}//end if
},
error: function(request, textStatus, errorThrown) {
console.log(textStatus);
},
complete: function(request, textStatus) { //for additional info
//alert(request.responseText);
console.log(textStatus);
}
});
// Prevent click eventpropagation
return false;
}//end pageselectCallback()
I'm not sure how to go about troubleshooting this.
Any suggestions would be appreciated
I decided to reduce the number of records returned to one per page... to narrow down the offending record.
now that I know which record it is, i should be able to resolve problem.

Catch data from JSON without a key

My problem is that i cant print what i recieve from a server with out having a key at the start of the JSON file, here is my current code...
$.getJSON("http://10.21.26.251:8080/Transport/getMessage?user=1", function(data) {
var output = "<tr>";
for ( var i in data.item) {
output += "<td>"
+ "-- "
+ data.item[i].messageId
+ " --<br>-- "
+ data.item[i].userId
+ " --<br>"
+ data.item[i].messageContent
+ "<br></br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;
});
But this is reliant on the code being recieved having a name of items, the current JSON is recieved like this... I have no control over what is recieved
{
"messageId": "d1e5afa5-5153-49b7-ae73-3501fbed1b68",
"userTo": {
"userId": 1,
"userName": "COE",
"userLastCheckedDate": 1362994638139
},
"userFrom": {
"userId": 2,
"userName": "Man",
"userLastCheckedDate": 1362994638139
}
etc...
Its difficult to get an idea of the json schema with such a small sample, but assuming it is a list of emails i would try this:
$.getJSON("http://10.21.26.251:8080/Transport/getMessage?user=1", function(data) {
var output = "<tr>";
for ( var i = 0; i < data.length;i++) {
output += "<td>"
+ "-- "
+ data[i].messageId
+ " --<br>-- "
+ data[i].userFrom.userId
+ " --<br>"
+ data[i].messageContent
+ "<br></br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;
});
If I understood what you're trying to do, you basically want to loop through the JSON object properties without knowing their names. Also (correct me if I'm wrong), your object seems to be an array of objects.
You could do something like this:
var output = "<tr>";
for (var i=0; i<data.length; i++) { // Loop through the main array of objects
output += "<td>";
$.each(data[i], function(key, val) { // Loop through the properties of the current object
output += "-- "
+ val
+ " --<br>";
});
output += "</br></td>";
}
output += "</tr>";
document.getElementById("placeholder").innerHTML = output;

Categories

Resources