div element hides when load() function is called - javascript

I'm working on making ordering by some criterias(e.g. by price, by author) on my jsp page. And using ajax to reload content of div when new sorting option is selected. But when reload function is called, it just hides div on web page. I've checked out, that there are books in session scope needed to be shown and Jquery is included correctly. This is html for choosing criterias to sort by:
<select>
<option id="default">Default</option>
<option id="price">By price</option>
<option id="author">By author</option>
</select>
And here is a code for processing click events for select element:
$(document).ready(function () {
$('select').change(function () {
$( "select option:selected" ).each(function() {
let sortAttr = $('option:selected').attr('id');
$.ajax({
// passing data to servlet
url: 'http://localhost:8080/sort',
type: 'GET',
// sort criteria
data: ({sort: sortAttr}),
// div needed to be reloaded
success: function () {
$('#mydiv').load(' #mydiv');
}
});
})
});
})
And code on jsp page for the div needed to be reloaded:
<div id="mydiv">
<c:forEach var="book" items="${sessionScope.books}">
<div class="col-4"><a href="/home?command=book_details&isbn=${book.ISBN}">
<img src="data:image/jpg;base64,${book.base64Image}">
<h4>${book.title}</h4>
<p>${book.price}$</p>
</a></div>
</c:forEach>
</div>
Any ideas why this happens?
EDIT
Finally, I found out what's happenning. The important thing to notice(especially for me) in .load() function is that whenever we call this function, it actually not just refreshes div content with new data, but makes request to the provided url and on that page(which url we provided) looks for the div selector, gets it's content and then goes back and inserts that content in current div. Notice, that If we don't write url, .load() function will make request to current page (correct me please, If I'm mistaken).
Hope that will help somebody!

First of all, you need to fix the typo in your code. Having space at the beginning of JQuery identifier won't find the required element.
Change this: $('#mydiv').load(' #mydiv');
To this: $('#mydiv').load('#mydiv');
Also, I think you're using it the wrong way.
Check the documentation here

How about
$(function() { // on page load
$('select').on("change", function() { // when the select changes
let sortAttr = $('option:selected', this).map(function() {
return $(this).attr('id')
}).get(); // get an array of selected IDs
if (sortArrr.length > 0) {
$('#mydiv').load('http://localhost:8080/sort?sort=' +
sortAttr.join(',') + // make a comma delimited string
' #mydiv'); // copy myDiv from the result
}
});
})

Related

Updating multiple DIV - tags with a single jQuery script

I have a page that pulls order statuses from a backend system and then shows the status updates on the page. I need to make the page dynamic to load, since now the page takes too long to update at once.
I got my code working so that the HTML page loads up first and then a single status update is loaded on the page.
Components:
index.php -page - basic page w. jQuery code that requests orders_updatestatus.php.
orders_updatestatus.php -page. Pulls info from a backend system and displays info. Receives what order to update via GET.
HTML (index.php - this works)
<div id="updateref"></div>
jQuery: (part of index.php - this works)
<script type="text/javascript">
// Update order status
$(function () {
$.ajax({
url: 'orders_updatestatus.php?reference=100000025',
success: function (data) {
$('#updateref').html(data);
}
});
});
</script>
UPDATED CODE
What I was thinking was that that I need to create a div for every single order so that they could then be updated individually.
$results = $mysqli->query("SELECT reference FROM orders;");
while($row = $results->fetch_assoc()) {
print '<div id="updateref'.$row['reference'].'"></div>';
}
So, with the code above I'll something like this:
<div id="updateref20000"></div>
<div id="updateref20001"></div>
<div id="updateref20002"></div>
<div id="updateref20003"></div>
<div id="updateref20004"></div>
etc..
Everything works great until this point. Now I need your help on building the corresponding jQuery code so that it would update every 'updaterefXX' -div that it sees.
My question is: How to update the following code so that it every updateref -div is updated on the page:
<script type="text/javascript">
// Update order status
$(function () {
$.ajax({
url: 'orders_updatestatus.php?reference=100000025',
success: function (data) {
$('#updateref').html(data);
}
});
});
</script>
Update/clarification: What I need is for the script to pull the orders_updatestatus.php with a GET variable for every div.
Example:
With <div id="updateref1000"> the script requests orders_updatestatus.php?reference=1000 and displays it in <div id="updateref1000"> when ready
With <div id="updateref1001"> the script requests orders_updatestatus.php?reference=1001 and displays it in <div id="updateref1001"> when ready
etc. Thank you!
You can use attribute begins with selector and .each() to iterate all elements having id beginning with "updateref", .replace() to replace portion of id that are not digits to set at query string, set .innerHTML the current element within success callback of $.ajax() call
$("[id^=updateref]").each(function(index, element) {
$.ajax({
url: "orders_updatestatus.php?reference=" + element.id.replace(/\D/g, ""),
success: function(data) {
element.innerHTML = data;
}
});
})

Check if <div> has been asynchronously loaded with data-url

I have a JSP with the following <div>:
<div class="articleInfo" data-url="${article.url}/infoSheet"></div>
If there is any data available for the article, then it will be populated inside the <div> like this:
<div class="articleInfo" data-url="${article.url}/infoSheet">
<div class="data">This is data</div>
</div>
If no data is available then the <div> is left as is.
I tried to do a check with jQuery if the "articleInfo" div has any children, but it doesn't, even if I put the check in the end of $(document).ready(function () {} of the last javascript file loaded. I suppose this is due to how the data is loaded with the data-url attribute of the <div>.
How can I check if any data has been populated?
You can use is() with :empty like
$(function(){
// assuming there is single element having class articleInfo
alert($('.articleInfo').is(':empty'));
});
And if your articleInfo div is filled asynchronously then you need to check its data in your ajax callback like,
$.ajax({
url:....
data:...
success:function(data){
if(!data){
// this div url has no data
}
}
});
OK, i suppose You have no callback for this ajax downloading staff, and this operation not leave any signs of doing ajax like data attributes. If so - no callbacks and signs in DOM then my proposition is to do setInterval and in there check divs has data or not:
var checkedCount=0;
var maxCheckCount=5;//we check 5 times
var checkInterval=setInterval(function(){
var $divs=$('div[data-url]');
$divs.each(function(index){
if ( $(this).find("div.data") ){
//our div has data
}else{
//our div has no data ( maybe will be downloaded? )
}
});
checkedCount++;
if (checkedCount==maxCheckCount)
clearInterval(checkInterval);
},1000); //check every 1 sec
So we check 5 times, one on 1 second ( customise it to Your needs). This is not perfect solution, if ajax will be long, then it will stop working before ajax end.
You can also watch changes in DOM:
$('div[data-url]').bind('DOMSubtreeModified', function(e) {
if ($(this).find("div.data")){
//div has data
}else{
//div has no data but in this situation this never calls
}
});

Jquery: bind several dynamically added elements to an html() event

I have in my page several dropdowns that will be dynamically updated using AJAX, in this way:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response);
}
The dropdowns have names in this format:
<select id="elemento_1" class="dropdowns">
<select id="elemento_2" class="dropdowns">
<select id="elemento_3" class="dropdowns">
The PHP responds with a string response in the form <option value=1>Bla<option value=45>Ble … and it gets appended to the dropdown. You get the idea.
Initially there's only one dropdown, but whenever the user clicks a button, a new dropdown will be added and loaded using the method above, and I want it to have by default the same value than the previous dropdown. After reading this answer about how to trigger html() events:
https://stackoverflow.com/a/3616565/470994
I changed the code above to the following:
$.ajax({
data: parametros,
url: 'getList.php',
type: 'POST',
success: function (response) {
element.html(response).triggerHandler("cambia");
}
$(".dropdowns").unbind().bind("cambia", function() {
var nombre=this.id;
var numero=parseInt(nombre.slice(-1));
alert("Mooooo " + numero);
if (numero > 1) {
var anterior = $("#elemento_" + (numero - 1)).val();
this.find("option[value='" + anterior + "']").prop("selected", "selected").change();
}
});
Which inspects the dropdown in question and, if it's not the first one, will get the value of the previous dropdown and load it in the current one.
Now, this is all fine and well… except that, in my tests, the event only gets triggered when the first dropdown is loaded (the alert("Moooo") only appears in the first dropdown). If I press the button, the 2nd, 3rd… dropdowns appear, but the event isn't triggered. I suspect that it's because of the explanation here:
https://stackoverflow.com/a/6173263/470994
(bind only works for the elements that exist initially, not the ones added later).
The suggested solution is to use on()… but I don't know exactly how to use it to capture custom events like the one I've defined for html() changes. Can you even do that? Is there any other solution?
Thanks.

Setting jQuery value into c:foreach loop

I am basically trying to get values with an ajax request based on a specific id. I then would like to load the json List returned, and load it into a jstl foreach loop. This is my code for the ajax GET request:
$(this).on("click", ".edit_sighting", function(){
var username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings) {
});
});
My Button that gets pressed to load these values: So when this is instantiated, I want to load all the sightings that user has into a modal.
<button class="edit_sighting" value="${sighting.username}">Edit Sighting</button>
I want the returned 'sightings' to go into a c:foreach loop to show if the user has more than 1 sighting.
<c:forEach var="" items="${?}">
</c:forEach>
I dont know how to set the jQuery value returned into the 'var' section?
Thanks
Try this:
$(this).on('click', '.edit_sighting', function() {
$.get('${pageContext.request.contextPath}/getSighting/' + $('.edit_sighting').val(), function(sightings) {
$('c\\:forEach').attr('var', sightings);
});
});
Also, why are you using $(this) as a selector when binding the click event?

How to get div from second page display in first page

In my main.html page I have a button. When that button is clicked, I need to get the content of another page.
The target page has five divs, I need to catch one div and display that div data in main.html page.
Use Javascript and JQuery. See http://docs.jquery.com/Manipulation or specifically http://docs.jquery.com/Ajax/load
To be precise use something like this:
$("#yourdiv").load("/yourpage.html #section");
jQuery can do this very elegantly:
<script type="text/javascript" src="/js/jquery/jquery-1.3.2.min.js"></script>
<script>
//only when the DOM has been loaded
$(document).ready(function() {
//bind to button id="myButton" click event
$('#myButton').click(function() {
//populate div id="myDiv" with specific div (div id="someDiv") from another page
$('#myDiv').load('/anotherPage.html #someDiv');
});
});
</script>
See jQuery Ajax/load
As long as the second page is on the same domain, you can use AJAX techniques. For example, using Prototype you could do something like this:
new Ajax.Request('http://url.of.second/page', {
method: 'get',
onSuccess: function(transport) {
//make a regular expression to grab the required HTML fragment
var re = /<div id="otherdiv">(.*)</div>/i;
//extract the fragment from transport.responseText
var found = transport.responseText.match(re);
//add the fragment to targetdiv on current page
$('targetdiv').innerHTML=found[1];
}
});
Jiri's answer is spot on.
http://docs.jquery.com/Ajax/load
is the exact jquery link.
Thanks Jiri...

Categories

Resources