JQUERY/AJAX-multiply classes based on content number - javascript

I'm trying to extract specific data and send them to the client side so in order to achieve that I used AJAX like below :
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`) // event1 is the id of field name
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} |
${data[i].events.targetAmPM} </b>`)// time1is the id of field time and date
$("#comment1").html(`<b>${data[i].events.caption}</b>`) // comment1 is the id of field description
$("#location1").html(`<b>${data[i].events.location}</b>`) // location1 is the id of field location
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
and this is the output
this script works perfectly and fill one container with the requested values but what I'm looking for is to fill every container and multiply them based on data found from my db
which mean :
1- if there is more than one data data[i].events.eventName or other another container must be created and get filled by the new value
the HTML code is below :
<div class="card">
<div class="card-header" id="headingOne-1">
<script type ="text/Javascript">
$(document).ready(() => {
$.ajax({
type: 'GET',
dataType : 'json',
url: '/envoi/events/',
})
.done(function(data) {
for(let i =0; i< data.length;i++) {
console.log(data[i].events.eventName);
$("#event1").html(`<b>${data[i].events.eventName}</b>`)
$("#time1").html(`<b>${data[i].events.eventDate} - ${data[i].events.targetReminder} | ${data[i].events.targetAmPM} </b>`)
$("#comment1").html(`<b>${data[i].events.caption}</b>`)
$("#location1").html(`<b>${data[i].events.location}</b>`)
}
})
.fail(function(xhr, status, error) {
console.log(error);
})
.always(function(data){
});
})
</script>
<div class="event-time">
<time id="time1" datetime="2004-07-24T18:18">9:00am</time>
<div class="more"><svg class="olymp-three-dots-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-three-dots-icon"></use></svg>
<ul class="more-dropdown">
<li>
Mark as Completed
</li>
<li>
Delete Event
</li>
</ul>
</div>
</div>
<h5 class="mb-0 title">
<a href="#" data-toggle="collapse" data-target="#collapseOne-1" aria-expanded="true" aria-controls="collapseOne" id = "event1">
Breakfast at the Agency
<i class="fa fa-angle-down" aria-hidden="true"></i>
<span class="event-status-icon" data-toggle="modal" data-target="#public-event">
<svg class="olymp-calendar-icon" data-toggle="tooltip" data-placement="top" data-original-title="UNCOMPLETED"><use xlink:href="svg-icons/sprites/icons.svg#olymp-calendar-icon"></use></svg>
</span>
</a>
</h5>
</div>
<div id="#collapseOne-1" class="collapse show" aria-labelledby="headingOne" data-parent="#headingOne-1">
<div class="card-body" id ="comment1">
Hi Guys! I propose to go a litle earlier at the agency to have breakfast and talk a little more about the new design project we have been working on. Cheers!
</div>
<div class="place inline-items">
<svg class="olymp-add-a-place-icon"><use xlink:href="svg-icons/sprites/icons.svg#olymp-add-a-place-icon"></use></svg>
<span id ="location1">Daydreamz Agency</span>
</div>
</div>
</div>
Any idea how to multiply that box based on data found with the script mentioned above ?
Hope I mentioned everything :-D ?
Best Regards,

Every time your loop works, $("#event1").html(....), $("#-----").html(....) will be replaced with your new values. So why don't you rather create a variable name html outside a loop and every div section or html tags that needs to be rendered in DOM, inside the loop and append after the div you want to render. Like mentioned on above answer,
var html="";
for(let i =0; i< data.length;i++){
html += `<div class="card-header"> ${data[i].event.eventName} </div>` +
`<div class=" -----"> $${data[i].event.eventDate} ` +
------------------and so on---------------------------;
}
$("#NAME OF ID BEHIND YOU WANT TO SHOW YOUR NEW DIV").append(html);
Hope it will work :)

I believe you should just create the whole HTML in javascript then append that HTML to DOM. for example.
let html = "";
for(let i =0; i< data.length;i++) {
html += "<p>"+ data[i].events.eventName + "</p>";
html += "<p>"+ data[i].events.eventDate + "</p>";
}
$("#ParentDivIDWhereToAppendThisContent").html(html);
The above code is just an example of how you can do it. You need to customize it to suit your needs.

Related

Issue on getting id from Selected HTML elements from Ajax GET response with jQuery

I am using ajax to display product data and then delete on click a specific on using the product id but am not able to get the product id as it is showing undefine can you guys suggest something.
In this code first I am getting the product details for the cart dropdown menu and then displaying it in list format with delete button through the first ajax and then on clicking delete should delete the element in the second ajax using the elements product id which I have saved inside data-r but on console, it showing undefined can anyone tell me what is the issue. As I know that the elements are created dynamically but I am not getting a solution
function TopCartVal() {
// Used Route inside the ajax
var url = "{{ route('pdt.details', ':id') }}";
var yui = "{{ route('delete_fr.cart', ':id') }}";
// Ajax Structure
$.getJSON( "{{ route('my.cart','json') }}", function( data ) {
console.log(data);
var Cart = $('#cart_dp_sec_pdt_desc');
// Loop for data
$.each(data, function(key , value) {
console.log(value);
url = url.replace(':id', value.product_id);
yui = yui.replace(':id', value.product_id);
Cart.append(`
<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="`+url+`">
<img src="{{ asset('')}}`+value.image+`" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
`+value.product_name+`
</h3>
<div class="price">`+value.currency+value.product_price+`</div>
</div>
<div class="col-xs-1 action">
<a href="#"
data-r"`+value.id+`"
class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>
`);
});
});
}
// delete part
$(document).on('click', '.cart_dp_btn_ctn_delete', function(e){
e.preventDefault();
var id = $(this).attr('data-r'); // id of to be deleted element
var yui = "{{ route('delete_fr.cart', ':id') }}";
yui = yui.replace(':id', id);
console.log(yui);
console.log(id); // it is showing undefined`enter code here`
// $.getJSON( yui, function(data){
// TopCartVal();
// });
});
You are missing an = here:
data-r"`+value.product_id+`"
But using template literals correctly will make it easier to see
`<div class="row">
<div class="col-xs-4">
<div class="image">
<a href="${url">
<img src="{{ asset('')}}${value.image}" alt=""/>
</a>
</div>
</div>
<div class="col-xs-7">
<h3 class="name">
${value.product_name}
</h3>
<div class="price">${value.currency+value.product_price}</div>
</div>
<div class="col-xs-1 action">
<a href="#" data-r="${value.product_id}" class="cart_dp_btn_ctn_delete">
<i class="fa fa-trash"></i>
</a>
</div>
</div>`

Validate if 2 elements have same attribute value

In my e-commerce environment, I need a jQuery validation between 2 product attributes. Simplified it needs to check if the cart has a product which is present on the same page:
<! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
<li class="woocommerce-mini-cart-item mini_cart_item">
<a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6735" data-cart_item_key="..." ></a>
</li>
</ul>
<! –– Product ––>
<article class="post-6735 product" data-id="6735">
<div class="product_wrapper">
<a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
</div>
</article>
I would like to be able to check if the attribute and its value from data-product_id within the cart is the exact same as in article a.button element. My approach:
jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id').each( function() {
if( jQuery('article a.button')/*check if it is the same*/){
// do something here
}
});
As you can see the ID number 6735 is in more attributes. So perhaps a different way is also possible?
To get current_ProductId, You just need to get from $('article').data('id')
To loop through all mini cart items, You just need mini_cart_item
As you can see, we can get data attribute value by using data
var current_ProductId = $('article').data('id');
$('.mini_cart_item').each(function() {
var productId_MiniCartItem = $(this).find('a').data('product_id');
if(productId_MiniCartItem == current_ProductId){
// do something here
console.log("ProductId: " + productId_MiniCartItem + " has been ordered");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<! –– Cart ––>
<ul class="woocommerce-mini-cart cart_list product_list_widget ">
<li class="woocommerce-mini-cart-item mini_cart_item">
<a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6735" data-cart_item_key="..." >6735</a>
</li>
<li class="woocommerce-mini-cart-item mini_cart_item">
<a href="/example-product/" class="remove remove_from_cart_button" data-product_id="6736" data-cart_item_key="..." >6736</a>
</li>
</ul>
<! –– Product ––>
<article class="post-6735 product" data-id="6735">
<div class="product_wrapper">
<a href="?add-to-cart=6735" data-quantity="1" class="button add_to_cart_button" data-product_id="6735"</a>
</div>
</article>
If you only need help to clarify your solution it would be
$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
if( $('article a.button').data('product_id') == $(this).data('product_id'){
// do something here
}
});
each iterate through collection of jquery elements.
This
jQuery('.woocommerce-mini-cart .remove_from_cart_button').attr('data-product_id')
is the single value, it would take the first element that finds and then executes attr on it.
UPDATE
To update all products button on site based on all products that are inside the card
var product_id = "";
var article = ".post-"; // class of article
$('.woocommerce-mini-cart .remove_from_cart_button').each( function() {
product_id = $(this).data('product_id')
article = article + product_id; // we add strings here, example .post-6225
$(article + " .product_wrapper a").attr('disabled', 'disabled');
});

accessing jquery form and the parent of the a tag

With the following jQuery code.
$('#trade-offer form').on("submit", function(event) {
event.preventDefault();
var stock = $(this).closest('.allloopedover');
console.log(stock);
return;
$.ajax({
url: ajaxurl,
type: "POST",
dataType: 'json',
context: this,
data: $(this).serialize() + '&action=offer',
beforeSend: function() {
$('.alert-modal').remove();
$(this).closest('form').find('input').removeClass('form-error');
$(this).closest('form').find('.stm-ajax-loader').addClass('loading');
},
success: function(data) {
$(this).closest('form').find('.stm-ajax-loader').removeClass('loading');
$(this).closest('form').find('.modal-body').append('<div class="alert-modal alert alert-' + data.status + ' text-left">' + data.response + '</div>')
for (var key in data.errors) {
$('#request-trade-offer-form input[name="' + key + '"]').addClass('form-error');
}
}
});
$(this).closest('form').find('.form-error').live('hover', function() {
$(this).removeClass('form-error');
});
});
And the HTML code.
<div id="2012 FORD SUPER DUTY F-250 XLT" data-item="B01606" class="allloopedover listing-list-loop stm-listing-directory-list-loop stm-isotope-listing-item">
<div class="image">
<!--Video-->
<a href="http://x.com/listings/2012-ford-super-duty-f-250-xlt-2/" class="rmv_txt_drctn">
<div class="image-inner">
<!--Badge-->
<img width="300" height="225" src="http://x.com/blog/wp-content/uploads/2017/12/31-6-300x225.jpg" class="img-responsive wp-post-image" alt="" srcset="http://x.com/blog/wp-content/uploads/2017/12/31-6-300x225.jpg 300w, http://x.com/blog/wp-content/uploads/2017/12/31-6.jpg 640w" sizes="(max-width: 300px) 100vw, 300px"/>
</div>
</a>
</div>
<div class="content">
<div class="meta-top">
<!--Price-->
<div class="price offerc">
<div class="normal-price">
<span class="heading-font offercode">
<a class="rmv_txt_drctn" href="#trade-offer" data-toggle="modal" data-itemname="2012 FORD SUPER DUTY F-250 XLT" data-target="#trade-offer">Offer</a>
</span>
</div>
</div>
<!--Title-->
<div class="title heading-font mmbot">
<a href="http://x.com/listings/2012-ford-super-duty-f-250-xlt-2/" class="rmv_txt_drctn">
2012 FORD SUPER DUTY F-250 XLT
</a>
</div>
</div>
</div>
Now the div code it is not complete as it did not copied the whole code which is too big but it runs inside a loop and creates all the settings differently, notice the first div which have the
id="2012 FORD SUPER DUTY F-250 XLT" data-item="B01606"
and class as allloopedover.
now with jQuery, I want that when I click the submit button of a popup it should pass the id and data-item of that div, I tried using closest but that does not seems to be working, any idea?
When you attach a submit event handler to a form, the this inside your handler function will be the form itself, and not the button that you pressed to submit the form (which could be some div inside the form).
Therefore, $(this).closestwill traverse the parents of the form. If the div.allloopedover is inside the form that is being submitted, closest is not going to find it. If the div you're looking for is inside the form, you can get access to it with $(this).find(".alloopedover"). You should then be able to get the id and data-item value of that div from the jQuery object yielded by find.

show records on same details page by clicking next button in asp.net mvc getting error

I want to display the records on details page when user click on next button then he should be able to display the next record of table. Suppose user select the details of a particular record id 1 he get the details of that id 1 at the same time on the same page by clicking the next button user should be able to get the record of id 2 and vice versa. I have done it but getting some error when table has no such id named id 3 after id 1 and id 2 its showing me the error. Please help me to find out where i am wrong.
View
#model WebApp.ViewModels.ViewTeamList
<script type="text/javascript">
var dataid = '#Html.Raw(Json.Encode(Model.TeamDetails.TeamId))';
for( var item in dataid)
console.log(dataid[item]);}();
</script>
<script type="text/javascript">
$("#btnNext").click(function () {
var $buttonClicked = $(this);
var nid = $buttonClicked.attr('data-id');
console.log(nid);
$.ajax({
url: 'Team/Next',
data: { dataid: nid },
//data: JSON.stringify(data.TeamId),
success: function (response) {
divDetail.html(data);
}
});
});
</script>
<div class="row">
<div class="col-md-11 col-sm-11 pull-left" style=" font-size:large; font-weight:600">
#Model.TeamDetails.TeamName
</div>
#* <div class="col-md-1 col-sm-1 pull-right">*#
<div class="navi-but">
<a href="#" id="btnPrevious" data-id="#Model.TeamDetails.TeamId" class="details">
<span class="previous">Previous</span>
</a>
<a href="#" class="details" data-id="#Model.TeamDetails.TeamId" id="btnNext">
<span style="padding-right:7px">Next</span><span class="next"></span>
</a>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="~/Images/settings.png" />
</a>
<ul class="dropdown-menu" role="menu">
<li>Edit</li>
</ul>
</li>
</div>
#* </div>*#
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblTeam","CT Team Name:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.TeamName
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblDescription","Description:")
</div>
<div class="col-md-8 col-sm-8">
#Model.TeamDetails.Description
</div>
</div>
<div class="row">
<div class="col-md-4 col-sm-4">
#Html.CustomLabel("lblCTUserCount","User Count")
</div>
<div class="col-md-8 col-sm-8 pull-left">
#Model.TeamDetails.UserCount
</div>
</div>
Controller
public ActionResult Next(int dataid)
{
dataid++;
ViewTeamList viewTeamList = new ViewTeamList();
viewTeamList.ViewTeamDetails(dataid);
return PartialView("_ViewTeamDetails", viewTeamList);
}
View model
public class ViewTeamList
{
public TeamDetails TeamDetails;
private ITeamService teamService;
public ViewTeamList()
{
}
public void ViewTeamDetails(int Id)
{
teamService = new TeamService(pDbContext);
TeamDetails = teamService.GetTeamDetails(Id);
//return (TeamDetails.First());
}
}
Please help where i am doing wrong.
I didn't look your code in detail but it seems to me that you have a logical problem. Since you are always incrementing id by one ( dataid++; ) that won't work if some record is deleted in the meantime. For example let's say that you have Record1 with id 1, Record2 with id 2 and Record 3 with id 3 and you delete Record2. Now when you are trying to get next record after Record1 you are incrementing id by 1 so you have 2 and there is no record with id 2 in the db anymore.
Instead of dataid++; you should find next id that really exists in db. As I said I didn't read code in detail so there may be more possible problems.
To Display from WebMethod You Should follow these steps:
create
[webmethod]
to retrieve all the data
List items then make a javascript method in client side use:
ajax({ type:'post', url:'exaple.aspx/showMethod', data:{}, datatype:'json', contentType:'application/json; charset=utf-8',
scuccess:function(data) --display from here in table or any other
data ), error:function(){ alert('Error'); } })

hide div depending on ajax response result

I want to hide a div depending on the result of the response from an ajax call to my server. My server is responding with an object {available: yes/no} depending on the domain and username searched for. If the response if yes I want to maintain the div on the available column of my html and hide the corresponding div on the unavailable column and if the response is no hide the div on the available column and maintain the div visible on the unavailable column.
My problem is attaching each response to the corresponding div. How could I do this?
html:
<div id="searchresults">
<div id="available">
<h4><span class="username"></span><span class="positive-result">is available</span> as a username on:</h4>
<div class="facebook"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-facebook-square"></i>Facebook
</div>
<div class="pinterest"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-pinterest"></i>Pinterest
</div>
<div class="twitter"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-twitter"></i>Twitter
</div>
<div class="instagram"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-instagram"></i>Instagram
</div>
<div class="github"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-github"></i>GitHub
</div>
</div> <!--End of #available-->
<div id="unavailable">
<h4><span class="username"></span><span class="negative-result">is not available</span> as a username on:</h4>
<div class="facebook-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-facebook-square"></i>Facebook
</div>
<div class="pinterest-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-pinterest"></i>Pinterest
</div>
<div class="twitter-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-twitter"></i>Twitter
</div>
<div class="instagram-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-instagram"></i>Instagram
</div>
<div class="github-unavailable"> <!--Class to hide and show this div can be toggled with jQuery -->
<i class="fa fa-github"></i>GitHub
</div>
</div> <!--End of #unavailable-->
Javascript using jQuery
$(document).ready(function(){
console.log("Ready!");
var domains=[ ];
domains.push($(".facebook").find("a").text());
domains.push($(".github").find("a").text());
domains.push($(".twitter").find("a").text());
domains.push($(".instagram").find("a").text());
domains.push($(".pinterest").find("a").text());
// console.log(domains);
$("#searchbutton").on('click', function(event){
var username = $("#searchname").val().trim(); // store value from searchbox
console.log(username);
if(username === ""){
event.preventDefault();
}
if(username){
var newhtml = "<p>";
newhtml += username;
newhtml += "</p>";
$(".username").html(newhtml);
$(".username").remove("newhtml");
var domainCheck = function(domainName){
$.ajax({
url: "/"+username,
type: "get",
data: {domainName: domainName, username: username},
success: function(response){
console.log(domainName);
console.log(response.available);
//hide show logic here
var elem = $("#available").find("div"); returns an array of divs for each search result
console.log(elem);
}
});
};
//send ajax request to server for each domain name to check for username availability
var len = domains.length;
for(var i = 0; i<len; i++){
domainCheck(domains[i]);
console.log(domains[i]+'\n');
}
}
});
});
Your response data type looks JSON, not simple text. So, first of all you should pass the correct dataType argumento to ajax call:
$.ajax({
url: "/"+username,
type: "get",
data: {domainName: domainName, username: username},
dataType: "json",
[...]
then you can easily access the data inside your success() method as follows:
success: function(response){
if(response.available === "yes") {
//show?
} else if(response.available === "no") {
//hide?
} else {
//wtf?
}
}
You can probably adapt this:
on document load -> condition -> show or hide. You would only need to edit 'if ($("#maincontent").width() < 600){'
'$( document ).ready(function() {
if ($("#maincontent").width() < 600){
$( "#toolbarright").hide();
} else { $("#toolbarright").show();}
});'
http://jsfiddle.net/ablueman/vdgeLsgL/

Categories

Resources