Make ajax request and success data show in id <select></select> part - javascript

See this link..
My HTML page contains a similar multiple select drop down. Something like this -
<select id="box" data-placeholder="Choose from available option.." class="chosen-select student-select" name="classes" multiple style="width:310px;" tabindex="4">
</select>
In this select drop down, I'm trying to print <option></option> by making an Ajax request and showing the success data there.
When I used a simple <select></select> without using the chosen style, I can see the options there. But when I use the chosen style near the select (multiple selection) then is doesn't shows the options.
document.getElementById("box").innerHTML = data;
I am doing something like this.Please, help why it doesn't show me when I used that chosen effect.?
$(document).ready(function(){
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: '../folder/page1.php',
data: "mid="+Id,
success: function( data ) {
alert(data);
document.getElementById("box").innerHTML = data;
}
});
});
});

You will need to initiate chosen after the new html has been loaded in the page via ajax.
This has been answered in this question.
Chosen not working on elements from AJAX call

You only can show the HTML output in DOM. I am assuming that you're getting options after ajax request. Just try to change like
$(document).ready(function(){
$('#customer').change(function(){
var Id = $(this).val();
$.ajax({
type: "GET",
url: '../folder/page1.php',
data: "mid="+Id,
success: function( data ) {
$("#box").html(data);
$(".chosen-select").chosen();
}
});
});
});
After AJAX call you should initialize your select box. try and share the results.

Related

div element hides when load() function is called

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
}
});
})

Attach jquery events to dynamically created elements (jquery load php file)

I have a php employee directory website that lists all our employees in a table (connected to mysql), and you are able to click each employee to open up their details in another div.
$('.emptab').click(function(event) {
var status = $(this).attr('id');
$("#empview").load("employee.php", {'data': datastring, 'current': status});
});
I originally had the above code, but needed to be able to attach events to dynamic elements, so I changed to the following code:
$('tbody').on('click', 'tr.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});
I did it that way as I read in another question (In jQuery, how to attach events to dynamic html elements?) that you can use that format to attach events to dynamic elements. Just to clarify, this code continues to work with the initial page, but fails after the search filter is used.
My dynamic elements comes from a filter/search function I have that will change the list of employees based on a search text box which changes the list of employees based on a filter.php document I created.
$('#search').on('input propertychange paste', function() {
var string = $('#search').val();
$("#employeelist").load("filter.php", {'data': datastring, 'search': string});
});
However, when those elements are created from that php file, I am unable to access the elements through my jquery, I'm not sure what I'm doing wrong. There were about 4 other questions I saw where the answer was to use the jquery on function, which I've tried with no success.
Thanks for your time.
You can use following code for this
$(document).on('click', '.emptab', function() {
var status = $(this).attr('id');
$("#employeedetails").load("employee.php", {'data': datastring, 'current': status});
});

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.

AJAX dropdown within toggle(function) only works once

I have a table where rows are dynamically added.
In one of the cells I would like to toggle between a dropdown and an input box.
The dropdown is a PHP file loaded via AJAX. The issue is the dropdown only renders once.
First time you click the toggle button, the dropdown appears, as it should.
Second click switches it to the input field, as it should.
Third click does nothing, it just stays on the input box and does not toggle back to the dropdown.
If I comment out the AJAX call and put in a simple dropdown, it toggles back and forth just fine. So I believe the issue is with the AJAX portion.
Link to http://jsfiddle.net/6h5BD/1/
NOTE: the AJAX is currently commented out in jsfiddle and replaced with a temp dropdown so you can see what results I am looking for.
The portion of JS in question:
$('input[name="button"]').toggle(function() {
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$('#brand').html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
The PHP:
$sqlbrand = "SELECT BRD_Name FROM Brands ORDER BY BRD_Name asc";
$resultbrand = odbc_exec($conn, $sqlbrand);
ECHO "<select name='itemBrand[]' style='width:120px' size='1'>";
while ($rowbrand = odbc_fetch_array($resultbrand)) {
echo "<option value='".$rowbrand['BRD_Name']."'>".$rowbrand['BRD_Name']."</option>";
}
echo "</select></td>";
I am very open to handling this in a different manner. I have tried several different approaches, but to no avail.
Thank you in advanced for any assistance with this issue.
I cant completely help you debug if I can't see the PHP file.
But from the HTML/JS I can see a potential problem. You are selecting $("#brand") and changing the html to the output_string. But when you are cloning your rows, you are making multiple divs with id of #brand and ids are supposed to be unique, you should use class instead.
Can you try if this works?
$('input[name="button"]').toggle(function() {
var $this = $(this);
$.ajax({
url: 'http://localhost/brandDropdown.php',
type:'POST',
dataType: 'html',
success: function(output_string){
$this.closest('td').prev().html(output_string);
}
});
}, function() {
$(this).closest('td').prev().html("<input type=\"text\" name=\"itemBrand[]\" id=\"itemBrand\" size=\"10\" placeholder=\"New Brand\" style=\"text-transform: uppercase\"/>");
});
In your code (in the fiddle)
$(this).closest('td').prev().html(...)
should be
$(this).closest('td').prev().find('#brand').html(...)
because $(this).closest('td').prev().html(...) is replacing the html of td which means it's just removing the div with id #brand from within the td so in your ajax success callback $('#brand').html(output_string); is not working because it's not inside the td once you toggled it.

How to select parent div of a form in JQuery?

here is what i got
<div id="right">
<from id="test">
<input type="submit">
</form>
</div>
and a lil jquery
$(document).ready(function(){
$('form').submit(function()
{
$(this).parent().html('<h1>1</h1>');
});
});
you can play with that here,
and by clicking on submit button it should put <h1>1</h1> in div#right but it don't !
Cause this is a form in this case but it works with button label or any thing else and I think that is because form is not a DOM node.
So how can I select the parent of a form, or in other words how can i select the Div that contents the form ?
Update: as it was a part of an ajax call i wanted to break it down and find the problem
but i had made a typo which cost me an hour or so, but the problem with ajax was that you $(this) inside success: is not the form any more so i did like this
`$('form').submit(function(){
form = $(this);// I set the form to a varible !!
$.ajax({
type: "POST", url: "ajax.php", data: $(this).serialize(),
success: function(data){
$(form).parent().html(data); // I used the varible i set to form before!
}});`
anyways, how can i mark this question as solved ?!
As Chowlett says, use form rather than from.
That code will then work, because the $(this) inside the submit function will select the form element, the parent of which is is the #right div.
You could use .parent('div') to make sure you select a div, and not anything else.
as it was a part of an ajax call i wanted to break it down and find the problem but i had made a typo which cost me an hour or so, but the problem with ajax was that $(this) inside success: is not the form any more so i did like this
$('form').submit(function(){
form = $(this);// I set the form to a varible !!
$.ajax({
type: "POST", url: "ajax.php", data: $(this).serialize(),
success: function(data){
$(form).parent().html(data); // I used the varible i set to form before!
}});

Categories

Resources