I want to update a select options according to date that the user picks. For that I tried using ajax request to get data and append the data received to a select element as options. There's nothing wrong with the json object that's received as I tried logging data to console and it gives the data I ant. But hen I try to append it to select element the options do not get appended.
JavaScript code
$.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
html code
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
function f1(){ $.ajax({
type: 'GET',
url: 'sessions',
data: { date: date },
success: function (data) {
var sessions = data['sessions'];
console.log(sessions);
$('select').html('');
$.each(sessions, function (i, session) {
$('select').append($('<option/>', {
value: session[0],
text : session[1]
}));
console.log(i);
console.log(session[1]);
});
}
});
}
var data ={
"sessions" : [{"value":"value 1","text":"Option 1"},
{"value":"value 2","text":"Option 2"},
{"value":"value 3","text":"Option 3"},
{"value":"value 4","text":"Option 4"},
{"value":"value 5","text":"Option 5"}]
}
function fillSelect(){
var sessionList=data.sessions;
$('#session12').empty();
var msg='';
console.log(sessionList.length);
for(i=0;i<sessionList.length;i++){
var bean=sessionList[i];
msg+='<option value="'+bean.value+'">'+bean.text+'</option>';
}
$('#session12').html(msg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div id="sessionDiv" class="input-field" style="padding:10px">
<select class="black-text text-lighten-1" name="session" id="session12" >
<option value="0" disabled selected>Choose your preferred session</option>
</select>
<button type="button" onclick="fillSelect()"> click to fill</button>
<label for="session" class="purple-text text-lighten-2"> Session :</label>
</div>
</div>
If response of async request you are getting in data is similar to what i have written in data variable in snippet then my way of generating the option will work just fine. If response you are getting is exactly same as i have shown in data(by that i mean structure of the variable) then you can simply replace all your code in ajax function with my code in fillSelect function
Related
I'm trying to set the selected option text for a select menu to be whatever location is - this parameter has been passed into the updateDepartment function dynamically from a previous PHP request.
The AJAX function that follows calls to another PHP file to dynamically populate the #editDepartmentLocation select menu with a list of text/value option pairs. One of the names in this list will always match whatever location parameter is passed into the function.
I'm able to set the value of #editDepartmentName to the name parameter as this is just a text input, however when I try to add $("#editDepartmentName").val(location) this does not work and the selected option just defaults to the item at the top of the list, even though the value of location is present in the list.
Is there a way to get around this?
Thanks for any help.
JS:
function updateDepartment(name, id, location) {
$.ajax({
url: "libs/php/getLocation.php",
type: 'GET',
dataType: 'json',
success: function (result) {
console.log(result);
if (result.status.name == "ok") {
$.each(result.data, i => {
$('#editDepartmentLocation').append($("<option>", {
text: result.data[i].name,
value: result.data[i].id,
}));
});
};
},
error: function (error) {
console.log(error);
}
});
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
HTML:
<div class="form-group">
<label for="name">Name:</label>
<input type="text" value="" class="form-control" id="editDepartmentName" required>
</div>
<br>
<div class="form-group">
<label for="location">Location:</label>
<select class="form-control custom-select" id="editDepartmentLocation" required>
</select>
</div>
Ajax is async, so "editDepartmentLocation" is most likely not populated yet.
Try moving:
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
Inside the success function. Or do a comparison like:
var option = $("<option>", {
text: result.data[i].name,
value: result.data[i].id,
});
if (result.data[i].id == location){
option.attr("selected", "selected");
}
$('#editDepartmentLocation').append(option);
I am using select2 version 3.5.4.
I want to have two select2 dropdowns side by side. When page loads first time one select2 dropdown has data whereas second select2 dropdown is empty. Once user clicks on an entry/option in the first select2 dropdown an ajax call should be made to the server and second select2 dropdown should be populated with ajax response data. I am not being able to achieve it. Whenever i try to populate second dropdown I get errorrs like,
Option 'data' is not allowed for Select2 when attached to a <select> element
Option 'ajax' is not allowed for Select2 when attached to a <select> element
My code is something like,
HTML:-
<div class="form-group">
<label class="col-md-4 control-label" for="folderSelect">Files & Folders</label>
<div class="col-md-5">
<div class="select2-wrapper">
<select class="form-control select2" id="folderSelect" name="folderSelect">
<option></option>
<option th:each="folder : ${folders}" th:value="${folder}" th:text="${folder}"/>
</select>
</div>
</div>
<div class="col-md-5">
<div class="select2-wrapper">
<select class="form-control select2" id="fileSelect" name="fileSelect">
<option></option>
<option th:each="file: ${files}" th:value="${file}" th:text="${file}"/>
</select>
</div>
</div>
</div>
JS:-
$('#folderSelect').on("select2-selecting", function(e) {
var value = $(e.currentTarget).find("option:selected").val();
var data = null;
$.ajax({url: "test?value=" + value, success: function(result){
data = result;
return result;
}});
$("#fileSelect").select2({
/* ajax: { // Tried but didn't work
dataType: 'json',
url: 'test',
results: function (data) {
return {results: data};
}
}*/
/*data: function() { //Tried but didn't work
$.ajax({url: "test", success: function(data){
return data;
}});
}*/
});
//Tried but didn't work <br>
$("#fileSelect").select2('destroy').empty().select2({data: data});
});
follow this
$("#fileSelect").empty();
$("#fileSelect").select2({data: data});
It worked well in my case
I want to add this into my database but I don't know how to send it.
db_table
id int(11)
employee varchar(40)
date_complete date
time time
status boolean
job varchar(50)
I have all the data but I don't know how to turn it into an array so that I can send it to php and save it in my mysql database.
or if there is a better way to structure this code to make it easier or better practice.
$(document).ready(function() {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function() {
$('<div/>', {
'class': 'extraPerson',
html: GetHtml()
}).hide().appendTo('#container').slideDown(200);
});
})
function GetHtml() {
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=date]')[0].name = "date" + len;
$html.find('[name=employee]')[0].name = "employee" + len;
$html.find('[name=time]')[0].name = "time" + len;
$html.find('[name=status]')[0].name = "status" + len;
$html.find('[name=job]')[0].name = "job" + len;
return $html.html();
}
.extraPersonTemplate {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<form name="form1" id="form1">
<div class="extraPersonTemplate">
<div class="controls controls-row">
<select class="span2" name="employee">
<option value="Joe">Joe</option>
<option value="Anna">Anna</option>
<option value="Liz">Liz</option>
<option value="Daniel">Daniel</option>
</select>
<input class="span3" placeholder="date" type="date" name="date">
<select class="span2" name="time">
<option value="9:00:00">9 a.m.</option>
<option value="10:00:00">10 a.m.</option>
<option value="11:00:00">11 a.m.</option>
<option value="12:00:00">12 p.m.</option>
<option value="13:00:00">1 p.m.</option>
</select>
<select class="span2" name="status">
<option value="finished">Finished</option>
<option value="inprogress">In Progress</option>
</select>
<select class="span2" name="job">
<option value="design">Design</option>
<option value="html">HTML</option>
<option value="php">PHP</option>
</select>
</div>
</div>
</form>
<div id="container"></div>
<i class="icon-plus-sign icon-white"></i> Add another Job</p>
One solution would be to serialize the form fields in your Form with Jquery:
$( "form" ).on( "submit", function( event ) {
var params = $( this ).serialize();
$.post(yourserver.php, params, validate, "json")
});
function validate(response) {
if (response.success) {
// -- Do something after successful commit
console.log("Allgood")
} else {
// -- Display an error
console.log(response.message)
}
}
Good doc on https://api.jquery.com/serialize/
Where is your database located? Is it at a server with a URL? Can you configure an API with endpoints for that URL? Without knowing much about your database, we can't speak to how, in your specific case, you will actually save that data.
As for your options, should you figure out what your database situation is, here's what I think:
Here's an intro to HTML forms and here's a deeper break-down. HTML forms can automatically send POST requests with the data in the form sent as form-data on a submit event. It appears your data is structured in an HTML form, this could be an option.
You seem to have an understanding of how to access DOM data with jquery. You could gather up the data into an object of key-value pairs and then send it to your server with the jquery.ajax() method.
For a good breakdown of setting up a RESTful backend, I like to recommend Heroku's RESTful MEAN guide.
Pass an array of elements created with jQuery
var elementValue1 = $("#id").val(); // depends on type of element (text, select, checkbox, ...)
var elementValue2 = $("employee").val();
var request = $.ajax({
url: "script.php",
method: "POST",
data: { id : elementValue1, employee: elementValue2 }, // etc.
dataType: "html"
});
request.done(function( msg ) {
alert("data sent to script");
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
Look at http://api.jquery.com/jquery.ajax/ too
Hello i am making option to choose among few ips and as its auto generated with php all option id="userip" is same. I face problem when i choose 2nd, 3rd or even 4th it auto take first ip which is 127.0.0.1 even if in option i choose ip 127.0.2.2 or any other.
I wanted to solve this so wanted to know best way to do it.
<div class="row"> Choose ip:
<select name="search">
<option id="userip">127.0.0.1</option>
<option id="userip">127.0.2.2</option>
<option id="userip">127.3.3.3</option>
<option id="userip">127.0.4.4</option>
</select>
<input class="adm" type="button" onclick="getuser()" value="Get Result">
</div>
Here is my js
function getuser() {
var e = $("#userip").val();
$("#showuser").html("")
$.ajax({
url: "adm.php",
type: "post",
data: "action=getuser&search="+e+"",
dataType: "json",
success: function (e) {
// do something
},
error: function () {}
})
}
ID must be unique at the page:
<div class="row"> Choose ip:
<select name="search" id="userip">
<option>127.0.0.1</option>
<option>127.0.2.2</option>
<option>127.3.3.3</option>
<option>127.0.4.4</option>
</select>
<input class="adm" type="button" onclick="getuser()" value="Get Result">
</div>
And for select option value, use child selector. See jquery official documentation
var e = $("#userip option:selected").text();
Or
var e = $("#userip").val();
just fetch the value of the search field. you can also use the callback onchange.
HTML code
<div class="row"> Choose ip:
<select name="search" id="search" onchange="getuser()">
<option id="userip">127.0.0.1</option>
<option id="userip">127.0.2.2</option>
<option id="userip">127.3.3.3</option>
<option id="userip">127.0.4.4</option>
</select>
</div>
JS code
function getuser() {
var e = $("#search").val();
$("#showuser").html("")
$.ajax({
url: "adm.php",
type: "post",
data: "action=getuser&search="+e+"",
dataType: "json",
success: function (e) {
// do something
},
error: function () {}
})
}
I have 3 dropdowns that are created via javascript, they call an 'updateTable' function when a choice gets made.
Ultimately I am trying to 'filter' a table of data depending on choices made in the dropdowns. If the user just picks one of the dropdowns I want the other choices to submit at the same time (just with empty data if they are not selected, or the currently selected choice if they had already chosen them).
My updateTables function looks like this:
function updateTables (creativeVal,stationVal,verticalVal)
{
//-----------------------------------------------------------------------
//Send the filter criteria
//-----------------------------------------------------------------------
$.ajax({
url: 'api.php', //the script to call to get data
data: {"creative": creativeVal, "station": stationVal, "vertical": verticalVal}, //insert url arguments here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
$('#results').empty();
updateTableRows(response);
} //end of on success
}); //End Ajax call
}; //End Creative Function
My dropdowns look like this:
<!--DROPDOWNS-->
<div id="dropdowns">
<div id="creativesel">
Creative -
<select name="creative-select" id="creative-select" onChange ="updateTables(this.value);">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="stationsel">
Station -
<select name="station-select" id="station-select" onChange ="updateTables(this.value)">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="verticalsel">
Vertical -
<select name="vertical-select" id="vertical-select" onChange ="updateTables(this.value)">
<option value="" selected="selected">All</option>
</select>
</div>
</div> <!--Dropdowns ending-->
No matter which dropdown is selected - the request goes through appending ?creative=whatever_the_user_selected_from_any_of_the_3_dropdowns
Ultimately I want it append something like ?creative=whatever_selection&vertical=whatever_selection&station=whatever_selection so I can get the data on the other end and do what I need to with it.
Am I sending the json request improperly?
How about something like this: http://jsfiddle.net/joeframbach/2XBVv/
I've moved the onchange event to jquery where it belongs, and am pulling all the values from all dropdowns rather than just the one that changed.
html:
<!--DROPDOWNS-->
<div id="dropdowns">
<div id="creativesel">
Creative -
<select name="creative-select" id="creative-select">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="stationsel">
Station -
<select name="station-select" id="station-select">
<option value="" selected="selected">All</option>
</select>
</div>
<div id="verticalsel">
Vertical -
<select name="vertical-select" id="vertical-select">
<option value="" selected="selected">All</option>
</select>
</div>
</div> <!--Dropdowns ending-->
javascript:
$(function() {
$('#dropdowns select').change(function() {
//-----------------------------------------------------------------------
//Send the filter criteria
//-----------------------------------------------------------------------
$.ajax({
url: '/echo/json', //the script to call to get data
data: {"creative": $('#creative-select').val(), "station": $('#station-select').val(), "vertical": $('#vertical-select').val()}, //insert url arguments here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(response) //on recieve of reply
{ //Do the following on Success
$('#results').empty();
console.log(response);
} //end of on success
}); //End Ajax call
}); //End Creative Function
});
Add the values for the other dropdowns into your onchange call.
updateTables($('#creative-select').val(), $('#station-select').val(), $('#vertical-select').val())
Alternatively, don't pass the parameters in your onChange method and get the values in the updateTable function.