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.
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 country, state and city chained dropdown which loads a state depending on the country and loads the cities depending on the state. The code works perfectly fine on my local server but when pushing to the live one, the dropdown is not functioning correctly, for example in some cases it works fine for all 3 but for some cases it just does not load anything and in the console I am seeing a simple false and nothing else.
Here is the JS:
$(document).ready(function() {
var country_id = localStorage.getItem("select2CountryValue");
var state_id = localStorage.getItem("select2StateValue");
var page_load = true; //added this
// Triggering the deleteLocalStorage function in case the client is not
// created and the back button is clicked
$('.del-ls').click(function() {
deleteLocalStorage();
});
// This function is also called by PHP using script tags when the create
// client form is successfully submitted
function deleteLocalStorage() {
var country_id = localStorage.getItem("select2CountryValue");
var state_id = localStorage.getItem("select2StateValue");
localStorage.removeItem('select2CountryValue');
localStorage.removeItem('select2StateValue');
}
//$('.csc-select').select2();
$('#country').select2({
placeholder: 'Select Country'
});
$('#state').select2({
placeholder: 'Select State/Region'
});
$('#city').select2({
placeholder: 'Select City'
});
$('select[name="country"]').on('change',function() {
var country_id= $(this).val();
localStorage.setItem("select2CountryValue", country_id);
if (country_id) {
$.ajax({
url: "/src/Pages/world/getStates.php",
type: "GET",
data: {'country_id':country_id},
dataType: "json",
success: function(data) {
console.log(data);
$('select[name="state"]').empty();
$('select[name="state"]').append('<option value="">Select State</option>');
$.each(JSON.parse(data), function(key,value) {
$('select[name="state"]').append('<option value="'+value.id+'">'+value.name+'</option>');
});
//check if the change is called on page load
if (page_load == true) {
$('#state').val(state_id).trigger('change'); //assign slected value after element option is added in dom
page_load = false; //adding this so that next time this doesn't get execute
}
}
});
} else {
$('select[name="state"]').empty();
}
});
$('#country').val(country_id).trigger('change');
$('select[name="state"]').on('change',function() {
var country_id = $('#country').val();
var state_id = $(this).val();
localStorage.setItem("select2StateValue", state_id);
if (state_id) {
$.ajax({
url: "/src/Pages/world/getCities.php",
type: "GET",
data: {'country_id': country_id, 'state_id': state_id},
dataType: "json",
success: function(data) {
console.log(data);
$('select[name="city"]').empty();
$('select[name="city"]').append('<option value="">Select City</option>');
$.each(JSON.parse(data),function(key,value) {
$('select[name="city"]').append('<option value="'+value.id+'">'+value.name+'</option>');
});
}
});
} else {
$('select[name="city"]').empty();
}
});
});
And this is the HTML and just a some simple PHP to load the countries which is working fine:
<p>
<span>Country</span>
<select class="csc-select" name="country" id="country">
<option value="">Select Country</option>
<?php foreach($countries as $country) { ?>
<option value="<?php echo $country[$columnName['COLUMN_NAME']]; ?>"
>
<?php echo $country['name']; ?>
</option>
<?php } ?>
</select>
</p>
<p>
<span>State</span>
<select class="csc-select" name="state" id="state">
<option value="">Select State</option>
</select>
</p>
<p>
<span>City</span>
<select class="csc-select" name="city" id="city">
<option value="">Select City</option>
</select>
</p>
I am a bit clueless now since locally it works perfectly however on the live server it doesn't work for every option you pick, I rechecked the countries, states and cities database and all the info is there so its not missing, the database is identical to the one I am using in the local version too. If anyone has any idea or suggestions, I would appreciate it a lot.
And here is the console log error that appears sometimes:
> Uncaught SyntaxError: Unexpected end of JSON input
> at JSON.parse (<anonymous>)
> at Object.success (add:977:29)
> at c (jquery-3.6.0.min.js:2:28327)
> at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
> at l (jquery-3.6.0.min.js:2:79901)
> at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)
and now I am adding a screenshot of the console.log, this happens when I choose the country United States, the state Caliornia, so it does not show anything for California but it should:
Here is the getStates.php file code:
<?php
use App\Session;
use App\Login;
use App\Location;
require_once("../../../vendor/autoload.php");
$objSession = new Session();
if(!$objSession->isLogged()) {
Login::redirectTo("/login");
}
$country_id = $_GET['country_id'];
if(isset($_GET['country_id'])) {
$objLocation = new Location();
echo json_encode($getStates = $objLocation->getStates($country_id));
}
and here is the getCities.php file code:
<?php
use App\Session;
use App\Login;
use App\Location;
require_once("../../../vendor/autoload.php");
$objSession = new Session();
if(!$objSession->isLogged()) {
Login::redirectTo("/login");
}
$state_id = $_GET['state_id'];
$country_id = $_GET['country_id'];
if(isset($_GET['state_id']) && isset($_GET['country_id'])) {
$objLocation = new Location();
echo json_encode($getCities = $objLocation->getCities($state_id, $country_id));
}
and this is the code in the Location class that fetches the data:
public function getStates(string $id): ?string
{
$sql = "SELECT `id`, `name` FROM {$this->table_3}
WHERE `country_id` = '". $this->escape($id) ."'
ORDER BY `name` ASC";
$result = $this->fetchAll($sql);
return json_encode($result);
}
public function getCities(string $state, string $country): bool|string
{
$sql = "SELECT `id`, `name` FROM {$this->table_4}
WHERE `state_id` = '". $this->escape($state) ."'
AND `country_id` = '". $this->escape($country) ."'
ORDER BY `name` ASC";
$result = $this->fetchAll($sql);
return json_encode($result);
}
So, I have asked on the comments and you have provided... here is what I think is happening... and what I think you should do.
your method getCities on the Location::class is returning a boolean... and sometimes a string...
json_encode will only return false on failure, this means json_encode has failed on encoding your sql result...
you can use json_last_error() and json_last_error_msg() to debug your json_encode() problem
you can find the documentation here
You can debug your problem on Local but, please make sure your local machine is running the same things on the live server, to replicate the error...
PHP version
Database Data
MySql Version (But I don't think it's necessary)
Browser (but just for testing, app should work on all browser)
if you can't replicate the error, you need to do it LIVE. (please be very careful, this should be your LAST RESORT)
I could not provide a specific answer because I don't know if $this->fetchAll() only returns an array or maybe sometimes it returns an error message...
I have provided you this answer, because your main concern on this question is why your program returning a simple false value...
for example in some cases it works fine for all 3 but for some cases it just does not load anything and in the console I am seeing a simple false and nothing else.
Hi I think it could be the $.ajax AND the echo json_decode the issue....
I made my own AJAX function that I share in github https://github.com/jintor/stubajax
async function stubajax (divid,phphat,postix = [],pend = 'html') {
var pcache = (Math.floor(Math.random() * 100000000) + 1);
postix["preventcache"] = pcache; // prevent browser caching
postix["divid"] = encodeURIComponent(divid);
postix["mojax_height"] = encodeURIComponent($(window).height());
postix["mojax_width"] = encodeURIComponent($(window).width());
// if you need to send cookies
postix["cookies"] = decodeURIComponent(document.cookie);
// if you need to send localStorage or sessionStorage stuff
for (var i = 0; i < localStorage.length; i++){ postix[localStorage.key(i)] = localStorage.getItem(localStorage.key(i)); }
for (var i = 0; i < sessionStorage.length; i++){ postix[sessionStorage.key(i)] = sessionStorage.getItem(sessionStorage.key(i)); }
await fetch(phphat+"?pcache="+pcache, {
method: "POST", body: JSON.stringify(Object.assign({}, postix)), headers: {"Content-type": "application/json; charset=UTF-8"}
}).then( response => { return response.text(); }).then( html => {
switch ( pend ){
case 'append' : $("#"+divid).append(html); break;
case 'prepend' : $("#"+divid).prepend(html); break;
default : $("#"+divid).html(html); break;
}
}).catch( err => console.log(err) );
}
AND YOU USE IT LIKE THIS
<input onchange="stubajax (\'div_id_that_will_reseive_the_ajax_message\',\'/path/to_php.php\',{\'extra1\':this.value},'html');
On the PHP side :
a the end simply echo (WITHOUT json_encode)....
So I am adding the solution which #SeanReyes led me to.
Actually it led me to 2 solutions, and they are:
Solution 1. I could simply do an if condition in my Location::class to check if the json_encode is working correctly and if not simply add a JSON flag like so (JSON_INVALID_UTF8_IGNORE or JSON_INVALID_UTF8_SUBSTITUTE):
public function getStates(string $id): ?string
{
$sql = "SELECT `id`, `name` FROM {$this->table_3}
WHERE `country_id` = '". $this->escape($id) ."'
ORDER BY `name` ASC";
$result = $this->fetchAll($sql);
if(json_encode($result)) {
return json_encode($result);
} else {
return json_encode($result, JSON_INVALID_UTF8_IGNORE);
}
}
and did the same with the getCities method.
Solution 2. While this did fix it, it displayed the latin characters incorrectly and so that made me find another easy solution by simply adding a charset to my mysqli connection like so:
$this->db->set_charset("utf8mb4");
and like magic everything worked perfectly, but this was a rookie mistake on my end as this should of been set anyway, thanks to everyone for pointing me in the right direction.
I am trying to populate the drop down using Chosen plugin for multiple select.
I have added the fiddle
http://jsfiddle.net/san1234/ymnj12xk/
My intention is to populate the "options" tag in the "select" tag, basing on JSON data obtained by sending user typed letter via the Ajax call.
For this I need to know, how to make an ajax call onkeyup i.e. if the user typed "Am", i want to send that input to an Ajax call and get the JSON response, something like ["America","Amsterdam"]
I'm new to this and I cant figure out a way to extract the user typed input in the 'select' box to actually send it as request in an Ajax call.
I have tried doing this but 'autocomplete' method in the JS file doesn't work
How do i do this? kindly help!
JS file
$(".chosen-select").chosen();
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
$('.chosen-choices input').autocomplete({
source: function(request, response) {
$.ajax({
url: "/someURL/" + request.term + "/",
dataType: "json",
beforeSend: function() {
$('ul.chosen-results').empty();
},
success: function(data) {
alert("Success!");
response($.map(data, function(item) {
$('ul.chosen-results').append('<li class="active-result">' + item.name + '</li>');
}));
}
});
}
});
<link href="http://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<select class="chosen chosen-select" multiple="" data-placeholder="Choose a Country" style="width:200px">
<option value="America">America</option>
<option value="Amsterdam">Amsterdam</option>
<option value="Australia">Australia</option>
<option value="Dallas">Dallas</option>
<option value="GHI">hij</option>
</select>
I dont know if you are using PHP in your back end or any other program language but here's my solution using php and javascript :
First your javaScript:
//initialization of chosen select
$(".chosen-select").chosen({
search_contains: true // an option to search between words
});
$(".chosen-select-deselect").chosen({
allow_single_deselect: true
});
//ajax function to search a new value to the dropdown list
function _ajaxSearch (param){
return $.ajax({
url: "request.php",
type: "POST",
dataType: "json",
data: {param:param}
})
}
//key event to call our ajax call
$(".chosen-choices input").on('keyup',function(){
var param = $('.chosen-choices input').val();// get the pressed key
_ajaxSearch(param)
.done(function(response){
var exists; // variable that returns a true if the value already exists in our dropdown list
$.each(response,function(index, el) { //loop to check if the value exists inside the list
$('#mySelect option').each(function(){
if (this.value == el.key) {
exists = true;
}
});
if (!exists) {// if the value does not exists, added it to the list
$("#mySelect").append("<option value="+el.key+">"+el.value+"</option>");
var ChosenInputValue = $('.chosen-choices input').val();//get the current value of the search
$("#mySelect").trigger("chosen:updated");//update the list
$('.chosen-choices input').val(ChosenInputValue);//since the update method reset the input fill the input with the value already typed
}
});
})
})
your php file:
if (isset($_POST["param"])) {// check is the param is set
$param = $_POST["param"]; // get the value of the param
$array = array('JKL' => 'jkl' , 'MNO'=>'mno', 'PQR'=>'pqr','STU'=>'stu','VWX'=>'vwx','YZ'=>'yz' );//array of values
$matches = array();//array of matches
foreach($array as $key=>$value){//loop to check the values
//check for match.
if(strpos($value, $param) !== false){
//add to matches array.
$matches[]= array ("key"=> $key,"value"=>$value);
}
}
//send the response using json format
echo json_encode($matches);
}
Hope it helps
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 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"