I am new to ajax. I am trying to display data into table in JSP file.
API is called using AJAX.
Controller pass below response:
BatchwiseStudent [name=Ram, course=MCA (Commerce), emailId=rammansawala#gmail.com, placed=null, batch=2016, mobileNo=7.276339096E9]
In JSP page:
<script type="text/javascript">
function getStudentDetails(){
$batch = $('#batch');
$course = $('#course');
$.ajax({
type: "GET",
url: "./batchAjax?batchId="+$batch.val()+"&courseId="+$course.val(),
success: function(data){
console.log("SUCCESS ", data);
if(data!=null){
$("#batchwiseTable").find("tr:gt(0)").remove();
var batchwiseTable = $("#batchwiseTable");
$.each(JSON.parse(data),function(key,value){
console.log(key + ":" + value);
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['name']);
rowNew.children().eq(2).text(value['emailId']);
rowNew.children().eq(3).text(value['placed']);
rowNew.children().eq(4).text(value['batch']);
rowNew.children().eq(5).text(value['mobileNo']);
rowNew.appendTo(batchwiseTable);
});
$("#batchwiseTable").show();
}
},
error: function(e){
console.log("ERROR ", e);
}
});
}
</script>
I can see new row into the table but there is no data. I want name, emaild, mobileNo, etc into particular field.
can anyone guide me where am i wrong?
Below code should be keep in the .jsp Page where you show table you don;t need to write html code for table jsp page.
<div id="insert-table-here"></div>
Javascript code:
below code is for ajax call
replace uri with your url value that is used in your url.
$.ajax({
type: 'GET',
url: uri,
success: function (data) {
var str = '<table class="table table-bordered"><thead>'+
'<tr><td>Name</td><td>Course</td><td>EmailId</td><td>Place</td><td>Batch</td><td>Mobile Number</td></tr></thead><tbody>';
$.each(data, function (key, value) {
str = str + '<tr><td>' +
value.name + '</td><td>' +
value.course + '</td><td>' +
value.emailId + '</td><td>' +
value.placed + '</td><td>' +
value.batch + '</td><td>' +
value.mobileNo + '</td></tr>';
});
str = str + '</tbody></table>';
$('#insert-table-here').html(str);
}, error: function (data) {
}, complete: function (data) {
}
});
Related
I am using ajax and dynamically manipulating <td> elements inside success returning of data using java script.
I have tried and everything is running fine , I am getting data inside my <td> elements but unfortunately can not handle how to put anchor tag inside some <td> elements as those returning data containing some files that is present on server folder so I need to make anchor tag so that user can open the file .
$("#Status").on('change', function () {
$("#Table11").find("tr:not(:first)").remove();
debugger;
var Status = $("#Status").val();
$.ajax({
url: '/BusinessCaseProcess/GetRec',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { Status: Status },
success: function (response) {
debugger;
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.Title + '</td><td>' + item.EmployeeName + '</td><td>' + item.Department + '</td><td>' + item.SubDepartment + '</td><td>' + item.Station + '</td><td>' + item.DateOfRequest + '</td><td>' + item.TrackingID + '</td><td>Primary </td><td>Secondary </td><td>' + item.HeadOfDepartmentStatus + '</td><td>' + item.HRMStatus + '</td><td>' + item.HeadOfITStatus + '</td><td>' + item.FinanceControllerStatus + '</td><td>' + item.VPPStatus + '</td></tr>';
});
$('#Table11').append(trHTML);
}
})
As you can see i am trying to make anchor tag inside td elements in code. The variable is containing the file name , and inside href i am giving folder name , i need to open the file on click just like anchor tag does.
I am using jquery to pull football data from an api as follows
type: 'GET',
dataType: 'json',
url: "http://api.football-data.org/v1/competitions/426/teams",
processData: true,
//idLength: url.Length - url.LastIndexOf("/", StringComparison.Ordinal) - 1,
//id: url.Substring(url.LastIndexOf("/", StringComparison.Ordinal) + 1, idLength),
success: function (data, status) {
var trHTML = '';
$.each(data.teams, function (key, item) {
var id = item._links.self.href;
var indexOfLastBackSlash = id.lastIndexOf("/") + 1;
id = id.substring(indexOfLastBackSlash);
//$('<option>', { text: item.TeamName, id: item.ID }).appendTo('#lstTeams');
trHTML += '<tr class="info"><td>' + item.name +
'</td><td>' + item.code +
'</td><td>' + item.shortName +
'</td><td>' + item.squadMarketValue +
'</td><td>' + item.crestURL +
'</td><td>' + id +
'</td></tr>';
I want to be able to select a 'td' and navigate to another url like "http://api.football-data.org/v1/teams/322/fixtures" for the team with id of 322. How can I do so?
You can create a function which will do same ajax request but this time for single record. On your target's click event you need to call that function passing the id you need to fetch records for. One way of doing this is to set a data attribute to your target container.
Below is the sample code performing similar functionality.
$(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/',
method: 'GET',
dataType: 'json'
}).then(function(Data) {
$.each(Data, function (key, data) {
var id = data.id;
var title = data.title;
$('.tableAllRecords').append('<tr><td><a href=# class=mylink data-id='+id+'>'+id+'</a></td><td>'+title+'</td></tr>');
});
});
});
function fetchSingle(id) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/' + id,
method: 'GET',
dataType: 'json'
}).then(function(data) {
var id = data.id;
var title = data.title;
var body = data.body;
$('.tableSingleRecord').append('<tr><td>'+id+'</td><td>'+title+'</td><td>'+body+'</td></tr>');
});
}
$(document).on('click', '.mylink', function(e) {
var id = $(this).data('id');
fetchSingle(id);
e.preventDefault(); // disabling anchor's default [redirect] behaviour
});
Here is the link to fiddle. https://jsfiddle.net/2h54vu7h/
If you need to display records on a new page, you simply have to pass id into your url and on next page you have make an ajax request getting the id variable from url.
Example: '<a href=somepage.html?id='+id+'>View Details</a>';
I am calling an Ajax function from another function and want to get the response and then parse the Json in order to assign it to new divs.
The call is made like this: thedata = GetChequesByBatchID(batchId); and this is the response:
Then, I am trying to loop through the response, but this is where the problem is. I am not sure how to get the response and loop through the thedata. This data should be assigned to the htmlFromJson so it will be inserted as group of divs in the TR. Any ideas?
My function:
<script type="text/javascript">
$(document).ready(function (params) {
var batchId;
var thedata;
var htmlFromJson = "";
$('.showDetails').click(function () {
// Show Details DIV
$(this).closest('tr').find('.details').toggle('fast');
batchId = $(this).data('batchid');
thedata = GetChequesByBatchID(batchId);
var json = jQuery.parseJSON(thedata);
$.each(json, function () {
htmlFromJson = htmlFromJson + ('<div class="ListTaskName">' + this.ChequeID + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAccountNumber + '</div>' +
'<div class="ListTaskDescription">' + this.ChequeAmount + '</div>');
});
}).toggle(
function () {
// Trigger text/html to toggle to when hiding.
$(this).html('Hide Details').stop();
$(this).closest("tr").after("<tr class='456456'><td></td><td colspan = '999'>" + '<div class="zzss">' + htmlFromJson + '</div></td></tr>');
},
function () {
// Trigger text/html to toggle to when showing.
$(this).html('Show Details').stop();
//$(this).find('.zoom').remove();
$('tr.456456').remove();
}
);
});
</script>
My Ajax function:
<script type="text/javascript">
function GetChequesByBatchID(BatchID) {
var xss;
var qstring = '?' + jQuery.param({ 'BatchID': BatchID });
return $.ajax({
url: '<%=ResolveUrl("~/DesktopModules/PsaMain/API/ModuleTask/GetChequesByBatchID")%>' + qstring,
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
jQuery.parseJSON(result); //the response
},
error: function (response) {
alert("1 " + response.responseText);
},
failure: function (response) {
alert("2 " + response.responseText);
}
});
return xss;
}
</script>
$.ajax is async operation (if you don't include async:false option which is not recommended) so your GetChequesByBatchID function immediately returns either $.ajax object or undefined. Correct usage of $.ajax is to call DOM changing methods from success or error parts of $.ajax.
I do not understand how to do the right thing.
With this query I get a JSON with the file names:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
With this query I get a JSON with the tag names:
$.getJSON("http://api.server.com/list/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<label class='radio'><input type='radio' name='list' id='" + result.List + "' value='" + result.List + "' checked>" + result.List + "</label>");
});
$('.my_list').html(results.join(""));
}
);
In the end, I need to display a list of files. Next to each file should to show a form with a file name and a list of tags:
$(document).on('click', '.share_file_form', function() {
$('.share_file_form').validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
All of this works.
The question is how to make sure that each form will work separately?
Now only works the first form. If you press the button on the other forms will still work the first form.
Your mistake is in the way you identify the form on which the user clicked. The following line is the problem:
$('.share_file_form').validate({
Independent of what you clicked on, you always will get the first form with this selector.
Here is what you need instead:
$(document).on('click', '.share_file_form', function(event) {
$(event.target).validate({
submitHandler: function(form) {
hmm. I 'think' I know what you want..
how about wrapping the second call in a method, or perhaps both, ala.
function fireJSON(){
var func1 = function(){
//your first json code
func2(); // call your second json code
}
var func2 = function(){
// second json code
}
return {
func1: func1
}
}
fireJSON().func1();
I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.