This is a bit of a learning exercise for me so please excuse the code I am about to present. I am sure it could be better. In the following code you will see that I have successfully created a variable that is pulling in properly formatted JSON data. I am then, creating a function that appends a block of html. Within that append, I am referencing specific pieces of JSON data to be displayed.
HTML
<table id="jobSearchResults" bgcolor="white" style="border: 1px solid #ddd;width:100%;">
<tbody>
</tbody>
</table>
Javascript
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "../data/jobSearchResults.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
$(jobSearchResults).each(function(index, element){
$('#jobSearchResults').append('<tr><th><div style="background-color:#ddd;height:55px;width:80px;"><img src="" style="height:55px;width:80px;"></div></th><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].job_header+' </h4> '+json[0].specialty_name+', '+json[0].facility_name+' </td><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].city+', '+json[0].state_name+' </h4> United States </td><td class="text-right"></td></tr>');
});
Now, I need to complicate matters by making that table row repeat X number of times and have the JSON record number increment with each new row. In this case, I am both interested in how to take what I have written and expand on it to include this new functionality and I am also interested in what a more concise way to approach this problem would have been had I written this more efficiently.
The callback function for jQuery's each is passed two values. They represent the index and value of the current iteration, respectively. You can use either of these to reference your original JSON data and output each row accordingly.
The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
In my example below, I'm iterating over the json variable, which contains the JSON data returned from your AJAX call. In this context, you could use the index to reference the current iteration (e.g. json[index].job_header) or use the value directly (e.g. job.job_header).
function displayData(json) {
var $resultDisplay = jQuery('#jobSearchResults tbody');
if (!json) {
// variable is false. there was an ajax error.
$resultDisplay.html('<tr><td>There was an error.</td></tr>');
} else if (jQuery.isEmptyObject(json)) {
// variable is an empty object. no records were returned.
$resultDisplay.html('<tr><td>No data to display.</td></tr>');
} else {
// display the returned records.
$resultDisplay.empty();
jQuery.each(json, function(index, job) {
$resultDisplay.append('<tr>' +
'<td><div class="row-img"><img src="" alt=""></div></td>' +
'<td><h4>' + job.job_header + '</h4>' + job.specialty_name + ', ' + job.facility_name + '</td>' +
'<td><h4>' + job.city + ', ' + job.state_name + ' </h4>United States</td>' +
'</tr>');
});
}
}
jQuery.ajax({
'url': "https://epearson001.github.io/prototype-web-application/assets/data/jobSearchResults.json",
'dataType': "json"
})
.done(function(data) {
displayData(data);
})
.fail(function() {
displayData(false);
});
#jobSearchResults {
border: 1px solid #ddd;
width: 100%;
background-color: white;
}
div.row-img {
background-color: #ddd;
height: 55px;
width: 80px;
}
div.row-img img {
height: 55px;
width: 80px;
}
h4 {
margin-top: 0;
margin-bottom: 2px;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="jobSearchResults">
<tbody>
<tr>
<td>Loading data...</td>
</tr>
</tbody>
</table>
Edit
I also notice that you're setting async to false in your AJAX call. This defeats the asynchronous functionality of AJAX and, unless there's a particular reason to do so, I advise against it. I've restructured my example to use a callback function, so that data will be displayed after it is returned from your asynchronous AJAX call. I also added a bit of error handling. I acknowledge that this might not be appropriate for your particular context, but I thought I'd offer the idea.
The answer given definitely shows the right way to do what you're asking. But I would've approached this differently if you are controlling the server as well. Instead of sending JSON data back, I'd send formatted HTML back and use:
$('#jobSearchResults tbody').load('../data/jobSearchResults/')
Related
so i have an mvc project using php/js/oracle db on the backend and this one thing is completely stumping me.
i have a select that im trying to fill with and array of values received from an ajax call. but when i try to append.() the values to the select nothing happens, no errors that i can see, nothing. it just doesnt assign the values like how i think it should work. this is the block of code
`$("#newuserModal #bscid").focusout(function () {
var based_url = $('#base_url').text();
var bscidlong = $('#newuserModal #bscid').val();
$.ajax({
type: 'POST',
url: based_url + '/user_data/get_roles',
data: {bsc_id: bscidlong},
cache: false,
success: function (data) {
var prole = JSON.parse(data);
var $option = $("<option>");
$option.val("");
$option.text("Select a location type.");
$select.append($option);
if (prole != undefined && prole.length > 0) {
prole.map(function (d, i) {
$('#newuserModal #f_process_role').append(new Option(d.p_role, d.p_role_id));
})
}
}
})
});`
stepping through as the focusout executes the ajax is fine, i get the array of data i expect, hits the if statement loops through without issue but when it gets to the append literally nothing happens and the event ends and the values are not assigned, front end dev really isnt my thing so im stumped as to what is wrong.
You seem to have a typo which is causing the issue:
<select class="form-control col-md-7" id="f_process_role" name="f_process_role" style=" height: 32px;">
the id is "f_process_role" while in your js code you are checking for an id of #f_p_role
$('#newuserModal #f_p_role').append(new Option(d.p_role, d.p_role_id));
You can choose to update the select to match your id as thus:
<select class="form-control col-md-7" id="f_p_role" name="f_p_role" style=" height: 32px;">
How will i be able to display the array values of FileList using foreach inside a div? and reiterate the items one by one?
dataservice code:
var GetUploads = function (GetUploadsObservable) {
var Importoptions = {
url: 'api/test/GetUploads',
type: 'GET',
async: true,
contentType: false,
processData: false,
};
return $.ajax(Importoptions).then(GetDataSucceded).fail(queryFailed);
function GetDataSucceded(data) {
var Filelist = [];
if (data != null) {
data.forEach(function (item) {
Filelist.push(new model.FolderFiles(item));
});
}
GetUploadsObservable(Filelist);
//alert("YYYY");
console.log(Filelist);
}
}
HTML code:
<div id="timesheet" class="" data-bind="foreach: Filelist" style="border:solid 1px red;">
</div>
Your question is bit vague, but if I'm understanding you correctly you're trying to loop through a list of files which you get from some kind of service.
Your file list variable is a local function array therefore isn't available to be bound to the view. What you might want to try is to bind to 'GetUploadsObservable' instead, and make sure GetUploadsObservable is part of your view model. See example below:
<div id="timesheet" class="" data-bind="foreach: GetUploadsObservable" style="border:solid 1px red;"><span data-bind="text: $data"></span></div>
Please see this link for more info on $data: http://knockoutjs.com/documentation/binding-context.html
In a form, i have a dropdownlist and a textbox which will get user's input. Then when the user submits the form, i don't want the whole page to refresh. i only wanted the table which is just below it to refresh and load data from database. I tried code below but only alert pops up. The table is still empty.
$('#frmPrescDrugList').submit(function (e) {
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: '/consultation/PrescDrugList',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html',
success: function (data) {
var row_data = "";
row_data += "#{ var rowNum = 0; } #foreach (var item in Model.LoadDrugList) {
rowNum += 1;
<tr Class="odd gradeX">
<td>#rowNum</td>
<td>#item.dsubsystem</td>
<td>#item.tradename </td>
<td style="text-align: center; vertical-align: middle;"><form Class="form-horizontal" role="form" action="#Url.Action("Prescription", "consultation", new {dgid = item.dgid})" method="post"><Button type="submit" Class="btn btn-default" name="btnDrugListSelect">Select</Button></form></td>
</tr>
}";
$("#LoadDrugListTable").append(row_data);
alert('Drug list has been loaded.');
},
error: function () {
alert('Ajax Submit Failed ...');
}
}); // end ajax
}); // end form-submit
LoadDrugListTable is the table's id. Why didn't it load the data when the ajax is already successful? Can anyone please help point out my mistake or suggest me a better example reference?
I tried following this example, but i'm stuck at the #Url.Action(). Its underlined red. And when i try to separate them by "" and + it's still underlined red saying
Too many characters in character literal.
UPDATED
This is the form i mentioned that doesn't pass the id properly. I'm passing it to a get method. By the way, this is an entirely different page than the one i mentioned above. When i try to do the same thing in another page, it passes a null paid value. Paid is the id. Maybe because this time i'm passing to another page.
"<td style='text-align: center; vertical-align: middle;'><form Class='form-horizontal' role='form' action='#Url.Action("PatientMedicalInfo", "consultation", new { paid = Html.Raw(" + data[i].paid + ") }) method='get'><Button Class='btn btn-default' name='btnSelectPatient' id='btnSelectPatient'>Select</Button></form></td>"
This is the controller:
[HttpGet()]
public ActionResult PatientMedicalInfo(string paid)
{
PatientLookupVM Patient = new PatientLookupVM();
dynamic CurrentPatientDetailsByPtId = Patient.GetCurrentPatientDetailsByPtId(paid);
Patient.LoadCurrentPatientDetails = CurrentPatientDetailsByPtId;
return View(Patient);
}
Try replacing double " quotes with single ' quotes in action.
Well for consistency you could replace them everywhere.
<td ... action='#Url.Action("Prescription", "consultation", new {dgid = item.dgid})' ... </td>
I'm trying to create and HTML chart with a jquery plugin and I'm using HTML5 data attributes to pass data from my rails app to jquery function.
My html, after the ruby hash conversion, is something like this:
<div class="chart" data-contents-01="0" data-contents-02="1" data-contents-03="3" data-contents-04="0" data-contents-05="0" data-contents-06="0" data-contents-07="0" data-contents-08="0" data-contents-09="0" data-contents-10="0" data-contents-11="0" data-contents-12="0" data-contents-13="0" data-contents-14="0" data-contents-15="0" data-contents-16="0" data-contents-17="0" data-contents-18="0" data-contents-19="0" data-contents-20="0" data-contents-21="0" data-contents-22="0" data-contents-23="2" data-contents-24="1" data-contents-25="4" data-contents-26="0" data-contents-27="0" data-contents-28="0" data-contents-29="2" data-contents-30="2" data-contents-31="0" id="chart_2" style="padding: 0px; position: relative;">
I have a lot if data-contents-xx and I must convert this data to an array of array.
My function take data as:
var contents = [
[x, y],
[x,y]
];
so I must process my data attributes to have an array of array, where each sub-array is a couple of data-contents-x
How can i serialize my data attribute?
The JQuery method .data() will pull all data objects into an array of key: value pairs. With your element names:
$('.chart').data();
For example, given:
<div class="chart" data-foo="1" data-bar="2"></div>
Use:
var data = $('.chart').data();
for(var i in data){
console.log("data attribute - " + i + ":" + data[i]);
}
Here's the fiddle: http://jsfiddle.net/WVfSg/260/
When playing with your code in the fiddle, it doesn't work. However, when I get rid of the second hyphen, it works as expected.
The structure I plan to have is an horizontal description list like
key key2 ...
value value2 ...
My code is:
html:
<dl class="horizonal_list">
<dt>Key</dt>
<dd>Value</dd>
</dl>
<dl class="horizonal_list">
<dt>Another key</dt>
<dd>Another value</dd>
</dl>
...
css:
dt, dd {
margin-left: 15px;
margin-right: 15px;
text-align:center;
}
.horizonal_list {
float: left;
}
Basically, I'd like to show into the above horizontal list some information retrieved from the server and then sent to a JSON object, like the following:
var current_status = {"REFERENCE":"1000006",
"NUMBER":108,
"DESCRIPTION":"SC1B",
"CONFIRMATION":"155248",
"CREATION_DATE":15584,
"YEAR":2013,
"NDOQ":161,
"NEZC":"161",
"STATUS":"LI"};
But, I'm very new to web dev and I'd like some tips. Thanks.
You can loop through each property in your object, and then add a new <dl> element for each key/value pair.
NOTE that this example JQuery for appending the html to the DOM.
function addItem(key, value) {
$("div").append('<dl class="horizonal_list"><dt>' + key + '</dt><dd>' + value + '</dd></dl>');
}
for (var key in current_status) {
addItem(key, current_status[key]);
}
Here is a working example
In the example above, <div> has been used to represent an empty container that each <dl> element will be added to. This may be different from what you current have so you will need to change that accordingly.
If you are going to be calling this function more than once you will want to clear the <div> element each time before you populate it:
$("div").empty();
Here is a more realistic example, which shows how to update the data on demand