hide div depending on ajax response result - javascript

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/

Related

JQUERY/AJAX-multiply classes based on content number

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.

Retrieve newly updated article without refreshing the page

I'd like to make a edit link to update the article when it's clicked,
In the template, it's structured as:
post-text
article-content
article-form
post-menu
I hide "article-form" in first place as <div class="article-form" style="display: none;"> until edit link is clicked.
<div class = "col-md-12 post-text" >
<div class="article-content">
{{article.content}}
</div>
<div class="article-form" style="display: none;">
<form class="form-horizontal" action="/article/edit/{{ b.id }}" method="POST">
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control" id="editContent" name="content" rows="10" cols="30">
{{form.content.value}}
</textarea >
</div>
</div>
<div class="form-group" >
<div class="col-sm-offset-0 col-sm-12">
<button type = "submit" class = "btn btn-success btn-sm" id = "saveEditBtn"> Save Edits </button>
</div>
</div>
</form>
</div><!-- article-form -->
</div>
<div class="post-menu pull-left">
<a id="editArticleLink" href="{% url 'article:article_edit' article.id %}">
<span class="glyphicon glyphicon-edit" aria-hidden="true">edit </span>
</a>
<a id="delArticleLink">
<span class="glyphicon glyphicon-trash" aria-hidden="true">delete</span>
</a>
</div>
After updating is completed and submit is cliked, send data to backend using Ajax, hide "article-form" and show "article-content".
<script>
$(document).ready(
$(".post-menu a").on("click", function(e){
e.preventDefault();
//retrieve the topmost element which the target lives in
$postText = $(e.target).closest(".post-text");
//hide article-content
$postText.find(".article-content").hide();
//show the article-form for users to update
$postText.find(".article-form").show();
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:,
success: function(){
//if saved successfully
$postText.find(".article-content").show();
$postText.find(".article-form").hide();
},//success
})//ajax post request
});//nested button click event
}) //click event
)//ready
</script>
My problem is that in ajax success,
$postText.find(".article-content").show() still display the non-updated article,
How could I retrieve the updated without refreshing the page?
If you can send the edited version to server... You have the new content! Update the .article-content with it then show.
Here is what I think it is...
//capture the button submitting event
$(".article-form button").on("click", function(e){
var content = $postText.find("textarea").val();
$.ajax({
type:"POST",
url: ,
data:, // <-- There is something missing here... I assume it's content.
success: function(){
//if saved successfully
$postText.find(".article-content").html(content).show(); // update before the show!
$postText.find(".article-form").hide();
},//success
})//ajax post request
});

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.

Updating Model with JavaScript/Jquery

I have a strongly typed model to my view. In my view I also have a foreach loop that itirates thru the content and renders an accordion with conent. i also have a search box that has a keyup event that fires when you type in it. The event fetches new data with a ajax call. All of this works fine. Now to the problem. Is there a way of updating the Model with JavaScript/Jquery with the new values from the ajax call. This is ASP.NET MVC 5 I am working in.
This is my code.
View
#model List<CMP_FastaSamarbeten_ProjektWeb.Models.SubSiteViewModel>
#{
foreach (var item in Model)
{
<div class="accordion">
<a href="#">
<h4>#item.Title</h4>
<h4 class="status">#Resource.AccordionStatus</h4>
<i class="fa fa-chevron-right rotate"></i>
</a>
</div>
<div class="accordion-desc">
<h3>#Resource.AccordionProjectLead</h3>
<h4>Kay Wiberg</h4>
<h3>#Resource.AccordionDescription</h3>
<p>
#item.Description
<p>
<div class="link">
#Resource.AccordionGoTo
</div>
</div>
}
}
<script>
window.globalModel = [];
</script>
ajax call and keyup event
$("#searcheBar").on("keyup", function () {
var input = this.value;
$.ajax({
url: '/Home/SendSearchInput',
type: 'POST',
data: {input: input},
dataType: "json",
error: function (xhr) {
console.log(xhr.statusMessage);
},
success: function (data) {
for (var i = 0; i < data.length; i++) {
console.log(data[i]["Title"]);
}
window.globalModel = data;
}
});//Ajax call
});//OnKey up
Thanks for all the help!

jQuery modal not show name after close and open

I create my custom modal window where i show image and that image contain comments and owner name. When i click on some image modal is opened and show big image, author name, comments etc... Problem is when i close current modal and opent it again name does not exist. But first time when i open modal name is there but only when i close that window and opent it again name does not exist. Check screenshots.
I try to debug it with firebook console and GET response return real name but that name is not rendered after closing and opening.
To prview image i use this code:
preview: function() {
$('body').on('click', '#open-picture-modal', function (e) {
e.preventDefault();
$("#photo_preview").show();
var $this = $(this);
var guid = $this.data('guid');
var photo_id = $this.data('id');
$.ajax({
method: 'post',
dataType: 'json',
url: baseurl + '/photo/preview',
data: {'photo_id': photo_id},
success: function(data) {
Photo.photo_author_meta(photo_id);
$(".pleft").html('<img class="fileUnitSpacer" src="'+ $this.data('href')+data['photo_name']+'">');
}
});
//window.history.pushState(null, null, pic_url);
// $(".image-source").attr("src", $this.data('href'));
});
},
// Close image preview modal
close: function() {
$("body").on("click", ".close", function(e) {
e.preventDefault();
$('#photo_preview').hide();
$('#photo_preview .pleft').html('empty');
$('#photo_preview .pright').html('empty');
});
},
// Show photo author meta(name, date created, etc..)
photo_author_meta: function(pid){
$.ajax({
method: "post",
dataType: 'json',
url: baseurl + '/photo/photo_details',
data: {'post_id': pid},
success: function(data) {
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
}
});
},
And here is modal where i append and set html
<div id="photo_preview" style="display:none">
<div class="photo_wrp">
<span class="pull-right close fa fa-times"> </span>
<div style="clear:both"></div>
<div class="pleft"></div>
<div class="pright">
<div class="photo-author-meta">
<div class="media">
<a href="#" class="media-left">
<img alt="64x64" data-src="holder.js/64x64" class="media-object" style="width: 64px; height: 64px;" src="test.png" data-holder-rendered="true">
</a>
<div class="media-body photo-author-name-box">
<div class="photo-author-name">
<h4 class="media-heading photo-author-full-name"></h4>
</div>
<div class="photo-datetime-box">
<div class="photo-date-posted"> Objavljeno: </div>
</div>
</div>
</div>
</div> </div>
<div style="clear:both"></div>
</div>
</div>
Like u can see on first image i have firstname and lastname in modal.
On second image i open again the some modal but name and surname does not exist. But check firebug console, data exist but not rendered.
Your close method is removing the HTML that renders the meta data.
$('#photo_preview .pright').html('empty');
That line is emptying all the HTML within . So, when photo_author_meta() is called a subsequent time after closing, h4.photo-author-full-name no longer exists.
You have various things:
1 - You are messing with .html() and .empty():
$('#photo_preview .pleft').html(); // or .empty()
2 - As you delete all the content from #photo_preview .pright, when you do:
$("h4.photo-author-full-name").html(data['account_firstname'] +' '+ data['account_lastname']);
This element don't exist. You could create it, or not empty all the div content.
You could change this:
$('#photo_preview .pright').html(); // or .empty()
to
$('h4.photo-author-full-name').html(); // or .empty()
In order to no delete the element, only the content on it.

Categories

Resources