I have a multiple select item, which allows me to check multiple items. I want to send those selected items via ajax request and afterwards I want to import the those items into my database. My problem is, that I don't know how to loop thru the passed array, which I get by the POST request.
Ajax Request
function insertPlayers(){
var data = $("#playerCards").serialize();
$.ajax({
url: "/database/playercards.php",
type: "POST",
data: data,
success: function (response) {
}
});
}
This is my HTML multiple select:
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
// Options inserted by JQuery later
</select>
This is how my data looks like when I alert it before sending the Ajax Request:
playersearch=test&buypercentage=85&assignAccount=9&assignAccount=10&assignAccount=11
How I add the options to my multiple selectbox:
// loop the response
$.each(response, function(i, e){
// just use your column names, these are just an example, but you get the idea
opt += '<option value="'+e.id+'">'+ e.email + ' - ' + e.coins + '</option>';
});
// append the markup to that select box
$('#assignAccount').html(opt)
My problem:
It should be clearly now that the assignAccount variable is a array which I want to loop thru in PHP but I don't know how I can do this because I don't know the indices. This is what I've tried:
$accountIds = $_POST['assignAccount'];
foreach ($accountIds as $account){
echo $account;
}
Change
<select multiple id="assignAccount" name="assignAccount" class="form-control select">
to something more like
<select id='assignAccount' name='assignAccount[]' multiple='multiple' class='form-control select'>
make the select statement multiple id an array
<select name='assignAccount[]' id='assignAccount[]'>
on your php page you will now have an array for this post.
$_POST['assignAccount'][0]
$_POST['assignAccount'][1]
and so on.
The select element when multiple send data like this:
playersearch=test&buypercentage=85&assignAccount=9,10,11
Hence, in the PHP side you do this:
$accountIds = explode(",", $_POST['assignAccount']);
foreach ($accountIds as $account){
echo $account;
}
Related
i have a select2 element that load data from database using ajax. i want to load the value from db and select it as selected value in edit mode.
but im not able to load the value using trigger function.
i tried using looping by comparing selected values but i got the select2 option orinted twice.
$(document).ready(function(){
var area = $('#area').select2({
placeholder: "Pilih Cabang Area Tagih Collector Agency...",
multiple: true,
allowClear: true,
width: 'resolve'
});
var k;
var selected = [];
//imloading the value from db and insert it into an array
<?php foreach($area_coll as $area){
?>
selected.push("<?php echo $area->group_branch_id;?>");
<?php
}?>
$.ajax({
url: "<?php echo base_url();?>ama/c_agency/populate_dropdown_cabang",
type: 'GET',
success: function(data) {
var html = '';
var j;
data = JSON.parse(data);
//looping cabang
for(j=0; j<data.length; j++){
$('#area').append($('<option>').val(data[j].GroupBranchID).text(data[j].branch));
}
}
});
//this function not working at all
area.val(selected).trigger("change");
});
im not getting any error with this code nor the value still not selected.
Select2 have ajax options.
So I think you can use ajax directly as an options of select2 (reference: https://select2.org/data-sources/ajax#default-pre-selected-values)
The document said:
To provide default selections, you may include an <option> for each selection that contains the value and text that should be displayed:
<select class="js-example-data-ajax form-control">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Mean that at the options you can push selected="selected" at edit page when option is stored on exist record.
Hope it help. thanks
I currently have a webpage that works great. I select my load number and a ajax query gets the information and puts the results in textboxs. The page is split, one part displays information, but when "print" is selected, it formats the results to print a bubble sheet.
Here is the problem. Instead of displaying the "On Screen" results in textboxs, I would rather just display as normal text.
The active page is located at this address
The retrieval code is quite long, here is a sample.
<script>
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#loads").change(function(){ /* TRIGGER THIS WHEN USER HAS SELECTED DATA FROM THE SELECT FIELD */
var loadnumber = $(this).val(); /* STORE THE SELECTED LOAD NUMBER TO THIS VARIABLE */
$.ajax({ /* START AJAX */
type: "POST", /* METHOD TO USE TO PASS THE DATA */
url: "actionprt.php", /* THE FILE WHERE WE WILL PASS THE DATA */
data: {"loadnumber": loadnumber}, /* THE DATA WE WILL PASS TO action.php */
dataType: 'json', /* DATA TYPE THAT WILL BE RETURNED FROM action.php */
success: function(result){
/* PUT CORRESPONDING RETURNED DATA FROM action.php TO THESE TEXTBOXES */
for (i = 1; i < 14; i++) {
$("#prtDescription" + i).val("");
$("#prtMethod" + i).val("");
$("#prtPONumber" + i).val("");
$("#prtGallons" + i).val("");
$("#prtAmount" + i).val("");
}
$("#NumberStops").val(result.NumberStops);
$("#ShipperName").val(result.CustomerName);
$("#prtship").val(result.CustomerName);
$("#ShipperAddr1").val(result.CustomerAddress);
$("#ShipperAddr2").val(result.CustomerAddress2);
$("#ShipperCity").val(result.CustomerCity);
$("#prtshipcity").val(result.CustomerCity);
$("#ShipperState").val(result.CustomerState);
$("#prtshipstate").val(result.CustomerState);
$Phone = result.CustomerPhone
$Phone = '(' + $Phone.substring(0,3) + ') ' + $Phone.substring(3,6) + '-' + $Phone.substring(6,10)
$("#ShipperPhone").val(result.CustomerPhone);
$("#ShipperContact").val(result.CustomerContact);
$("#PickupDate").val(result.PickupDate);
$("#prtdate").val(result.PickupDate);
$("#PickupTime").val(result.PickupTime);
$("#CustomerPO").val(result.CustomerPO);
$("#Weight").val(result.Weight);
$("#prtweight").val(result.Weight);
$("#Pieces").val(result.Pieces);
$("#prtpieces").val(result.Pieces);
$("#BLNumber").val(result.BLNumber);
$("#prtbol").val(result.BLNumber);
$("#TrailerNumber").val(result.TrailerNumber);
$("#prttrailer").val(result.TrailerNumber);
...
I tried document.write() but that cleared the page which is not what I am looking for. I want to keep my images and combobox selection box on the page so I can select other loads when needed rather then just one at a time.
Please help.... If you require more information to answer the question, please ask and I will post.
Why not just make a new div after your load selection and simply append all those results into it?
There are different options to use Ajax as per your Requirement. You can replace the Entire div with the new Data or with the Entire HTML or you can change the selected part alone. It is up-to you who have to choose the suitable method which will be easy for you.
These are the methods available:
Method 1:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(data) {
handleData(data);
}
});
}
This above method will replace the Ajax success with the data that is available after your process is completed.
Method 2:
function testAjax(handleData) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&s=1",
success:function(html) {
handleData(html);
}
});
}
The above function will replace the entire success div with the new HTML part.
Now i will illustrate it with a simple example of how to replace the div using PHP and HTML using AJAX.
Scenario: User Has to select the city and the City Details will load up in Ajax.
HTML:
<select name="city" onchange="selectcity(this.value)">
<option value="">Please Select</option>
<option value="1">USA</option>
<option value="2">Europe</option>
</select>
<div id="ajax_output">
</div>
While selecting the city it will load up the function by using onchange attribute in jQuery and the Ajax will be passed.
JS:
function selectcity(a) {
$.ajax({
type: 'POST'
url:"yourpostpage.php",
data: "&city="+a,
success:function(html) {
$('#ajax_output').html(html);
}
});
}
In the JS am getting the selected value using a since i have passed a parameter to the function and passing it to the Ajax Page.
Ajax Page:
Note: Ensure that if you are going to display the information form the DB you have to connect the DB file to the Ajax page.
<?php
$city_id = $_POST['city']; // Jquery Data that i am retriving on Ajax Page
$select="SELECT * FROM TABLENAME WHERE `city_id`='".$city_id."'";
$query = $con->query($select);
$count = $query->num_rows;
if($count==0)
{
echo 'No Data Found';
}
else
{
while($fetch = $query->fetch_assoc())
{
?>
<div class="col-sm-6">
<label>City</label>
<span><?php echo $fetch['city_name']; ?></span>
</div>
<div class="col-sm-6">
<label>Place</label>
<span><?php echo $fetch['place']; ?></span>
</div>
<?php
}
}
?>
Now in my example i am going to replace the #ajax_output div with the content that is going to come from the Ajax page.
As per the request made in the question i hope so this would be the easiest method so that PHP will execute faster when compared to the JS and the Errors will also be minimal when you use this method.
Hope so my explanations would be clear for you and if you face any hindrance in development let me share thoughts and i will provide you with a solution.
Happy Coding :)
I'm not very familiar with select2.js and the documentation is not that easy to understand.
I have a Compose Message module and I have a select2 with tagging support as the input for the recipient of the message. Every keyup will fire an ajax which will query all the results WHERE something LIKE '%something%'.
The result of the ajax is something like this (when there is already 1 result):
[{
id : 12102719,
firstname : "John",
lastname : "Doe"
}]
What it will supposed to look like if displayed normally
echo "<option value='".$sendTo['id']."'>".$sendTo['firstname']." ".$sendTo['lastname']."</option>";
My HTML is something like this:
<select multiple="true" name="tagRecipients[]" id="tagRecipients" class="form-control select2 input-inline input-xlarge"></select>
My CI Controller looks like this
public function sendToUser() {
$findthis = $this->input->post('findthis');
$this->data['recipients'] = $this->User_model->sendToUser($findthis);
if($this->data['recipients']){
foreach($this->data['recipients'] as $sendTo){
echo "<li id='select2-tagRecipients-result-".$sendTo['school_id']."' class='select2-results__option' role='treeitem' aria-selected='false'>".$sendTo['firstname']." ".$sendTo['lastname']."</li>";
}
} else {
echo "No match found";
}
}
My script looks like this
$(document).on('keyup','.select2-search__field',function(){
$('.select2-results__option').remove();
var tosearch = $(this).val();
$.ajax({
type: "POST",
url: BASE_URL+'users/sendtouser',
data: {findthis: tosearch},
success: function(data){
$('#select2-tagRecipients-results').append(data);
}
});
});
The problem is that the results appended by the ajax can't be clicked.
I believe it is because I just manually accessed the elements created by the theme. The classes and ids .select2-results__option, #select2-tagRecipients-results, .select2-search__field are all from just inspecting the elements using FireBug. Including the whole echo line in the controller.
Basically, what is supposed to happen is that the user can type in some keywords and the results with WHERE column_value LIKE '%keywords%' will be shown as options. And then multiple results can be selected as recipients.
This question already has answers here:
Fetching data from MySQL database to HTML dropdown list
(4 answers)
Closed 7 years ago.
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'"> Barang: ';
row += '<select name="???">';
row += '<option value="A1">A1</option>';
row += '<option value="A2">A2</option>';
row += '<option value="A3">A3</option>';
row += '<option value="A4">A4</option>';
row += '</select>';
row += ' Satuan: <input type="text" size="5" name="satuan[]" value="'+frm.add_satuan.value+'"> Quantity: <input type="text" name="qty[]" value="'+frm.add_qty.value+'"> <input type="button" value="Remove" onclick="removeRow('+rowNum+');"><hr color=red></p>';
$('#itemRows').append($(row));
frm.add_qty.value = '';
frm.add_nama.value = '';
frm.add_satuan.value = '';
};
</script>
How to make drop-down list but with query mysql to show A1, A2, dll.
When submit button for drop-down can't post data anything. Can I store data with this javascript. For text input success post data.
DO NOT DO WHAT YOU ARE TRYING TO DO. You should never, ever, ever write queries on the front-end. You should do your absolute best to hide every detail of the server/database from the user. It is a massive security risk. Please read about SQL injection attacks for starters.
How you should do this:
Store the values of the dropsdowns in JavaScript. Let's keep them in a single object to make life easy:
Your JS:
var options = {
A1: $("#rowNum select option[value='A1']").text(),
A2: $("#rowNum select option[value='A2']").text(),
A3: $("#rowNum select option[value='A3']").text(),
A4: $("#rowNum select option[value='A4']").text()
};
// Now, send this object to your PHP via an AJAX call. Let's assume for simplicity that you will do this using jQuery:
$.ajax({
url: 'my/php/script.php',
data: options,
success: function (data) { console.log('Yay, it worked!'); },
error: function (jqXHR, textStatus, error) { console.log('crap it didn't work', jqXHR, textStatus, error); }
});
Your PHP
<?php
$options = $_REQUEST['options']
// You need to verify the options are valid (and don't have bad values) but that's a different question
// Build your query here. Your PHP is run on the server only so no one else will see it or be able to change it.
You can try this code with some modification. Use jQuery's each to iterate over the array value.
$('#emptyDropdown').empty();
// Parse the returned json data
//var opts = $.parseJSON(data);//Remove comment if you are using JSON
// Use jQuery's each to iterate over the opts value
$.each(opts, function(i, d) {
// You will need to alter the below to get the right values from your data.
$('#emptyDropdown').append('<option value="' + d.yourID + '">' + d.yourValue + '</option>');
});
When I select one item from 1st dropdown, an ajax event will fire up, invoke another function that will and load information to the second dropdown. I do not want this (No button solution please)
<select id=combo1>
<option>...</option>
...
</select>
<input type=button onclick="loadCombo2()">
You can go about something like this:
<select id="combo1" onchange="requestSend(this.value);">
options..........
</select>
<select id="combo2">
options...........
</select>
<script>
function requestSend(txt)
{
$.ajax({
url:'process.jsp',
data: "v=" + txt,
cache:false,
success: function(response){
$("#combo2").val(response);
}
});
}
</script>
....
Populating Combo2 Options:
To populate combo2 options, you need to create them in the script which process ajax request, for example in php (i don't know which language you are using), i will do something like this in ajax processing script:
// db queries to get data or whatever
// create a variable that will hold options and shown in combo2
$options = '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
$options .= '<option value="whatever">whatever</option>' . "\n";
//........ etc
// Now we send back the $options variable which will populate the combo2
echo $options;
If it was being implemented in ASP.NET I'd use an HTTP handler to return the data in JSON format to the second combobox.
Using jQuery you'd call the handler in the following way to implement cascading:
$("#combo1").change(function()
{
$("#combo2").html("");
var valueSelected = $("#combo1").val();
if (valueSelected != 0)
{
$.getJSON('LoadCombo2.ashx?valueSelected=' + valueSelected, function(returnedData)
{
$.each(returnedData, function()
{
$("#combo2").append($("<option></option>").val(this['ID']).html(this['Value']));
});
});
}
});
To see how to implement the HTTP handler, take a look at a more complete step-by-step in this post:
http://www.codedigest.com/Articles/jQuery/224_Building_Cascading_DropDownList_in_ASPNet_Using_jQuery_and_JSON.aspx
If you don't need cascading the comboboxes, it gets easier. Just call the handler passing no parameters and load any data you need to fill the second combobox in the callback function of jQuery.
http://api.jquery.com/jQuery.getJSON/
Hope you get the idea.