How to insert data in child div? - javascript

i met a problem when tried to put some data in my block. I have div structure like this:
<div class="1">
<div class="2">
<div class="3">
<div class="4"></div>
</div>
<div class="5"></div>
</div>
</div>
<div class="1">
<div class="2">
<div class="3">
<div class="4"></div>
</div>
<div class="5"></div>
</div>
</div>
...
and i need to place some data only in<div class="4"></div>
when i use this JS:
function sendDataChild(btn) {
var form = $(btn).closest('FORM[name=answer-form]');
var data = form.serialize();
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: data,
cache: false,
success: function (data) {
form[0].reset();
$("div.4").html(data.error_name);
},
error: function (xhr, str) {
alert('Возникла ошибка: ' + xhr.responseCode);
}
});
return false;
};
it puts data in all div's with class = "4"
I tried to find parent, but it just put data in parent:
$("div.4").parent().html(data.error_name);
Can U advise how to make it right?
P.S
I used numbers just for example.)

As long as your button is under one div.1 you can replace your
$("div.4").html(data.error_name);
with
$(btn).closest("div.1").find("div.4").html(data.error_name);
Edit: Like the comments say you should not start your class names with numbers, but I hope this are just placeholders.

I suggest you identify your div by id and use the append method.

Related

Why does my view function render data but it won't show up in the browser? (AJAX/Django)

I have finally achieved that my Javascript on 'click' function and AJAX work handy in collaboration with my view function that calls data from an API. But now I have one more issue:
The data from the API is forwarded smoothly to the html containers that contain the according variables. But in my browser I don't see the content being displayed?!
Why is that?
I don't have a success function set up in AJAX so far, since I understood that the view function renders the frontend so there is no need for AJAX success function in that case?
In advance thank you so much for your inputs.
View
import requests
from django.shortcuts import render
import json
def team_update(request):
team_id = request.GET.get('team')
response = requests.get(f'http://www.api-football.com/demo/api/v2/teams/team/{team_id}')
team_data = response.json()
teams = team_data.get('api', {}).get('teams', [])
if teams and len(teams) == 1:
teams = teams[0]
return render(request, 'index.html', {
'name': teams['name'],
'country': teams['country'],
'founded': teams['founded'],
'logo': teams['logo'],
'venue_capacity': teams['venue_capacity'],
})
Javascript/Ajax:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id},
success: function(response) {
console.log(response)
}
});
});
HTML (the key part):
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="{% static "images/club_flags/Clubs/Germany/FC Bayern München.png" %}" alt="Manchester United">
</div>
<div class="selectedClub">{{ name }}</div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded">{{ founded }}</p>
</div>
Debug:
You need to utilise the response data from within your success function, rather than simply logging it. I'll make some assumptions about your page, say for example you currently have the following
<body>
<!-- all your other stuff on the page -->
<div id="container-element">
<div class="topRow">
<div class="team">
<div class="teamLogo">
<img class="teamLogo" src="" alt="">
</div>
<div class="selectedClub"></div>
</div>
</div>
<!---End of Top Row and Start of Second row--->
<div class="secondRow">
<div class="column">
<p class="heading">Founded in</p>
<p class="figure" id="founded"></p>
</div>
</div>
</body>
If that was how your page is currently set up, then in your success function of your AJAX call, you could do this:
$.ajax({
method: "GET",
url: "/dashboard/",
data: {'team': team_id },
success: function(response) {
$('container-element').html(response);
}
});
Which will replace the content inside your actual page.

Scrape a page with Javascript and then append a specific section to current page

I'm trying to scrape and then pull out a specific section (section-two) to append to my current page.
Current page
<div id="container">
</div>
<script type="text/javascript">
$.ajax({
url: "external.html",
dataType: 'text',
success: function(data) {
var externalPage = data;
$("#container").append(externalPage);
}
});
</script>
external.html
<div class="section-one">
<p>Content I don't want</p>
</div>
<div class="section-two">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
Ideal Result
<div id="container">
<div class="section-two">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
</ul>
</div>
</div>
So far I have loaded the external page into a variable but I do not know how to filter out only the section I want to append. Can anyone help me out? Thanks in advance.
To only append .section-two, you'll need this:
$.ajax({
url: "external.html",
dataType: 'text',
success: function(data) {
var externalPage = $($.parseHTML($.trim(data)));
$("#container").append(externalPage.find('.section-two'));
}
});
$.trim() (optional) will remove any newlines and spaces at the beginning and end that might be in external.html. $.parseHTML() will convert the HTML string to a set of DOM nodes (so that we can traverse it). The surrounding $ will convert the DOM nodes to a jQuery object so that we can use .find() method to filter out the descendant that we want.
Try this
$.ajax({
url:"template.html",
dataType:'text',
success:function(data){
var parsedHTML=$.parseHTML($.trim(data));
var arr= jQuery.grep(parsedHTML, function( node, index ) {
if($(node).attr('class')=="section-two"){
return node;
}
});
$("#container").append(arr[0]);
}
});

How to maintain the DOM position when elements are faded out and faded in

I am trying to hide a category list on click of a particular category and load the respective contents. The loading, fading in and fading out works fine but the problem is that whenever I fade Out the div the page scroll position goes to the element before the hidden div and whenever new elements are faded in the scroll position remains in the position of the last element. What to do so that the scroll position remains the same and a text or gif can be shown so that the user can see that some work is going on before the new elements are faded in?
HERE IS MY paste.
HTML
<div id="main_container">
<div id="coupon">
<div id="left_content">
<div id="coupon_heading">COUPON ★★★ </div>
<div id="coupon_text">USE <strong><i>NEW20</i></strong> TO GET AN ADDITIONAL 20% OFF</div>
</div>
<div id="right_content">
<div id="exclamation">OPENING<br>SALE</div>
</div>
</div>
<div id="content">
<div id="category1" class="category" data-categories="SPL">
<img src="images/c_w.png"><div class="category_description">Chef's Special</div>
</div>
<div id="category2" class="category" data-categories="LCH">
<img src="images/l_w.png"><div class="category_description">Lunch</div>
</div>
<div id="category3" class="category" data-categories="SNK">
<img src="images/s_w.png"><div class="category_description">Snacks</div>
</div>
<div id="category4" class="category" data-categories="DNR">
<img src="images/d_w.png"><div class="category_description">Dinner</div>
</div>
<ul class="items">
<!-- Menu List -->
</ul>
</div>
</div>
JS
<script type="text/javascript">
$(document).ready(function(){
$('body').on('click', '.category', function(){
var category = $(this).data('categories');
//alert(category);
$('.category').fadeOut(300);
$.ajax({
type: "POST",
url: "./assets/listproducts.php",
data: {cat: category},
cache: false,
success: function(response){
//console.log(response);
$('#nav').html('Back').addClass('back');
$('.items').html(response).delay(400).fadeIn(300);
}
});
});
$('#action_bar').on('click', '.back', function(e){
e.preventDefault();
//alert('click');
$('.items').fadeOut(300);
$('.category').delay(400).fadeIn(300);
$('#nav').html('CATEGORIES').removeClass();
});
});
</script>
UPDATE
I tried using a callback in fadeOut but didn't work.
success: function(response){
//console.log(response);
$('.category').fadeOut(300, function(){
$('#nav').html('Back').addClass('back');
$('.items').html(response).delay(400).fadeIn(300);
});
}
It seems that the following works just the way I want. If there is something really wrong in the code I wrote, please correct me.
$(document).ready(function(){
$('body').on('click', '.category', function(){
var category = $(this).data('categories');
//alert(category);
$.when($('.category').fadeOut(500)).done(function(){
//Try showing a loader
});
$.ajax({
type: "POST",
url: "./assets/listproducts.php",
data: {cat: category},
cache: false,
success: function(response){
//console.log(response);
$('#nav').html('Back').addClass('back');
$('#content').append($('<ul class="items">').append(response)).delay(400).fadeIn(500);
}
});
});
$('#action_bar').on('click', '.back', function(e){
e.preventDefault();
$.when($('.items').fadeOut(500)).done(function(){
$('.items').remove();
$('#nav').html('CATEGORIES').removeClass();
$('#content').append($('.category').css('display','block')).delay(400).fadeIn(300);
});
});
});
</script>

How to remove and display this elements when ajax success?

How to remove and display this elements when ajax success ?
i want to remove this elements when success
<a class="hyper" id="1234567890">
<div class="mine">
<img src="moo.png"/>
</div>
</a>
and display this elements when success
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
and this is my ajax post code
$('body').on('click','.hyper',function() {
var my_id = $(this).attr('id');
var postData = 'mydata='+my_id+'&time=now';
$.ajax({
type: "POST",
url: "my_post.php",
data: postData,
cache: false,
success: function()
{
}
});
})
When i use follow Zentoaku
$('#1234567890').removeClass('hyper').addClass('success').html('<div class="sura"><img src="naa.png"/></div>');
after success my element display
<a class="hyper" id="1234567890">
<div class="mine">
<img src="moo.png"/>
</div>
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
</a>
but after success i want to see this
<a class="success" id="1234567890">
<div class="sura">
<img src="naa.png"/>
</div>
</a>
how can i do ?
To Hide you can use following:
success: function()
{
$('.hyper').hide();
}
You can also use remove() method to completely remove the elements from DOM.
To show use this:
success: function()
{
$('.success').show();
}
You can use Id as well as your selector, if you use different ids for both the elements.
NOTE: This solution will be applicable when you have your html code already exists on your page which you have shown in your question.
jQuery has a toggle function, with which you can toggle the visibility of an item.
http://api.jquery.com/toggle/
Your code then could look like this:
$('body').on('click','.hyper',function() {
var my_id = $(this).attr('id');
var postData = 'mydata='+my_id+'&time=now';
$.ajax({
type: "POST",
url: "my_post.php",
data: postData,
cache: false,
success: function(my_id)
{
$('#'+my_id+'.hyper').toggle();
$('#'+my_id+'.success').toggle();
}
});
})
$('#1234567890').removeClass('hyper').addClass('success');
$('#1234567890 > div').removeClass('mine').addClass('sura');
$('#1234567890 > div > img').attr('src', 'naa.png')
OR
$('#1234567890').removeClass('hyper').addClass('success').html('<div class="sura"><img src="naa.png"/></div>');

Read XML File with JQuery and Write XML Attributes to Series of HTML Elements on a Webpage

I have an image slider on a page that reads an XML file called "slider.xml" that kinda looks like this:
<slider>
<slide>
<link>http://www.example.com/1</link>
<path>http://image.jpg</path>
</slide>
</slider>
There's multiple "slide" elements but I didn't include them for space reasons. I have some HTML that looks like this:
<body>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
<div class="slide"></div>
</body>
I want to read this XML file and write the "link" attribute to the "div" elements on an HTML page as a title attribute. I want it to look like this:
<body>
<div class="slide" title="http://www.example.com/1"></div>
<div class="slide" title="http://www.example.com/2"></div>
<div class="slide" title="http://www.example.com/3"></div>
<div class="slide" title="http://www.example.com/4"></div>
<div class="slide" title="http://www.example.com/5"></div>
</body>
So far I have tried this but haven't had any luck:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "slider.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('slide').each(function(){
var url = $(this).find('link').text();
$('.slide').attr('title', url);
});
}
});
});
I don't have issues reading the XML file, but run into problems after I parse the XML attributes and attach it to the various divs. Should I create a loop and store the xml attributes in an array? Is there a better way to do this?
Also, I cannot edit the XML or HTML.
All your divs will have the same title since you call $('.slide') which select them all.
This should work:
$(document).ready(function () {
var slide = $('.slide');
$.ajax({
type: "GET",
url: "slider.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('slide').each(function(i){
var url = $(this).find('link').text();
slide.eq(i).attr('title', url);
});
}
});
});

Categories