How to select multiple values in form:select using ajax response - ajax

I have an Ajax call that will return an object with an attribute of collection of profile. How can I select multiple values in <form:select> using these collection of profile.
$.ajax({
... // some omitted codes // ...
success : function(response) {
response.profiles // collection of profiles
}
<form:select id="profile" path="profiles"
items="${profilelist}" multiple="true" itemValue="id" itemLabel="type"/>

This seems duplicate question, always first try to see if similar question is there for your problem.
You also have not specified which framework you are using, because if you are using any framework then you can get data in option based on that.
Here I am answering for without any framework,
<form:select id="profile" path="profiles"
items="${profilelist}" multiple="true" itemValue="id" itemLabel="type"/>
ajax call should be something like this,
$.ajax({
type: "GET",
url: "http://.......api/1/AbsenceType",
dataType: "json",
success: function (data) {
// Get select
var select = document.getElementById('profiles');
// Add options
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] +
'</option>');
// Set selected value
$(select).val(data[1]);
}
}
Hope this helps.

Related

Harvest Chosen multiselect dropdownlist inconsistently populates with set value

I have a ASP.net webform populated with data from a MS SQL DB, and allows you to edit values.
The web app uses a Harvest Chosen multiselect dropdown list (max=1) to select two different persons picked from the same list of information, but on two separate controls.
When I refresh the page, sometimes both controls are populated with the correct value, sometimes neither or one are. I tested in the console and it is definitely pulling the correct information from the DB, but I must be missing something relating to how these procedures are executed. I have done this work with VB.NET and ASP controllers in the past. This is my first time using AJAX and web method functions. I believe I am missing an update somewhere, or not understanding the order in which code is executed.
I tried explicitly stating the order of operations in the .aspx page, and then doing no update triggers until after all the code for the controller had been executed, but this appears to have broken both controllers (the both end up looking like normal select controllers). Apologies if my terminology is not on point, I am very self-taught. The current state of the code where I get inconsistent application
The .aspx page is as such. Each control has a set of different parameters that affect how it is populated, and what happens when it changes.
<select class="chosen-select" multiple data-placeholder="Assign a scientist" name="ChosenScientist" style="width:800px;" id="cmbChosenScientist">
<script type="text/javascript">
handleChosenControls("select#cmbChosenScientist.chosen-select");
</script>
</select>
<select class="chosen-select" multiple data-placeholder="Assign a supervisor" name="ChosenSupervisor" style="width:800px;" id="cmbChosenSupervisor">
<script type="text/javascript">
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
</script>
</select>
The aspx page passes the controller name to a function which first defines all of the parameters used by the controllers.
function defineChosenControls(controller) {
switch (controller) {
case "select#cmbChosenScientist.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studyScientist" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
case "select#cmbChosenSupervisor.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studySupervisor" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
}
}
The function that handles the populating the options, setting the current value, and handling changes is as follows:
function handleChosenControls(controller) {
//Purpose: Any time a Chosen control is loaded, changed, etc., this is run.
defineChosenControls(controller);
$(controller).chosen({ max_selected_options: 1 });
//Script for populating the control
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: populateData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).append('<option value="' + line[Object.keys(line)[0]] + '">' + line[Object.keys(line)[0]] + '</option>');
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
//Script for determining current value during load
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: currentData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).val(line[Object.keys(line)[0]]).trigger("liszt:updated");
console.log(line[Object.keys(line)[0]]);
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to retrieve current value of " + controller + " from server-side."); }
});
//Script for when a value in the control is changed
$(controller).on('change', function (e) {
defineChosenControls(controller);
$.ajax({
type: "POST",
url: "ClientToServer.aspx/PassJqueryControlValue",
data: changeData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
});
}
I expect both controls to have the proper value in the DB, and those values are being written in the browser console properly, but the harvest chosen controls are inconsistent.
The solution was to call the code after load.
<script type="text/javascript">
$(window).bind("load", function() {
handleChosenControls("select#cmbChosenScientist.chosen-select");
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
});

data not pass using ajax after onclick

I'm trying to remove an element from the database.
I don't know why, but the data is not getting to the url i inserted.
this is the code (the obj is indeed faded - only in the client side):
$(document).on("click", "#deleteAdmin", function(e) {
$.ajax({
url: "admin/adminProccess.php",
type: "get",
data: $('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin',
success: function(data) {
$('#idPriv:checked').each(function(){
$(this).parent().parent().remove();
});
var item = $(deleteAdmin);
item.fadeOut();
}
});
});
is there something wrong in my code?
when i'm trying to access manually to the url i can see some results - but with my code its not sending the data.
any ideas?
edit: this is my idPriv:
<input type = "checkbox" name="idPriv[]" id="idPriv" onclick="evaluateIT(this)" data-related-item="adminPanelShow" value ="<?php echo $value["id"].':'. $count; ?>" />
Try to change:
$('#idPriv:checked').serialize() + '&str=' + 'deleteAdmin'
to:
$('#idPriv:checked').val() + '&str=' + 'deleteAdmin'

Send one more parameter from serialize()

Into the "data" line of my AJAX code, I would like to send one more parameter (called "action") from serialize(). The 'data' line would look like this (obviously it doesn't work) :
$('.input_inscription').blur(function(){
var myInput = $(this);
$.ajax({
dataType: 'json',
type: "POST",
url: "my_url.php",
data:myInput.serialize()+"&action='input_control'",
success: function(data){
if (data.a == true){
$(".inscription_form_ctrl").text( data.b );
}else{
$(".inscription_form_ctrl").text( data.b );
}
}
});
});
Ps: I serialize a input field, not a form ! So i need to add the "action" parameter "manually" (it can't be a hidden input for example).
Could you share a little more of your code to get a clearer idea of what you are doing?
Anyway,
If you do wish to pass the data through the url, you might as well append the &action="input_control" to the form action attribute if you are using a form, like so
<form action="next.php?action='input_control'" method="POST" >

How to populate a jQuery Mobile list view with JSON data from server?

I'm using jQuery Mobile with PhoneGap. How can I pull JSON data (from a server) and populate it into a list view.
Have a look at the jQuery.getJSON() method on w3schools and jQuery API.
Example from jQuery API:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example, of course, relies on the structure of the JSON file:
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Using this structure, the example loops through the requested data,
builds an unordered list, and appends it to the body.
try this one:
$.ajax({
type: "POST",
url: "your_url",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:successFunction,
error: function(msg) {
alert(msg.statusText);
}
});
function success:successFunction(data){
var html ='';
$.each(data.d, function(index, item) {
html += '<li>' + item.Your_data+ '</li>';
});
$('#ul_id').append($(html));
$('#ul_id').trigger('create');
$('#ul_id').listview('refresh');
}
function makeList() {
$.post("http://example.com/getlist.php",
function(resultfromphp) {
$('#ulListview').append(resultfromphp);
$('#ulListview').trigger('create');
$('#ulListview').listview('refresh');
});
}
$("#pageName").live('pagebeforeshow', function(event) {
makeList();
});
This works perfectly for me. The php is returning <li></li> tags
The html is a <ul id="ulListview"></ul> tag
I am working on a similar project using JQM which I would be passing through phone gap later on. The above answers although can be used to populate data dynamically using ajax, however don't address the implications of overriding the JQM ajax as the Jquery ajax is not really equipped at handling the JQM events which are built to extend DOM event for those who are interested or in a similar dilemma like me, I hope the below page helps you to take a informed decision with your project.
http://jquerymobile.com/demos/1.2.0/docs/pages/page-dynamic.html

jQuery ajax loop containing onclick event only changes last occurrance

My page displays posts stored in my database and pairs a like/dislike button to each post.
I am trying to make it so that when a user clicks like or dislike, the value is sent to my database for later recollection.
I have a complex loop that I hope to explain:
On page load, an ajax call is made to an external php file to fetch data from my database. The result is an object array which holds "postID":value. Inside a for loop, I am storing the value inside var postID for easy access. I'm obviously going about this wrong because the code does execute, but only sends the value and postID of the last occurrence in the loop no matter which pair of buttons I press: If I have 11 posts in my database and I press "like" on post 3 it will store the value 'like' but for post 11. If I press dislike on post 7 it will store the value 'dislike' but for post 11.
So the question is, how do I fix this so when I press like or dislike for post x, it will store the value for that same post and not the last post in my database?
The array looks like this:
{"s":0,"d":[{"postID":"1"},{"postID":"2"},{""pos‌​tID":"3"},{""pos‌​tID":"4"},{""pos‌​tID":"5"},{""pos‌​tID":"6"},{""pos‌​tID":"7"},{""pos‌​tID":"8"},{""pos‌​tID":"9"},{""pos‌​tID":"10"},{""pos‌​tID":"11"}]}
The post divs are the following format:
<div id="post_#"> //# representing the postID in the database
<div id="like_#"></div> //# repesenting the postID in the database
<div id="dislike_#"></div> //# representing the postID in the database
</div>
My jQuery (includes only the like button):
$(document).ready(function() {
$.ajax({
url: 'postID.php', //fetch the above array
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (post) {
if (post.s == 0) {
//Loop through returned data array using: post.d
for (var key in post.d) {
var obj = post.d[key];
for (var prop in obj) {
var postID = obj[prop];
//When like button is clicked do this
$('#like_' + postID).click(function() {
// Declare variables
var value = '1';
// Send values to database
$.ajax({
url: 'check.php', //check.php receives the values sent to it and stores them in the database
type: 'POST',
data: 'postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_'+ contestID).html('').html(result).prependTo('#post_' + postID);
}
});
});
}
}
}
}
});
});
So again, my problem is that the second ajax loop is only sending the last instance of var postID instead of sending the postID of the post that was actually clicked.
Any ideas?
*updated to use .on() instead of .live() as its deprecated since 1.7
try this instead:
html
<div id="post_#" class="post"> //# representing the postID in the database
<div id="like_#" class="like">test</div> //# repesenting the postID in the database
<div id="dislike_#" class="dislike"></div> //# representing the postID in the database
</div>
jquery
$(document).ready(function() {
//When like button is clicked do this
$('.like').on('click', function() {
var postID = $(this).attr('id').replace('like_', '');
// Declare variables
var value = '1';
// Send values to database
$.ajax({
url: 'check.php',
//check.php receives the values sent to it and stores them in the database
type: 'POST',
data: 'postID=' + postID + '&value=' + value,
success: function(result) {
$('#Message_' + contestID).html('').html(result).prependTo(this);
}
});
});
});
Here is the link to a sample http://jsfiddle.net/TXwZk/

Resources