How to get data from map json using jquery ajax? - javascript

i try go get the json data with the nested mapping json .
$.ajax
({
url: apiNik+"?nik="+nik,
type: 'get',
dataType: 'json',
headers: {
"Authorization": "Bearer "+token,
},
success: function(res)
{
var date = res.date;
console.log(date);
$.each(date, function(index, value){
$('#test223').append(`
<div class="carousel-item">
<div class="card">
<div class="date column">${value.date_show}</div>
<div class="card-body">
<h5 class="card-title">${value.????}</h5>
</div>
</div>
</div>
`);
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var err = JSON.parse(XMLHttpRequest.responseText);
console.log(err)
if (err.code === 401) {
window.location.replace(page1url);
Cookies.remove('token')
}
alert(err.message);
window.location.reload()
}
})
This is the json that i used for the code.
{
"id":"1231231",
"name":"testgo",
"date":[
{
"date_show":"Sunday, 2 February 2023",
"detail":[
{
"first_name":"first1",
"last_name":"last1"
},
{
"first_name":"first1.1",
"last_name":"last1.1"
}
]
},
{
"date_show":"Monday, 1 February 2023",
"detail":[
{
"first_name":"first2.2",
"last_name":"last2.2"
}
]
},
{
"date_show":"Saturday, January 2023",
"detail":null
}
]
}
I want to show the data with the same date and list detail . i confused how to retrieve the data.
The result i want to show the date with the list detail in the one card(html) . and list all the date for the card

Related

Cascading Dropdown - How to load Data?

I try to make an cascading dropdown, but I have problems with the sending and fetching of the response data.
Backend:
[HttpPost]
public async Task<JsonResult> CascadeDropDowns(string type, int id)
{ .............
return Json(model);
}
Here I get the correct data.
First I tried:
$("#dropdown").change( function () {
var valueId = $(this).val();
var name = $(this).attr("id");
let data = new URLSearchParams();
data.append("type", name);
data.append("id", valueId);
fetch("#Url.Action("CascadeDropDowns", "Home")", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
console.log('Success:', response);
return response.json();
})
.then(json => {
console.log('Success:', json );
console.log('data:', json.Projects);
PopulateDropDown("#subdropdown1",json.Projects)
})
.catch(error => {
console.log('Error:', error);
});
});
Here I can send the Request and get a "success" back. However, when I access json.Projects I just get an `undefined. I have tried to change the Content-Type, without success.
Secondly I have used:
$.ajax({
url: "#Url.Action("CascadeDropDowns", "Home")",
data: data,
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
console.log(data);
},
error: function (r) {
console.log(r.responseText);
},
failure: function (r) {
console.log(r.responseText);
}
});
With this I get an Illegal Invocation Error.
What do I have to do that get either of those working? What are their problems?
I try to make an cascading dropdown, but I have problems with the
sending and fetching of the response data.What do I have to do that get either of those working? What are their problems?
Well, let consider the first approach, you are trying to retrieve response like json.Projects but its incorrect because data is not there and you are getting undefined as below:
Solution:
Your response would be in json instead of json.Projects
Complete Demo:
HTML:
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-6">
<select class="form-control" id="ddlState"></select>
<br />
</div>
</div>
Javascript:
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Please wait ...'));
let data = new URLSearchParams();
data.append("type", "INDIA");
data.append("id", 101);
fetch("http://localhost:5094/ReactPost/CascadeDropDowns", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(result, function (index, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
})
Second approach:
In ajax request you are passing object as object fahsion like data: data whereas, your controller expecting as parameter consequently, you are getting following error:
Solution:
You should pass your data within your ajax request like this way data: { type: "YourTypeValue", id:101 }, instead of data: data,
Complete Sample:
$.ajax({
url: 'http://localhost:5094/ReactPost/CascadeDropDowns',
type: 'POST',
data: { type: "YourValue", id:101 },
success: function (response) {
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(response, function (i, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
},
error: function (response) {
alert('Error!');
}
});
Note: I have ommited contentType because, by default contentType is "application/x-www-form-urlencoded;charset=UTF-8" if we don't define.
Output:

In ASP.NET Razor Page Jquery Ajax Function not Working

I have a two onchange function for a page called create delivery request. One is when the dropdownlist of receiver changes, then it should show the phone number & address of receiver selected. Another one is when the dropdownlist of delivery item changes, then it should set the max attribute for the quantity.
The url of both these are linked to the customized OnGet method in razor page.
However, usually the above Onget method is hit but the below one is not. And the above OnGet method can't get the dryfood with the passed ID as well, it is null inside. And the two jQuery ajax function doesn't work at all. I'm totally a beginner. Hope that there is someone who can help me. Thanks in advance.
In create.cshtml:
<div class="mb-3">
Receiver Name
<select id="receiver" asp-for="Delivery.ReceiverID" asp-items="Model.ReceiverList" class="form-control">
<option>--Select the Receiever--</option>
</select>
</div>
<div class="mb-3">
Receiver Phone
<span id="receiverphone" class="form-control">----</span>
</div>
<div class="mb-3">
Receiver Address
<div id="receiveradrs1" class="form-control">----</div>
<div id="receiveradrs2" class="form-control">----</div>
</div>
<div class="mb-3">
Delivery Item
<select id="deliveryitem" asp-for="DeliveryItem.DryFoodID" asp-items="Model.DeliveryItemList" class="form-control">
<option>--Select Delivery Item--</option>
</select>
</div>
<div class="mb-3">
Quantity
<input id="quantity" asp-for="DeliveryItem.Quantity" min="1" class="form-control" />
</div>
In create.csthml.cs, two customized OnGet method here:
public async Task<IActionResult> OnGetSetMaxQuantity(int id)
{
List<DryFoodDonation> dfdlist = await _db.DryFoodDonation.ToListAsync();
var dryfood = dfdlist.Where(d => d.Id == id).FirstOrDefault();
Debug.WriteLine(dryfood.DryFoodName + " " + dryfood.DryFoodRemainQuantity);
return new JsonResult(dryfood.DryFoodRemainQuantity);
}
public async Task<IActionResult> OnGetGetPhoneAdrs(int id)
{
List<User> receiverlist = await _db.User.Where(u => u.UserType.TypeID == 3).ToListAsync();
var selectreceiver = receiverlist.Where(d => d.UserID == id).FirstOrDefault();
Debug.WriteLine(selectreceiver.UserName + " " + selectreceiver.UserPhone);
return new JsonResult(selectreceiver);
}
The jQuery AJAX function in a JavaScript file:
$(document).ready(function () {
$("#receiver").change(function () {
alert('Yes receiver here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=GetPhoneAdrs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
'id': item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$('#receiverphone').html(data.UserPhone);
$('#receiveradrs1').html(data.UserAdrs1);
$('#receiveradrs2').html(data.UserAdrs2);
}
});
});
$("#deliveryitem").change(function () {
alert('Yes item here changed.');
var item = $(this).val();
$.ajax({
type: 'GET',
url: 'Create/?handler=SetMaxQuantity',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
"id": item
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$("#quantity").attr({
"min": 1,
"max": data
});
}
});
});
});
Please help me with this. I can't solve this problem for a few weeks. Thank you!
// cshtml.cs
const sendMe = async function (someData) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ControllerName/MethodNameInController',
data: { someData: someData },
success: function (response) {
if (response != null && response.statusCode == 200) {
..
} else {
..
}
}
});
}
//Controller
[HttpPost("MethodNameInController")]
public IActionResult MethodNameInController([FromForm] string someData) {
..
}

How to make multiple post requests with one button submit in React?

I am trying to convert my Jquery code to React. I have a form that when submitted creates multiple post requests to different sites and generates data for each site in a "card" corresponding to each site.
I made a component for the form. I also have a handleSubmit event but that only makes one fetch request. I want to make multiple fetch requests to multiple sites with one button click.
handleSubmit(event) {
event.preventDefault();
this.setState({
input: event.target.value
})
const data = new FormData(event.target);
fetch('/d2s2/L1000', {
method: 'POST',
body: data
})
}
render () {
return (
<div>
<form class="form-inline" role="form">
<div class="form-group" style="text-align:center;">
<select id="memoryType" class="form-control firstList">
<option value="drug" selected="selected">Drug</option>
<option value="disease">Disease</option>
</select>
</div>
<div class="form-group">
<select id="drugInput" class="form-control search-input secondList" name="drug">
</select>
</div>
<button class="form-control" id="submit"><i class="fas fa-search"></i></button>
</form>
</div>
)
}
this is my Jquery:
$("#submit").click(function(e) {
var selectedOption = $('#memoryType option:selected').val();
var text= $("#drugInput option:selected").val();
var search = JSON.stringify({"input": text});
$('.post-load').show();
if (selectedOption.toLowerCase() == "drug") {
$.post("/d2s2/L1000", search, function(data) {
console.log(data);
$(".card-1").html(data);
$('.loader1').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-1 .card-text").html("No significant signatures found");
$('.loader1').fadeOut('fast');
})
$.post("/d2s2/creeds_drugs", search, function(data) {
console.log(data);
$(".card-2").html(data);
$('.loader2').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-2 .card-text").html("No significant signatures found");
$('.loader2').fadeOut('fast');
})
$.post("/d2s2/creeds_diseases", search, function(data) {
console.log(data);
$(".card-3").html(data);
$('.loader3').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-3 .card-text").html("No significant signatures found");
$('.loader3').fadeOut('fast');
})
$.post("/d2s2/geneshot", search, function(data) {
console.log(data);
$(".card-4").html(data);
$('.loader4').fadeOut('fast');
}).fail( function(xhr, textStatus, errorThrown) {
$(".card-4 .card-text").html("No significant signatures found");
$('.loader4').fadeOut('fast');
})
When I click on the submit button, all the cards should make post requests to their respective endpoints.
You can declare a state for each site you are requesting to and handle the requests separately like this:
state = {
site1: {},
site2: {}
}
requestSite1 = data => {
fetch('site1Url', {
method: 'POST',
body: data
}).then(res => this.setState({ site1: res }))
}
requestSite2 = data => {
fetch('site2Url', {
method: 'POST',
body: data
}).then(res => this.setState({ site2: res }))
}
async handleSubmit(event) {
event.preventDefault();
this.setState({
input: event.target.value
})
const data = new FormData(event.target);
await this.requestSite1(data);
await this.requestSite2(data);
}
and pass the states as props to your Card component like:
<Card site1Data={this.state.site1} site2Data={this.state.site2} />

How to update a textbox with the result from a get Request

I have a simple web page designed to show the list of players when a certain team is selected. Currently my API can successfully return all of the players and display it it on the console log, but I am confused on how to you connect that with my div container.
My function returns all the player names as a list
<div class="card">
<div class="card-header"> Player List</div>
<div class="card-body">
<label>Teams</label>
<select id="playerDisplay" onChange="updatePlayerlist();">
<option value=" ">Select a Team</option>
<option value="Fractional">Giants</option>
</select>
<div class="col-sm-7">
<label>Players</label>
<div id="listPlayers"></div>
</div>
</div>
</div>
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log(list);
playerPick = list;
} else
console.log("EMPTY");
}
})
}
Given that you state:
My function returns all the player names as a list
I'm going to assume that the response is an array of strings. Therefore you can simply loop through that and create the new elements to append to the DOM. Try this:
function updatePlayerslist() {
var playerPick = $("#playerDisplay").val(); // Note use of jQuery here
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(playerNames) {
var html = playerNames.map(function(playerName) {
return `<div>${playerName}</div>`;
});
$('#listPlayers').append(html);
}
})
}
function updatePlayerslist() {
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list) {
if (list.length === 0) {
console.log("EMPTY");
}
// Construct the text to be displayed from the `list` data
var textToDisplay = list.join(', ');
// Update the html
$('#listPlayers').html(textToDisplay);
}
})
}
loop through the list and update the element by appending with jQuery
function updatePlayerslist(){
var playerPick = $("#playerDisplay")[0].value;
$.ajax({
type: 'GET',
url: APICALL,
data: {
'code': playerPick
},
success: function(list){
console.log(list);
list.forEach(value => {
$("#listPlayers").append(value)
})
}
})
}

jQuery Select2 not displaying Data

I am stuck at problem where i believe i am getting the response in correct format but i am not able to display the data returned from the server. Intelligent Minds! I need your help.
Below is my HTML code:
<div class="form-group">
<select id="owner" class="dropDowns">
<option value="00000" selected="selected">Select Owner</option>
</select>
</div>
JQuery Code:
This function is getting called with no problems and a result is also returned from the server but some how i am not able to format that result and display it to the user. I am not sure what i am doing wrong and this has been bugging me for quiet some time now.
$("#owner").select2({
minimumInputLength: 3,
ajax: {
url: "http://localhost:8080/iam/aexp/rest/ePAAS/getOwner",
dataType: "jsonp",
headers: {
"Authorization": "Basic " + btoa('spadmin' + ":" + 'admin')
},
type: 'GET',
delay: 250,
data: function (params) {
return {
adsId: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
formatResult: function (data) {
return "<div>" + data.id + "</div>";
},
formatSelection: function (data) {
return data.id;
}
});
And here is the response I am getting from the server:
[{"id":0,"text":"rgadke"}]
Thanks!
I found the issue. I was not returning the result in the correct JSON format

Categories

Resources