I have a page which displays All Test Events on default (Initial Page View)
My controller:
public function testController()
{
$category = 0; //NEED TO BE CHANGED WHEN USER SELECTED TEST EVENT 2 AND GET ALL EVENTS (Category 2)
$getEventsBasedOnCategory = //DB QUERY TO GET ALL EVENTS (Category 0)
//Pass all events to view
}
My HTML page:
<select id = "event_filter">
<option value="" selected="selected" disabled>SELECT Event</option>
<option value="0">All Test Events</option>
<option value="2">Test Event 2</option>
</select>
My ajax request:
$("#event_filter").change(function(){
$.ajax({
url: '/site/example/displayEvents',
data: {
event_filter: $("#event_filter").val()
},
async: false,
type: 'POST',
success: function(data){
},
});
});
My question is how am I going to change the category to 2 (if user selected 2 in select box) and request again from the database and display the events with category 2 on site?
Im using codeigniter by the way. Thanks
Thanks, Sorry for bothering you guys.
Sorry for my bad English.
First of all, to retrieve data from post in codeigniter use $this->input->post('event_filter').
If you are calling '/site/example/displayEvents', in this function "displayEvents" you have to call the function in the model.
public function displayEvents(){
$data->variableToSend = $this->example_model->events_data($this->input->post('event_filter'));
$this->load->view('nameOfViewToDisplayData',$data);
}
The view is the result in your ajax call, then you can put it in a div.
success: function(data){
$('#target_div').html(data);
},
When you're using type: POST, this will post it to the next site :-)
The way i understand your question, you need the $category to be equal to the value of your select.
I havent testet you script, but they way you do it:
$category = 0;
if(isset($_POST['event_filter'])){
$category = $_POST['event_filter'];
}
and then just a simple
"SELECT * FROM {your category} WHERE {your_row_category} = $categori"
Related
Im using TomSelect to control my <select> UI for my dependent select dropdowns.
The <option>...</option> list of the To dropdown depends on the From dropdown and is updated per ajax call on the selection in the From dropdown. The first initialization works fine on both dropdowns. Unfortunately, after repeating the ajax request through selecting another location on the From dropdown results in the following error:
Uncaught Error: Tom Select already initialized on this element
What i did so far:
1. On page load i'm initializing TomSelect on the From dropdown with:
tsfrom = new TomSelect('#from-select-field',ttddssettings);
The relevant lines of code:
<select id="from-select-field" name="from" onchange="getTo();">
<option value='0'>Choose...</option>
</select>
<select id="to-select-field" name="from">
<option value='0'>Select From first</option>
</select>
<script>
jQuery(document).ready(function($) {
var tsfrom;
var ttddssettings = {
plugins: ['dropdown_input'],
};
tsfrom = new TomSelect('#from-select-field',ttddssettings);
var totoval = "xymydomain.com/get-to-options.php";
getTo = function () {
var fromvalue = $("#from-select-field").val();
var tovalue = $("#to-select-field").val();
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
},
});
}
});
</script>
The relevant lines of code inside the requested PHP file:
<?php
$sql_to = "SELECT * FROM locations WHERE ..... ORDER by names ASC";
$quer_to = $pdo_conn->prepare($sql_to);
$quer_to->execute();
$fetch_to_values = $quer_to->fetchAll();
foreach ( $fetch_to_values as $tovalues ) {
?>
<option value="<?php echo $tovalue['name']; ?>" <?php if ( $tovalue['name'] == $to) { echo "selected";} ?>><?php echo $tovalue['name']; ?></option>
<?php } ?>
<script>
jQuery(document).ready(function($) {
var tsto;
var tttossettings = {
plugins: ['dropdown_input'],
};
tsto = new TomSelect('#to-select-field',tttossettings);
});
</script>
2. After selcting a From location the To dropdown gets populated per ajax. The requested file (see above) through ajax url: includes also the following code to initialize TomSelect on the To dropdown:
tsto = new TomSelect('#to-select-field',tttossettings);
So far everything works fine.
3. THE PROBLEM:
As mentioned before, after repeatedly selecting a different location on the From dropdown i get the error Tom Select already initialized on this element.
The TomSelect DOCS mentioning refreshOptions(triggerDropdown) (Refreshes the list of available options shown in the autocomplete dropdown menu.). Unfortunately I have no idea if this is the right approach or how to fix this. Any help would be greatly appreciated.
Two changes should get rid of the error:
Remove script block from PHP page:
Get rid of the <script> block in your PHP file and only return the <option>...</option> values. This is also messy as you are setting the HTML of the <select> to be what the PHP code has generated, including the returned script block.
Trigger updating the drop down in the AJAX success block
$.ajax({
type: "POST",
url: totoval,
data: {
from: fromvalue,
to: tovalue,
},
success: function(data) {
$("#to-select-field").html(data);
tsto.clear(); // unselect previously selected elements
tsto.clearOptions(); // remove existing options
tsto.sync(); // synchronise with the underlying SELECT
},
});
Using the sync method should update the styled dropdown options based on the underlying <select>.
Alternatively, calling tsfrom.refreshOptions(); instead of sync() could also work.
I have a list of options inside a 'select' tag. For whichever option is selected, an 'onchange' function will be activated which carries on the value of that option. A function which activated will use Ajax to call to a controller to get a list of data that I can store into my others 'select' tag. How can I achieve this?
My HTML:
<select id="category-select" onchange="GetEmployee()">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
My JS:
function GetEmployee() {
var MaNguoiDung = 120;
var MaThuMuc = document.getElementById("category-select").value;
$('#employeeDisplay').change(function () {
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien?MaNguoiDung=" + MaNguoiDung + "&MaThuMuc=" + MaThuMuc,
success: function () {
alert('Get Success');
}
});
});
}
The alert was only to test if my ajax can run or not. Apparently, it can't. Also, I need to know how to stored query data into the second 'select'. Like after the URL attribute, I don't know what to write next after that. Sorry but I'm completely new in Ajax. Some referencing and tutorial online mostly shown how to load ajax into the table. There might be more but table is the only thing I can find so I'm very in need of a way to store it into select.
Edit: This is the response data I receive from my Controller
Sample JSON
You have several problems with the code shown.
The <select> you have the onchange in is not the same one you target to get value inside the function.
You are creating a new change event inside the function called by onchange. That new jQuery change() won't fire until next time you edit the <select>
You are manually creating the url query string but also providing a data object. Internally jQuery takes that object and will add it to the query string you manually created, effectively duplicating the parameters
So, lets get rid of the onchange , give the <select> an id and fix the query string in the ajax. Also you want an error handler to help troubleshooting
As for how to handle the response will need to see a sample of it first
HTML
<select id="category-select">
<option value="0" selected>ALL CATEGORY</option>
<option value="144">Food Category</option>
<option value="177">Music Category</option>
</select>
<select id="employeeDisplay" multiple>
</select>
JS
$(function () {
$('#category-select').change(function () {
var category = this.value;
// I don't know which variable is which in `data`
var MaNguoiDung = 120;// is this category ???
var MaThuMuc = null // confused where this comes from because other select is empty
$.ajax({
type: "GET",
dataType: "json",
data: {
"MaNguoiDung": MaNguoiDung,
"MaThuMuc": MaThuMuc
},
url: "/get-nhan-vien",
success: function (response) {
// ^^ missing argument needed to receive the data
console.log(response)// log it to console for now
alert('Get Success');
},
error: function(xhr, status, message){
console.log('Status: ', status, ', Message: ', message)
}
});
});
});
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 have a Wordpress site with 2 dropdown boxes. When I select an option in the first dropdown box I want the 2nd one to be refreshed with data from a PHP function. For that I need ajax. But I'm struggling with binding ajax into Wordpress.
The HTML looks like this:
<form method="get" action="http://siradjov.anex.at/playground/">
<div class="form-inner">
<div class="listing-search-main">
<input type="text" class="listing-search-text text" name="s" title="Coach House, Golf Course, Water View, etc" value="unique">
<input type="submit" class="listing-search-submit btn btn-large btn-primary" name="search-submit" value="Search">
</div><!-- .listing-search-main -->
<div class="listing-search-details">
<div class="listing-search-field listing-search-field-select listing-search-field-status">
<select class="listing-search-status select" name="status">
<option value="">Status</option>
<option value="sale">Sales</option>
<option value="rent">Rentals</option>
<option value="foreclosure">Foreclosure</option>
</select>
<div class="listing-search-advanced " style="display: block;">
<div class="listing-search-field listing-search-field-select listing-search-field-min">
<select class="listing-search-min select" name="min">
<option value="">Price (min)</option>
<option value="100000">100.000</option>
<option value="200000">200.000</option>
<option value="300000">300.000</option>
<option value="400000">400.000</option>
</select>
Now when for example the user selects "Sales" I want the second select tag to be reloaded with the matching prices from a PHP array.
The PHP function looks like this:
<?php
$selectedStatus = $_POST['status'];
if($selectedStatus == "sale")
{
// Set price (min) to select
$fields['min']['type'] = 'select';
// Set price (min) select options
$fields['min']['data'] = array(
'100000' => '120,000',
'120000' => '200.000',
'130000' => '300.000',
);
// Set price (max) to select
$fields['max']['type'] = 'select';
// Set price (max) select options
$fields['max']['data'] = array(
'100000' => '120,000',
'120000' => '200.000',
'130000' => '300.000',
);
}
else if($selectedStatus == "rent")
{
// Set price (min) to select
$fields['min']['type'] = 'select';
// Set price (min) select options
$fields['min']['data'] = array(
'200' => '200',
);
// Set price (max) to select
$fields['max']['type'] = 'select';
// Set price (max) select options
$fields['max']['data'] = array(
'200' => '200',
);
}
echo $fields;
I've save my jQuery Ajax call in a separate .js file. The code is the following:
jQuery(document).ready(function() {
jQuery(".listing-search-status.select[name='status']").change(function() {
if (this.value == "sale")
{
jQuery.ajax({
type: "POST",
url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
data: { status : "sale" },
success: function(data)
{
alert('Sale' + data['min']['data'][0]);
}
});
}
else
{
if (this.value == "rent")
{
jQuery.ajax({
type: "POST",
url: "http://siradjov.anex.at/playground/wp-content/plugins/wpcasa-extended-search-status-price-chain-select/wpcasa_custom_prices.php",
data: { status : "rent" },
success: function(data)
{
alert('Rent' + data['min']['data'][0]);
}
});
}
}
});
});
But the alert Boxes don't show up. Neither do I get any error messages on Google Chrome's Console. Can anyone help me?
Use the native methods that Wordpress provides to you to leverage ajax requests.
In your plugin file, we need to add a couple actions so that we can send ajax requests through and have them parsed by the admin-ajax.php file.
add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
add_action('wp_ajax_ajax_request', 'ajax_controller');
Now we build out an ajax controller in our plugin file. The purpose of this is to act as a controller that will switch it's output based on the FN parameter supplied by the ajax request (more on this later)
function ajax_controller(){
$ret = ''; //our return variable
switch($_REQUEST['fn']):
case 'status' :
$ret = update_status($_REQUEST['status']);
break;
endswitch;
echo $ret;
die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
}
Please note that the update_status() function was created to encapsulate your above php code.
Now we have the actions bound, and a controller that we can use endlessly to retrieve data. We just need to make a couple modifications to the ajax call. First, we can use ternary assignment for the 'rent/sale' switch, as opposed to 2 ajax calls, which will clean things up. Second, we need to change the url address to the /wp-admin/admin-ajax.php file.
var $status = (this.value == "sale") ? this.value : 'rent';
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'ajax_request',
fn : 'status', //this is the $_REQUEST['fn'] from above
status : $status },
success: function(data){
alert('Sale' + data['min']['data'][0]);
}
});
The action parameter is required, the fn is a result of my coding principles. The action attribute must directly match what comes after add_action('wp_ajax_nopriv_ and add_action('wp_ajax_.
This should resolve it.