How to pass the select2 dropdown value as parameter in ajax URL? - php

Hello everyone this is my first year studying web development, I have decided to work on a personal projet in order to get acquainted to web development world.
EXPLANATION: I am actually trying to design a dependent dropdown using SELECT2 dropdown and AJAX, so for a brief explanation, a customer which is normaly a company can have 1 or more printers and those printers are tracked by their code. Now i want all the printers that belong to a customer to be selected in multiple select2 dropdown once that customer is selected.
PROBLEM: I a using a GET type in the ajax and I find it difficult to pass the selected customer value as parameter in the url and also dynamically display the result in the second dropdown box. Can anyone help me I am so desperate, here is my code below.
PHP SERVER
$customerCode = $_GET['customer'];
$ivccodeArray = getPrinterCodesByCustomer($customerCode);
echo json_encode($ivccodeArray);
JSON ENCODING RESULTS FROM SERVER
[{"ivc_code":"IVC0001","model_id":"32","print_model_id":"32","print_model_name":"ECOSYS M3655idn"},
{"ivc_code":"IVC0002","model_id":"85","print_model_id":"85","print_model_name":"TASKalfa MZ4000i"},
{"ivc_code":"IVC0003","model_id":"57","print_model_id":"57","print_model_name":"TASKalfa 3212i"}]
HTML
<select name='customer' id='customer' class='form-control' required>
<option value=''>Select a Customer</option>
<option value="cus1">customer1</option>
<option value="cus2">Customer2</option>
<option value="cus3">Customer3</option>
</select>
<select name='customer' id='ivcCode' class='form-control' required multiple>
<option value="?=ivc_code?>"><?=print_model_name?></option>
</select>
JS
<script>
$("#customer").select2({theme:"bootstrap4",placeholder:"Select an option"}),
$("#ivcCode").select2({
theme:"bootstrap4",
ajax: {
url: '/mysite/call/pm/?action=printer_codes&customer',
type: 'GET',
data: function (params) {
return {
$("#customer").val(),
search: params.term
}
},
dataType: "json",
success: function(html) {
alert(html)
document.getElementById("ivcCode").innerHTML = html;
$('#' + customer).select2();
}
},
})
</script>

Your URL of
'/mysite/call/pm/?action=printer_codes&customer'
does not specify the customer value. You will need to append it, like:
'/mysite/call/pm/?action=printer_codes&customer=' + $("#customer").val()
So, we have an = sign that separates the customer parameter from its value and we concatenate the actual value to the URL via the + operator.

Related

How to get dropdown name with Ajax use Class

now im making form using PHP code. I combine with ajax code. inside the form contain input type="radio", <textarea></textarea> and dropdown list.
i create ajax code like this
$.ajax({
url: 'index.php?route=data/save',
type: 'post',
data: $('#save-method input[type=\'radio\']:checked, #save-method textarea, #save-method option:selected'),
dataType: 'json',
when debug it. i able to get name and value for radio and textare. but for dropdown, im only able to get the value.
{
data: {
room: "room.4",
undefined: "2021-03-26",
comment: "please ontime"
}
}
"room" is radio name
"comment" is textarea name
but for dropdown it display "undefined".
i set the dropdown like this
<select name="set_schedule" >
<option value="2021-03-26">2021-03-26</option>
<option value="2021-03-27">2021-03-27</option>
</select>
how do i able to get dropdown name using my ajax code.
please help

Ajax return value match the value of the dropdown and show the SELECTED value. Php

What I am doing is passing data via Ajax and putting that data into a Dropdown. So when the data gets passed it should match the selected value in the dropdown and then appear on top with SELECTED on the option so we can see the data right away. So if the data being returned is Product2 then Product2 should be SELECTED and visable.
<script type="text/javascript">
function myFunction() {
var skuvalue=document.my_form.modlistbox.value;
$.ajax({ url: 'modify.php',
data: {sku: skuvalue},
type: 'post',
dataType: "html",
error: function (request, error) {
console.log(arguments);
alert("ERROR: " + error);
},
success: function(data) {
var jsonvalue = $.parseJSON(data);
console.log(jsonvalue);
$(document).ready;
$("#modsku").val(jsonvalue[0]);
$("#modproduct").val(jsonvalue[1]).prop('selected', true); // I tried this and not working. Nothing is being SELECTED.
}
});
};
</script>
<input type="text" name="modsku" id="modsku" maxlength="10">
<select name="modproduct" id="modproduct">
<option></option>
<option value="Product1">Product1</option>
<option value="Product2">Product2</option>
<option value="Product3">Product3</option>
</select>
For what I am looking to have done is something like this.
<select name="modproduct" id="modproduct">
<option></option>
<option value="Product1">Product1</option>
<option value="Product2" selected>Product2</option>
<option value="Product3">Product3</option>
</select>
The chained function call here is superfluous (and doesn't really make much sense in the context, trying to set a selected property on a select element):
$("#modproduct").val(jsonvalue[1]).prop('selected', true);
You can set the selected option in a select simply by setting the value with jQuery:
$("#modproduct").val(jsonvalue[1]);
Note: There are other things in this code which don't make any sense. For example, this:
$(document).ready;
It doesn't do anything, and is really just an opportunity for an error. So there may very well be other problems in your code which prevent the overall result from happening.

How to write PHP code inside jquery for retrieving values from mysql database?

I am trying to get the values for the next drop-down from a database, which will be dependent on two previous drop-downs. The values for first two drop-downs are listed in the file itself. I want the second drop-down to be enable after selecting values from first, and similarly for third after second. Kindly help.
HTML code below:
<form>
<select id="branch" name="branch" class="form-control" onchange="showUser(this.value)">
<option value="">Select</option>
<option value="1">Civil</option>
<option value="2">Computer</option>
<option value="3">Mechanical</option>
<option value="4">Electronics and Telecommunications</option>
<option value="5">Electrical and Electronics</option>
<option value="6">Information Technology</option>
</select>
<select id="semester" name="semester" class="form-control" disabled>
<option value="1">I</option>
<option value="2">II</option>
<option value="3">III</option>
<option value="4">IV</option>
<option value="5">V</option>
<option value="6">VI</option>
<option value="7">VII</option>
<option value="8">VII</option>
</select>
</form>
jquery is:
<script>
$(document).ready(function(){
document.cookie = "s =hello" ;
console.log('hello');
$("#semester").attr("disabled", true);
$("#branch").change(function(){
$("#semester").attr("disabled", false);
$b = $('#branch').val();
$("#semester").change(function(){
$s = $('#semester').val();
$("#sub_code").attr("disabled", false);
console.log($s);
if($s!=1||$s!=2)
$s = $b+$s;
<?php
$s= $_COOKIE['s'];
$sql = "SELECT * FROM subjects WHERE sem_code=`$s`";
?>
});
});
});
</script>
I did not run the query since it is not assigned properly yet.
You can't include php code in javascript , the first is executed on the server side, the second is executed on the client side which means that you can't re-execute only if you resend a request to the server, obviously this is usually done by submitting forms, BUT sometimes -like in your case- we don't want to reload the whole page for each request ! and for this purpose we use AJAX
ajax sends post/get request to a specified php page which does the desired server-side tasks (updating data in the database, selecting some results from database, dealing with sessions maybe, etc...)
try something like this:
var pathurl='/path/to/your/php/file';
var params={}; //the parameters you want to send
params['semester']=$s;
var requestData= $.ajax({
type: 'POST',
url: pathurl,
cache: 'false',
data: params,
dataType: "json",
beforeSend: function () {
//here you can begin an animation or anything...
},
complete: function () {
//here you can stop animations ...
},
success: function (response) {
console.log(response); //check your console to verify the response
//loop other elements inside response
$.each(response, function (index, resultArray) {
//do something : in your case append to dropdown a new option
});
}
});
requestData.error(function () {
alert("error");
});
you should create a php file with the path specified in the above code, and there you can extract what you need from the database table, store values in an array and finally use:
echo json_encode($resultArray);
hope this was helpful

php & js dynamic creation of auto populated dropdown lists

I have created a script which fills the second combobox with the value of the first one. But it is not quite what I want to do. I want to fill the second combobox with the result of a SQL query based on the item which was selected in the first combobox.
Here is my javascript:
<script type="text/javascript">
function selectDropdown(){
var dropdownValue=document.getElementById("dropdown").value;
$('option[value=st]').text(dropdownValue);
}
</script>
first combobox:
<select id="dropdown" name="dropdown" onchange="selectDropdown()">
<option value="dd">--take an option--</option>
<?
$standard = Env::value('standard');
if (!$status)
$statement = "select code from standard";
foreach ($db->query($statement )->fetchall() as $row)
echo "<option".($row == $standard ? ' selected ' : '').">$row[0]</option>";
?>
</select>
and the second one in which I want to show the result of the query: $q= select request.code from request inner join standard on ( request.standard_id=standard.id) where standard.code=$st.
<select name='st' class='txt'>
<option value="st"><? echo $st; ?></option>
</select>
Can anyone give me a hint where I should put query execution? Or just point me what I am doing wrong?
Use jQuery's ajax call to make a request to the server each time when first dropdown selection has been changed. On the server side create a script which will receive that request and return corresponding records for 2nd dropdown in JSON format, which then can be easily processed by javascript. For using ajax see this link: http://api.jquery.com/jQuery.ajax/
It will be like:
jQuery.ajax({
method: "POST",
url: "http://domain.com/path/to/script.php",
data: value_of_selected_item_from_first_dropdown,
success: function(response) {
// Set 2nd dropdown values to those received via response
}
dataType: "json",
});

Dynamically add new combo (select) box

In my page, I have a combo box with an add button. How do I create a new combo box below the original combo box when I clicked the add button? If clicked again, it will produce another combo box. The value inside each combo box is called from the database.
Here's an example, though you'll have to work out the middle tier and back end portion yourself.
Example: http://jsfiddle.net/9hvbt/3/
JavaScript
$('#btnAdd').click(function(){
//Use Ajax to talk to your server (middle tier)
$.ajax({
url: '/echo/json/', //Replace with your URL to return Database data (JSON format)
dataType: 'json',
type: 'get',
success: function(data){
//Use the returned data to pass into CreateDropDown (Hard coded for an example)
CreateDropDown(["Item 1", "Item 2", "Item 3"]);
}
});
});
function CreateDropDown(data){
var $newSelect = $('<select />');
$.each(data, function(i, val){
$newSelect.append($('<option />', {
'text':val
}));
});
$newSelect.appendTo('#dropDowns');
}
​
​
HTML
<div id='dropDowns'>
<select>
<option>Item 1</option>
<option>Item 2</option>
<option>Item 3</option>
</select>
</div>
<input type='button' id='btnAdd' value="Add" />​
EDIT
You should also read up on jQuery's AJAX method
any ideas with jquery? jquery clone() will help you to solve this problem
JQuery .clone()
A LIVE EXAMPLE : http://jsfiddle.net/laupkram/6LBNs/
in the case of your problem try to study this one
Dynamic Loading of ComboBox using jQuery and Ajax

Categories