I've manage to create a sample in jsfiddle http://jsfiddle.net/9vkk5/ to illustrate my problem
As you might see it's only an example because I fill the select with information by database, this way:
$.ajax({
type: "POST",
url: "load.php?type=clients",
dataType: 'json',
success: function(data){
$("#clients").empty();
var options = '';
for(var i = 0; i <= data.length - 1; i++){
options += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
}
$("#clients").append(options);
$("#clients").trigger('chosen:updated');
}
});
But the problem I have is totally the same as the jsfiddle example. I would like to, whenever I click the select to fill with data from database but keep the actual option selected.
Edit: Solved.
$("#clients").append(options);
$("#clients").val(selected_option); // trick is here
$("#clients").trigger('chosen:updated');
$("#clients").trigger('chosen:refresh');
Related
I am just making a simple UI for display orders from Woocommerce shop. I am successfully getting the JSON response and put it into a HTML table. But I need to update the table without refreshing the whole page or table. Actually i need like, whenever Woocommerce get an order, the HTML table should get updated while highlighting the row. I am using AJAX to update the table but its not updating.
Note - I tried to set particular time interval for refreshing the page but i thought it won't be a good solution.
So far i got this below.
**
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "https://localhost/site/wp-json/wc/v3/orders?consumer_key=key&consumer_secret=key1",
dataType: 'json',
type: 'get',
cache:false,
success: function(data){
console.log(data);
var event_data = '';
$.each(data, function(index, value){
/*console.log(value);*/
event_data += '<tr>';
event_data += '<td>'+value.id+'</td>';
event_data += '<td>'+value.billing.first_name + value.billing.last_name+'</td>';
event_data += '<td>'+value.date_created+'</td>';
event_data += '<td>'+value.billing.phone+'</td>';
event_data += '<td>'+value.billing.address_1 + ", " + value.billing.address_2 + ", " + value.billing.city + value.billing.postcode +'</td>';
event_data += '<td>'+value.total+'</td>';
event_data += '</tr>';
});
$("#data").append(event_data);
},
error: function(d){
/*console.log("error");*/
alert("404. Please wait until the File is Loaded.");
}
});
});
</script>
**
Any suggestions please.
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I have this html:
<select id="test"></select>
And This ajax code:
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//url: localhost/web/index.php?name='whatever'
var value = get('name');
$(document).ready(function(){
$('select').select2();
$.ajax({
type: "POST",
url: 'getValues.php',
data: {'test': $("#test").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#test"), options = '';
select.empty();
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
});
</script>
I need to set the value of select as taken from the url,which is (var value).
The value is working fine,as I tested it in alert.
Any help is appreciated
1) You can use .val() after appending options:
select.append(options);
select.val(value);
2)
or add attribute selected to option having same value while building the options html string.
options += "<option value='"+data[i].id+"' "+(data[i].id == value ? "selected" : "") +">"+ data[i].name +"</option>";
Chances are its the AJAX that is causing the issue. you need to trim() the response to remove a whitespace at the end of the returned data. Try the following :
success: function(data) {
var response = data.trim(), select = $("#test"), options = '';
select.empty();
for(var i=0;i<response.length; i++)
{
options += "<option value='"+response[i].id+"'>"+ response[i].name +"</option>";
}
select.append(options).val(value);
}
My problem is solved.
The problem was that the returned value has space,which is taken from url as +
So I replaced "+" by " "
Thanks all !
This is my first attempt to databind an html control via ajax. I check/debug my ajax call and the data are retrieved OK, but the do not appear in the select option. My javascript is located at the bottom of my aspx page. What's the problem
$(function () {
$.ajax({
type: "POST",
url: "psHlp.asmx/getDistricts",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#District").empty();
$.each(msg.d, function () {
$("#District").append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("Failed to load districts");
}
});
});
This is my select option which is located at the beginning of my page
<div class="col-sm-3 col-xs-12 ffield">
<select id="District" style="display: none;">
</select>
</div>
Try using like this on your each loop.
var options;
$.each(msg.d, function () {
options += '<option value="' + this["Value"] + '">' + this["Text"] + '</option>';
});
console.log(options);
$("#District").append(options);
You need to specify (index,value) params in your $.each callback function and use value to access the iterated elements. Something like this.
$.each(msg.d, function (index,value) {
$("#District").append("<option value='" + value.Value + "'>" + value.Text + "</option>");
});
Finally I found the solution. All the above suggestions were correct. The problem occurred because I'm using bootstarp js/css (customer's designer provided the layout), so I need to rebuild the multiselect option after the append.
var options = "";
$.each(response.d, function () {
options += '<option value="' + this['Value'] + '">' + this['Text'] + '</option>';
});
$("#Town").append().html(options);
$("#Town").multiselect('rebuild');
Hope this will help at least one person :)
I am using two drop down(first drop-down category and second drop-down sub category) in a page,both drop-down will be loaded dynamically, in which I will be selecting a value from first drop-down accordingly I have to load value to second drop-down.I has done that,but thing is that it will get done for first time.
But when I click on some other option in states drop-down, its not getting updated on second drop-down.
And My code is:
This piece of code is to get list of category while loading page ie under document.ready
$.ajax({
url : "../category/getCategory",
type : "post",
contentType : "application/json",
dataType : "json",
success : function(data) {
var categoryBOs = data.categoryBOs;
$.each(categoryBOs, function(key, value) {
$("#productCategory").append(
'<option value='+value.categoryId+'>'
+ value.categoryName
+ '</option>');
});
}
});
This part of ajax is to load sub category
$("#productCategory").on('change', function() {
alert($(this).val());
$.ajax({
url : "../category/getSubCategory",
type : "post",
cache : false,
dataType : "json",
data : "categoryId=" + $(this).val(),
success : function(data) {
var subCategoryBOs = data.subCategoryBOs;
$.each(subCategoryBOs, function(key, subCategoryBO) {
subCategories.push({lable:subCategoryBO.categoryId , value:subCategoryBO.categoryName});
$("#productSubCategory").append(
'<option value='+subCategoryBO.categoryId+'>'
+ subCategoryBO.categoryName
+ '</option>');
});
}
});
});
From what I see in your code you always append new entries, yet never remove old ones before. So possibly your list just keeps getting longer with new entries at its end? Try to remove the entries before append new ones:
$("#productSubCategory option").remove();
$("#productSubCategory").append(
'<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>');
In my experience $.each with $.append can get very slow at some amount of list entries. I would rewrite it in native javascript with for() and createElement().
Try adding $("#productCategory").empty() before the first $.each and $("#productSubCategory").empty() before the second $.each.
you need to make html in .each and append after .each end. No option change from first drop down you need to remove the previous on by using $("#productSubCategory option").remove();
$.ajax({
url: "../category/getCategory",
type: "post",
contentType: "application/json",
dataType: "json",
success: function (data) {
var categoryBOs = data.categoryBOs;
var html = '';
$.each(categoryBOs, function (key, value) {
html += '<option value=' + value.categoryId + '>' + value.categoryName + '</option>';
});
$("#productCategory").append(html);
}
});
$("#productCategory").on('change', function () {
alert($(this).val());
$.ajax({
url: "../category/getSubCategory",
type: "post",
cache: false,
dataType: "json",
data: "categoryId=" + $(this).val(),
success: function (data) {
var subCategoryBOs = data.subCategoryBOs;
var html = '';
$.each(subCategoryBOs, function (key, subCategoryBO) {
subCategories.push({ lable: subCategoryBO.categoryId, value: subCategoryBO.categoryName });
html += '<option value=' + subCategoryBO.categoryId + '>' + subCategoryBO.categoryName + '</option>';
});
$("#productSubCategory").append(html);
}
});
});
Just simple thing you have to do here is that every time when you load sub-categories just place following before that .
$(dropdown).empty();
Thanks !
$("select#catname").change(function () {
// part of code
$("#subcatname").append($newOpt1);
// appending the category of dropdown
}
$("#subcatname").trigger('contentChanged');
// changing the contenet
}
});
$("select#subcatname").change(function () {
// something changes after trigger in dropdown
});
// removing the content or clearing the content after selecting
$("#subcatname").empty();
});
});