How do I select a '<td>' and navigate to url using jquery? - javascript

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>';

Related

cant redirect on change event datalist input

I am trying to redirect to a new page with data from the datalist input after a event
(selecting a option) but for some reason its just reloading the page
here is the code I have (I am retrieving the data for the input options with php from a mysql database I don't know if this matters)
<script>
$(document).ready(function() {
$.ajax({
url: 'fetch_data.php',
dataType: 'json',
success: function(data) {
// Populate the datalist input with the data
var datalist = $('#datalist-input');
$.each(data, function(key, item) {
datalist.append('<option data-id="' + item.id + '" value="' + item.name + '">' + item.value + '</option>');
});
// Handle the change event on the datalist input
datalist.change(function() {
// Retrieve the selected option's ID
var selectedOption = datalist.find('option:selected');
var id = selectedOption.data('id');
// Construct the URL of the target page
var targetUrl = 'target_page.php?id=' + id;
// Navigate to the target page
window.location = targetUrl;
});
}
});
});
</script>

Get data by Id using AJAX | JSON ASP.NET

i have this web service methode
List<object[]> List1 = new List<object[]>();
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public List<object[]> GetData(int ID)
{
var team = db.TEST.WHERE(a => a.id == ID).ToList();
List1.Add(new object[]
{
team
});
return teamList;
}
and this my Function using Javascript & jQuer & Json
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData",
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
and this my button to get data
<input id="Button1" type="button" onclick="BindMembersList(1)" value="button" />
My problem is where i need to put the id for give just data have id equal 1
thank you
Since it's an url you are calling, pass it on the url of your AJAX call like so:
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData/" + id,
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
If it's not working or you need to pass more parameter to the action, you can specify them and using the "&" as separator like so:
url: "/WebService1.asmx/GetData?id=" + id + "&parameter2=" + param,
Anyway, your c# method is wrong since you are returning teamList, which is not implemented inside the action
Try this url:
url: "/WebService1.asmx/GetData?id="+id

How to save the data into database in jquery and display upon the screen using web api

I want to add the values inot the database but I am not to able to do that.
var Array;
$(document).ready(function ()
{
$.ajax({
url: '../api/Emp/GetAll',
type: 'Get',
cache: false,
datatype: 'json',
success: function (text) {
Array = text.Table;
var List = JSON.stringify(text);
for (var i = 0; i < data.length; i++) {
var Id = Array[i].id;
var Name =Array[i].name;
var city = Array[i].city;
$('#table body').append('<tr><td>' + Id + '</td><td><input type="text" value="' + Name + '" id="txt' + Id + '" /></td><td>' + city + '</td> </tr>');
}
}
})
If you need to put it back into the database you just need to reverse the process.
Use post for your type and send the data back with ajax to a php script page that inserts the data into your database.
You can edit the data on the php page before you insert it into the database or you can edit the data with javascript then send it back to php page.
Create an ajax post
$.ajax({
type: "post",
datatype: "json",
url: "insertPage.php",
data: {dataNameHere: editedDataGoesHere},
success: function(data){
alert("SUCCESS");
},
error: function(e){
alert("ERROR");
}
});
And then in your PHP:
$obj = $_POST['dataNameHere'];
and insert it into your database like you normally would.

how to display JSON Array into table using AJAX in JSP

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) {
}
});

Jquery each data object attribute

I am trying to create table rows containing data from each attribute from my object response using $.each, however the Id, Purpose, and Amount are coming back undefined. I have tested the response in Fiddler and the data is all being received correctly, the problem just seems to be in the "item" part. Here is my Jquery:
$.ajax({
type: "GET",
url: "https://chad-test4.clas.uconn.edu/api/Commitments/GetCommitmentPurposes/2",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function (response) {
var purposes = $("#purposes tbody");
if (response.Success == true) {
purposes.empty();
var buttons = '<tr><td><button type="button" class="btn-primary">Save</button>'
+ '<button type="button" class=".btn-danger">Delete</button></td>'
var list = response.Data;
$.each(list, function (i, item) {
purposes.append(buttons + '<td><select id=' + item.Id + '>' + item.Purpose + '</select>'
+ '<td><input type="text" val =' + item.Amount + '/>')
});
}
}
});
});
Could you post a snippet of JSON aswell ?
Basically I believe what you need to do is to access the entries by an identifier:
$.each( list.items, function(i, item ) {
But posting JSON would clarify if that is true.

Categories