How to select element of click element parents using jQuery? - javascript

I have following HTML code and I am calling ajax using click event using this class .educacao_search.
<div class="tab-pane active" id="tab-educacao">
<br>
<div class="row">
<div class="col-md-12">
<h4>EucaÇÃo</h4>
<ul class="list-inline three">
<li><a class="educacao_search" data-slug="ension">Ensino</a></li>
<li><a class="educacao_search" data-slug="enem">ENEM</a></li>
<li><a class="educacao_search" data-slug="escolas">Escolas</a></li>
<li><a class="educacao_search" data-slug="lingua-e-linguagens">Lingua e Linguagens</a></li>
<li><a class="educacao_search" data-slug="historia">História</a></li>
<li><a class="educacao_search" data-slug="todos">Todos</a></li>
</ul>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group has-feedback has-search">
<input type="text" class="form-control" placeholder="Search" id="do_search_educacao">
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
</div>
</div>
<br>
<div class="row"><div class="show_result"></div><br></div>
</div>
now I on success I want to show result in show_result class.
To do this I am using collowing jQuery code but it seems not working! I mean the result is not showing in this class called show_result
$(this).parents(".tab-pane").find(".show_result").html(result);
Note: this is a bootstrap tabs and there are 5 tabs with same classes which is educacao_search and show_result
Update:
Ajax Call:
$(".educacao_search").click(function () {
var slug = $(this).data('slug');
$.ajax({
type: 'POST',
url: urls.ajax_url,
data: {
'slug': slug,
'action': 'get_post_content'
}, success: function (result) {
$(this).parents(".tab-pane").find(".show_result").html(result);
//$(this).find(".show_result").html(result);
},
error: function () {
alert("error");
}
});
});

Declare var obj = $(this); before .ajax and use it inside success callback.
$(".educacao_search").click(function () {
var slug = $(this).data('slug');
var obj = $(this);
$.ajax({
type: 'POST',
url: urls.ajax_url,
data: {
'slug': slug,
'action': 'get_post_content'
}, success: function (result) {
obj.parents(".tab-pane").find(".show_result").html(result);
//$(this).find(".show_result").html(result);
},
error: function () {
alert("error");
}
});
});
It's important to know how this keyword works in javascript. Refer below links it will be helpful.
https://javascript.info/object-methods
https://medium.com/tech-tajawal/javascript-this-4-rules-7354abdb274c

Related

Ajax status update in one page with one button

I am trying to update the status for my orders on the same page where it's displayed with an ajax HTML.
Displaying works just fine, but I want to set the status the the next one with only one click so I figured to use ajax for it too.
My ajax PUT for the next status
$(function () {
$(document).on('click', 'button#order_update', function (e) {
e.preventDefault();
let newStatus = '';
if ($(this).data('status') == 'pending') {
newStatus = 'confirm';
} else if ($(this).data('status') == 'confirm') {
newStatus = 'processing';
} else if ($(this).data('status') == 'processing') {
newStatus = 'picked';
}
let formStatusData = new FormData();
formStatusData.append('order_id', $(this).data('order'));
$.ajax({
type: 'PUT',
url: '{{ route("update-order-status") }}',
data: formStatusData,
success: (response) => {
console.log(response);
$(this).data('status', newStatus);
$(this).text(newStatus.charAt(0).toUpperCase() + ' order');
}
});
});
});
My ajax for the html
$.ajax({
type: 'GET',
url: '/order/view/all',
dataType: 'json',
cache: false,
success:function(response){
$('#pimage').attr('url','/'+response.product.product_thambnail);
var product_name = $('#pname').text();
var id = $('#product_id').val();
var quantity = $('#qty').val();
var OrderView = ""
$.each(response.orders, function (key,value){
var productsList = '';
$.each(value.product, function (key,value) {
productsList += `
<div class="row gx-4">
<div class="col-lg-3">
<div class="pos-task-product">
<div class="pos-task-product-img">
<div class="cover" style="background-image: url(${value.product_thambnail});"></div>
</div>
<div class="pos-task-product-info">
<div class="flex-1">
<div class="d-flex mb-2">
<div class="h5 mb-0 flex-1">${value.product_name_en}</div>
<div class="h5 mb-0">${value.pivot.qty} DB</div>
</div>
</div>
</div>
<div class="pos-task-product-action">
Complete
Cancel
</div>
</div>
</div>
</div>
`;
});
OrderView += `<div class="pos-task">
<div class="pos-task-info">
<div class="h3 mb-1" id=""><td>Üzenet: ${value.notes}</td></div>
<div><div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div></div>
<br>
<!-- You can safely remove this if not needed
<div class="mb-3">${value.product_id}</div>
<div class="h4 mb-8">${value.product_name}</div>
-->
<td> </td>
<div class="mb-2">
<span class="badge bg-success text-black fs-14px">${value.status}</span>
</div>
<div><span class="text">${value.created_at}</span> Beérkezett</div>
</div>
<div class="pos-task-body">
<div class="fs-16px mb-3">
Completed: (1/4)
</div>
${productsList}
</div>
</div>`
});
$('#OrderView').html(OrderView);
}
})
}
OrderView();```
**Im currently trying to use this button inside the HTML ajax**<div><button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button></div>
I tried using processData: false, but it just kills the process and the button is unusable. Please help.
Your problem is that you have many identifiers # with the same name.
id must be unique.
Replace in code
$(document).on('click', 'button#order_update'
to
$(document).on('click', 'button.order_update'
and
<button type="button" class="btn btn-outline-theme rounded-0 w-150px data-status="${value.status}" data-order="${value.status}" id="order_update">Confirm Order</button>
to
<button type="button" class="btn btn-outline-theme rounded-0 w-150px order_update" data-status="${value.status}" data-order="${value.status}">Confirm Order</button>
You still have the problem that you didn't close the class quote after w-150px, I closed it in the formatted code

Selecting element parent with a specific class and removing it [duplicate]

This question already has answers here:
Accessing $(this) after success:function() when using $.ajax
(3 answers)
Closed 5 years ago.
I have an anchor element nested within multiple divs. When I click on it the specific tweet gets deleted from the database using AJAX and I want to visually remove it using jquery but I can't get it to work.
HTML:
<div class="tweet-wrapper w-clearfix" >
<div class="tweet-left-side-wrapper"><img class="tweet-avatar" height="48" src="/images/profiles/{{$tweet->user->profile->image->file}}" width="48">
</div>
<div class="tweet-right-side-wrapper w-clearfix">
<a class="tweet-username" href="{{route('show.profile',$user->profile->url_handle)}}">{{$tweet->user->profile->display_name}}</a>
<a class="tweet-handle" href="{{route('show.profile',$user->profile->url_handle)}}">{{$tweet->user->profile->handle}}</a><span> · </span>
<a class="tweet-date" href="#">{{$tweet->created_at->diffForHumans()}}</a>
#if($tweet->user->profile->url_handle == $user->profile->url_handle)
<div class="tweet-dropdown w-dropdown" data-delay="0">
<div class="tweet-dropdown-toggle w-dropdown-toggle">
<div class="w-icon-dropdown-toggle"></div>
</div>
<nav class="tweet-dropdown-list w-dropdown-list">
<div class="nav-dropdown-link-group">
<a class="nav-dropdown-link w-dropdown-link" href="#">Share via Direct Message</a>
<a class="nav-dropdown-link w-dropdown-link" href="#">Copy link to Tweet</a>
<a class="nav-dropdown-link w-dropdown-link" href="#">Embed Tweet</a>
<a class="nav-dropdown-link w-dropdown-link" href="#">Pin to your profile page</a>
<a class="nav-dropdown-link w-dropdown-link profile-tweet-delete-button" data-tweet-id="{{$tweet->id}}" href="#">Delete tweet</a>
</div>
<div class="nav-dropdown-link-group"><a class="nav-dropdown-link w-dropdown-link" href="#">Add to new Moment</a>
</div>
</nav>
</div>
AJAX:
$('.profile-tweet-delete-button').each(function(){
$(this).on('click',function(){
$.ajax({
type:'post',
url:'{{URL::route('delete-tweet')}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
tweetID : $(this).data('tweet-id')
}
,
success:function(){
successAlert("Tweet deleted!");
$(this).parents('div[class^="tweet-wrapper"]').remove();
},
error: function(){
errorAlert("Failed to delete tweet!");
}
});
});
});
You have to store this outside the success callback like so..
$('.profile-tweet-delete-button').each(function(){
$(this).on('click',function(){
var thisRef = this; // store a ref here
$.ajax({
type:'post',
url:'{{URL::route('delete-tweet')}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data:{
tweetID : $(this).data('tweet-id')
}
,
success:function(){
successAlert("Tweet deleted!");
$(thisRef).parents('div[class^="tweet-wrapper"]').remove();
},
error: function(){
errorAlert("Failed to delete tweet!");
}
});
});
});

knockout carrying the data to Multiple View

Below is my code which is knocokout js,i have ListviewModel which is related to two views 1st and second view as below,Both views using the class name UserDetailsView, i am binding two views 1st and second view as below,my problem is, i have click event on the 1st view "Userview" i need to get data of clicked event which is $root.UserView, when i click this it should get all related value and pass to second view so i can bind the data using knockout js ,i am getting the value but unable to bind the data when i clicked $root.UserView so i used jquery in second view for binding, but Now requirement is changed i need make another click event in second view so i can carry data to another view,before that i need to bind the second view with Knockout js how it can be done need help
function ListviewModel()
{
var self = this;
self.Listarray = ko.observableArray();
self.getUserList = function () {
var ListModel = {
userId: UserID
}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ListModel),
url: serverUrl + 'xxx/xxx/xxx',
success: function (data) {
self.Listarray($.map(data, function (item) {
return new Listdata(item);
}));
}
});
};
//Click Function for UserPersonalview
self.UserView = function (Listarray) {
$("#userId").text(Listarray.userIdId());
$("#userName").text(Listarray.UserName())
document.getElementById('userProfilePic').setAttribute('src', "data:" + Listarray.ProfilePictype() + ";base64," + Listarray.ProfilePicBase64());
window.location.href = "#UserPersonalview";
}
self.UserProfile = function () {
console.log(self.Listarray());
}
}
//Model
function Listdata(data)
{
var self = this;
self.userId = ko.observable(data.userId);
self.userName = ko.observable(data.userName);
self.userProfilePicBase64 = ko.observable(data.userProfilePicBase64);
self.userProfilePictype = ko.observable(data.userProfilePictype);
self.userProfilepic = ko.computed(function () {
return "data:" + self.userProfilePictype() + ";base64," + self.userProfilePicBase64();
});
}
//1st View
<div data-role="view" id="Userview" class="UserDetailsView" data-layout="default">
<div data-role="content" style="background-color:#fff!important">
<div>
<ul style="list-style: none;" data-role="listview" id="hierarchical-listview" data-bind="foreach:Listarray">
<li style="background-color:#FFF" data-bind="click:$root.UserView">
<div style="width:100%;">
<div style="width:50%;float:left">
<span data-bind="text:$data.userId" style="display:none"></span>
<img data-bind="attr: { src:$data.userProfilepic }" onclick="Imagepopover()" />
<label style="width: 25%!important;" class="firendslisttext" data-bind="text:$data.userName"></label>
</div>
<div style="width:50%;float:left;margin: 0px -20px;">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
//second View
<div data-role="view" id="UserPersonalview" >
<header data-role="header">
<div data-role="navbar" class="UserDetailsView">
<div class="content-header ">
<ul style="list-style: none;" >
<li data-bind="click:$root.UserProfile">
<div class="km-leftitem">
</div>
<div class="block2" >
<div class="inner" style="float:left" >
<span id="userId" style="display:none"></span>
<img data-responsive="" width="40" height="40" id="userProfilePic" src="" style="border-radius: 50%;" />
</div>
<div class="inner" style="float:left;margin-left:15px">
<label id="userName" style="width: 100%!important;"></label>
</div>
</div>
<div class="km-rightitem">
<a data-align="right"><img src="images/icon-add.png" style="height:50px" /></a>
</div>
</li>
</ul>
</div>
</div>
</header>
<div data=role="content"><div>
</div>

How to use javascript to trigger a modal one after another

I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};

Why my previous button doesn't contain parameter for the controller ? PagedList MVC

i have a problem when implementing pagedlist mvc in my website project. I used pagedlist mvc to show partial view. When button previous is click, the parameter doesn't complete pass, just the page number that pass and the other is null. This is my controller
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
for previous button it will create link like this
localhost:20208/StoreItem/StoreItemView?Page_No=1
and has different with next button,that create link that contain all parameter
localhost:20208/StoreItem/StoreItemView?jenis=&sorting_key=&Page_No=2
why it's different call for previous and next button ?
i create the pager like this in cshtml
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
and i use javascript too for load partial view , my javascript is
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
I stuck in this problem almost 2 days. I hope the people who are here can help me. Thank you before :)
----EDIT------
#model PagedList.IPagedList<MVC_EDOLPUZ.Models.StoreItemModel>
#using System.Globalization
#using PagedList.Mvc
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<h3><span class="label label-primary">DOLANAN PUZZLE ITEM</span></h3>
<select id="Sorting_Order" name="Sorting" onchange="reloadPartialDDL()">
<option value="0">-Urutkan Berdasarkan-</option>
<option value="nama">Nama</option>
<option value="rendah">Harga Terendah</option>
<option value="tinggi">Harga Tertinggi</option>
</select>
<div id="products" class="row list-group">
#foreach (var item in Model)
{
<div class="item col-xs-5 col-lg-3">
<div class="thumbnail">
<img class="group list-group-image img-responsive" src="#Url.Content(#item.gambar_barang)" alt="" />
<div class="caption">
<h4 class="group inner list-group-item-heading">
#item.nama_barang
</h4>
<p class="group inner list-group-item-text">
<span class="label label-warning">#item.deksripsi_barang</span>
</p>
<div class="row">
<div class="col-xs-1 col-md-6">
<input id="#item.nama_barang" type="number" class="rating" min="1" max="5" step="0.5" data-size="xs" value="#item.rating_barang">
</div>
<script>
$('##item.nama_barang').rating('refresh', { disabled: true, showClear: false, showCaption: false });
</script>
</div>
<div class="row">
<div class="col-lg-5 col-xs-4">
<p class="lead" style="font-weight: bolder; color: red;">
#string.Format(new CultureInfo("id-ID"), "{0:C}", #item.harga_barang)
</p>
</div>
<div class="col-lg-1 col-xs-2">
<a class="btn btn-success btn-responsive btn-xs" onclick="addItemToCart('#item.id_barang')" href="#">Add to cart</a>
</div>
</div>
</div>
</div>
</div>
}
</div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#*#Html.PagedListPager(Model, page => Url.Action("Index",
new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))*#
<div id="myPager">
#Html.PagedListPager(
Model,
page => Url.Action(
"StoreItemView",
new
{
jenis = ViewBag.jenis,
sorting_key = ViewBag.sorting_key,
Page_No = page
}
),
PagedListRenderOptions.PageNumbersOnly
)
</div>
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});
</script>
that's my code for the view, and this controller that handle it's view
[HttpGet]
public ActionResult StoreItemView(string jenis, string sorting_key, int? Page_No)
{
ViewBag.jenis = jenis;
ViewBag.sorting_key = sorting_key;
List<StoreItemModel> products = StoreItemRepository.getItemList(jenis, sorting_key);
foreach (var items in products)
{
items.rating_barang = StoreItemRepository.getRatingBarang(items.id_barang);
}
int Size_Of_Page = 4;
int No_Of_Page = (Page_No ?? 1);
PagedList.PagedList<StoreItemModel> show = new PagedList.PagedList<StoreItemModel>(products, No_Of_Page, Size_Of_Page);
return PartialView("_StoreItem", show);
}
Please use like below
<div id="myPager" location="Url.Action("StoreItemView", new {jenis = ViewBag.jenis, sorting_key = ViewBag.sorting_key, Page_No = page})">
#Html.PagedListPager(
Model,
page => Url.Action("StoreItemView"),
PagedListRenderOptions.PageNumbersOnly
)
and javascript must be like
Before using the please check ViewBag.sorting_key and ViewBag.jenis is holding any value using alert in javascript. and I am not qable to see any tag with id="container_item_store". Make sure the container_item_store id must be place in some where in your view.
<script>
$(function () {
$('#myPager').on('click', 'a', function () {
var location = $(this).attr('location');
$.ajax({
url: location,
type: 'GET',
cache: false,
success: function (result) {
$('#container_item_store').html(result);
alert("sukses");
},
error: alert("bangsat")
});
return false;
});
});

Categories