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)
})
}
})
}
Related
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) {
..
}
I have a function for adding likes on the page
blade.php
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_heart }}
</div>
<a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button">
<div class="comments-sub-header__item-icon-count">
{{ $article->like_finger }}
</div>
js
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
});
$('.like-button').on('click', function(event) {
event.preventDefault();
let href = $(this).attr('href');
$.ajax({
url: href,
type: 'POST',
success: function() {
window.location.reload();
},
});
});
});
But when I click on the like to update the data, I reload the page using window.location.reload();
Can this somehow be done without reloading the page?
This is how adding likes is implemented, they are added to cookies and stored for 24 hours
web routes
Route::post('article/{id}', 'App\Http\Controllers\ArticleController#postLike');
Article controller
public function postLike($id, Request $request) {
$article = Article::find($id);
if(!$article){
return abort(404);
}
$type = $request->input('type');
if ($article->hasLikedToday($type)) {
return response()
->json([
'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.',
]);
}
$cookie = $article->setLikeCookie($type);
$article->increment("like_{$type}");
return response()
->json([
'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
Article model
public function hasLikedToday(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
if (!array_key_exists($this->id, $articleLikes)) {
return false;
}
if (!array_key_exists($type, $articleLikes[$this->id])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$this->id][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public function setLikeCookie(string $type)
{
$articleLikesJson = Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
$articleLikes[$this->id][$type] = now()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
Assuming those DIVs hold the number of hearts, if the response of the target page is the new number of hearts then:
success: function(data) {
targetElement.find(".comments-sub-header__item-icon-count").html(data)
}
elsewhere if you want to add +1 to current number regardless of server response:
success: function() {
var current= parseInt(targetElement.find(".comments-sub-header__item-icon-count").html());
targetElement.find(".comments-sub-header__item-icon-count").html(current+1)
}
Footnote: as the ajax request is nested inside the click function, the targetElement in my codes is the clicked element. You may get it in defferent ways e.g.
$('.like-button').on('click', function(event) {
var targetElement=$(this);
....
}
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
});
$('.like-button').on('click', function(event) {
event.preventDefault();
let href = $(this).attr('href');
$.ajax({
url: href,
type: 'POST',
success: function(response) {
$(this).parent(".comments-sub-header__item-icon-count").html(
parseInt($(this).parent(".comments-sub-header__item-icon-count").html()) + 1
)
// or return like or heart count from server
$(this).parent(".comments-sub-header__item-icon-count").html(response)
},
});
});
});
This should work for you
$(function () {
$.ajaxSetup({
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
},
});
$(".like-button").on("click", function (event) {
event.preventDefault();
const likeBtn = $(this);
$.ajax({
url: likeBtn.attr("href"),
type: "POST",
success: function () {
let currentCount = likeBtn.next().text();
likeBtn.next().text(parseInt(currentCount) + 1);
},
});
});
});
You can simply add the new count to the response from your controller.
return response()
->json([
'message' => 'Liked the Article '.$article->id.' with '.$type.'.',
'cookie_json' => $cookie->getValue(),
'new_count' => $article->{"like_{$type}"},
])
->withCookie($cookie);
Now you can use the updated count as new_count from the database.
$.ajax({
url: href,
type: 'POST',
success: function (response) {
$(this).next().text(response.new_count)
},
});
As you can see I have a for loop with Multiple ID and I want get the value of IDs and pass them to my controller, how can I achieve this ?
<form id="UserEdit">
#for (int i = 0; i < Model.Rights.Count; i++)
{
#Html.HiddenFor(m => m.Rights[i].ID)
}
<input id="BtnEditUserJS" onclick="PostFormUserEdit();" type="submit" value="Edit">
</form>
Generated HTML:
<input id="Rights_0__ID" name="Rights[0].ID" type="hidden" value="31">
<input id="Rights_1__ID" name="Rights[1].ID" type="hidden" value="32">
JavaScript:
function PostFormUserEdit() {
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: ,
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
Controller:
[HttpPost]
public JsonResult EditUser(int[] RightId)
{
var rights = db.Rights.Where(b => RightId.Contains(b.Id)).ToList();
//do something with rights
}
You can achieve it this way :
function PostFormUserEdit()
{
var arr = [];
$("#UserEdit input[type='hidden']").each(function (index, obj) {
arr.push(obj.val());
});
$.ajax({
type: 'POST',
url: '#Url.Action("EditUser")',
dataType: 'json',
data: arr , // or you can try data: JSON.stringify(arr)
success: function (run) {
console.log('Ok');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
I have concern regarding of javascript function, The question is there any indicator to determine if the javascript function still on going or still running? because I have problem on inserting hundred of items inserting in the database. I want to condition if the javascript function still on going the insertion will stay until the condition met the else if the javascript function is not running or done, it will automatically redirect to the other page.
In my onclick of my jquery I insert the javascript function.
$('#add_to_cart').on('click', function() {
orders = [];
menu = undefined;
$('.tbody_noun_chaining_order').children('tr').each(function() {
$row = $(this);
if ($row.hasClass('condimentParent')) {
if (menu) {
orders.push(menu);
}
menu = {
'total': $row.find('.total').text(),
'name': $row.find('.parent_item').text(),
'customer_id': customer_id,
'condiments': {
'Item': [],
'Qty': [],
'Total': []
}
};
} else if ($row.hasClass('editCondiments')) {
menu.condiments.Item.push($row.find('.child_item').text());
menu.condiments.Qty.push($row.find('.condiments_order_quantity').text());
menu.condiments.Total.push($row.find('.total').text());
}
});
if (menu) {
orders.push(menu);
}
storeOrder(orders)
});
My Javascript Function
function storeOrder(data) {
var customer_id = $('#hidden_customer_id').val();
var place_customer = $('#place_customer').text();
$id = "";
$total_amount = $('.total_amount').text();
$append_customer_noun_order_price = $('.append_customer_noun_order_price').text();
$tax_rate = $('.rate_computation').text();
$delivery_rate = $('.del_rate').text();
var sessionTransactionNumber_insert = localStorage.getItem('sessionTransactionNumber');
$.ajax({
url:'/insert_customer_order_properties',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'hidden_customer_address': place_customer,
'sessionTransactionNumber': sessionTransactionNumber_insert
},
success:function(data) {
$id = data[0].id;
$.ajax({
url:'/insert_customer_payment_details',
type:'POST',
data:{
'hidden_customer_id': customer_id,
'total_amount': $total_amount,
'customer_sub_total': $append_customer_noun_order_price,
'tax_rate': $tax_rate,
'id_last_inserted': $id
},
success:function(data) {
localStorage.removeItem('sessionTransactionNumber');
}
})
}
})
for (var num in orders) {
$.ajax('/insert_wish_list_menu_order', {
type: 'POST',
context: orders[num].condiments,
data: {
'append_customer_noun_order_price': orders[num].total,
'append_customer_noun_order': orders[num].name,
'customer_id': customer_id
},
success: function(orderNumber) {
$order_number = orderNumber[0].id;
$.ajax({
url:'/insert_customer_order_details_properties',
type:'POST',
data:{
'order_number': $order_number,
'data_attribute_wish_order_id': $id,
},
success:function(data) {
console.log(data);
}
})
if (orderNumber !== undefined) {
$.ajax('/insert_wish_list_menu_belong_condiments', {
context: orderNumber,
type: 'POST',
data: {
'ParentId': orderNumber,
'Item': this.Item,
'Qty': this.Qty,
'Total': this.Total
},
success: function(result) {
console.log(result);
},
})
}
}
})
}
}
I'm trying to change the class and text of the button that was clicked based on the result from an ajax post. The page has many buttons, none have IDs (although I could add them if it's for sure needed). I have the following javascript:
$('.ph-button').click(function () {
var selected = [];
$(this).closest('tr').each(function () {
$(this).find('td').each(function() {
selected.push($(this).html));
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
//need the if statements here I think
console.log(data);
}
});
});
It works and gives me a 0 or 1 as data. I need to change the class to class='ph-button ph-btn-blue and the text to Watched if data is 0 and change the class to class='ph-button ph-btn-grey and the text to Watch if data is 1.
I tried using $(".ph-button").toggleClass("ph-button ph-btn-blue"); but it changed the class of all the buttons on the page and didn't seem to do it like I need.
I'm guessing toggleClass isn't what I need and i'm not sure how to address the button that was clicked instead of all of them. Here are the two possible buttons:
<td><button class='ph-button ph-btn-blue'>Watched</button></td>
<td><button class='ph-button ph-btn-grey'>Watch</button></td>
SOLUTION:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
console.log(data);
if (data == 1) {
btn.toggleClass("ph-btn-grey ph-btn-blue").text('Watched');
}
if (data == 0) {
btn.toggleClass("ph-btn-blue ph-btn-grey").text('Watch');
}
}
});
});
set a temporary variable referencing the button, so you can use it later on in your AJAX success callback:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
if(data == "0"){
btn.toggleClass("ph-button ph-btn-blue").text('Watched');
}
}
});
});