Magento: Hide/Show input field based on Selected Country - javascript

I would like to hide/show || disable/enable an input field based on the selected country in magento checkout page. I tried this code separated from magento and it's working perfectly but when I applied it in my magento, it's not working. I just edited the billing.phtml from IWD checkout extension and nothing from magento core.
here is the javascript:
$(function() {
var $cid = $(document.getElementById("billing:country_id")), // Country ID in magento
$custom = $(document.getElementById("billing:custom")); //my custom input field
$cid.change(function() {
if ($cid.val() == 'US') {
$custom.removeAttr('disabled');
alert('working1');
} else {
$custom.attr('disabled', 'disabled').val('');
alert('working2');
}
}).trigger('change');
});
Here's the sample billing form template from IWD / Magento:
<li class="fields">
<label for="billing:country_id" class="required"><em>*</em><?php echo $this->__('Country') ?></label>
<div class="input-box">
<?php echo $this->getCountryHtmlSelect('billing') ?>
</div>
</li>
<li class="fields">
<label for="billing:custom" class="required"><em>*</em><?php echo $this->__('Custom Field') ?></label>
<div class="input-box">
<input type="text" name="custom[custom]" value="<?php echo $this->htmlEscape($this->getQuote()->getCustom()) ?>" title="<?php echo $this->__('Custom Field') ?>" class="input-text custom_id" id="billing:custom" />
</div>
</li>
Country Select getCountryHtmlSelect function is a built-in mage function:
public function getCountryHtmlSelect($type)
{
$countryId = $this->getAddress()->getCountryId();
if (is_null($countryId)) {
$countryId = Mage::helper('core')->getDefaultCountry();
}
$select = $this->getLayout()->createBlock('core/html_select')
->setName($type.'[country_id]')
->setId($type.':country_id')
->setTitle(Mage::helper('checkout')->__('Country'))
->setClass('validate-select')
->setValue($countryId)
->setOptions($this->getCountryOptions());
if ($type === 'shipping') {
$select->setExtraParams('onchange="if(window.shipping)shipping.setSameAsBilling(false);"');
}
return $select->getHtml();
}

<input id="billing:country_id"></input>
<input id="billing:custom" disabled="disabled;"></input>
code
$(function() {
var $cid = $(document.getElementById("billing:country_id"));
$custom = $(document.getElementById("billing:custom"));
$cid.change(function() {
if ($cid.val() == 'US') {
$custom.prop('disabled', false);
console.log('working1');
} else {
$custom.prop('disabled', true).val("");
console.log('working2');
}
}).trigger('change');
});
http://codepen.io/anon/pen/dMqYgK?editors=1011

Related

AJAX form with e.preventDefault(); redirects to the PHP file

When I click the button to submit the form it sends me to the PHP file (Php/modify-recipes.php). I'm using AJAX with e.preventDefault();, but it doesn't seem to work. I have a similar form on my other page and it works fine. This one is a little bit different, the form is generated from another PHP file (it takes values from the database).
// AJAX (in HTML head tag)
<script>
$(function () {
$("#search-form").on('click', 'p.product', function(e){
var product = $(this).attr('id');
e.preventDefault();
$.ajax({
type: "post",
url: 'Php/display-modify-recipes.php',
data: { "id": product },
success: function(response) {
$(".modify-recipes").html(response);
$(".search-results").html("");
}
});
}
)});
$(function () {
$('#add_recipes_form').on('click', '#add', function (e) {
e.preventDefault();
let sendForm = true;
$('.required').each(function(){
if ($(this).val() == ''){
$(this).addClass('error', 4000);
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error', 4000);
sendForm = false;
} else {
$(this).removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
$('.required2').each(function(){
if ($(this).val() == ''){
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error');
$('#file_style').addClass('error');
sendForm = false;
} else {
$('#file_style').removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
if (sendForm) {
$.ajax({
type: "post",
url: 'Php/modify-recipes.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
},
error: function () {
}
});
}
});
});
</script>
// HTML
<form method="POST" enctype='multipart/form-data' id="search-form" class="aaa">
<input type="text" name="search-bar" class="search-bar" placeholder="Search">
<div class="search-results"></div>
</form>
<div class="modify-recipes"></div>
// Php/display-modify-recipes.php
<?php
function display_mod_form(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = $_POST["id"];
$sql = "SELECT * FROM product WHERE id = '$product'";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$type = $row['type'];
$difficulty = $row['difficulty'];
$image = $row['image'];
?>
<form method="POST" action="Php/modify-recipes.php" enctype="multipart/form-data" id="add_recipes_form" class="add-form">
<input type="text" name="id" id="<?php echo $id ?>" value="<?php echo $id ?>" style="display:none;">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="required" maxlength="28" value='<?php echo $name ?>'>
<label for="description">Desc.</label>
<input type="text" name="description" id="description" class="required" maxlength="128" value='<?php echo $description ?>'>
<label for="type">Type</label>
<select name="type" class="required">
<option value="dishes" <?php if($type == 'dishes') {echo "selected=selected"; } ?>>
Dishes
</option>
<option value="desserts" <?php if($type == 'desserts') {echo "selected=selected"; } ?>>
Desserts
</option>
<option value="snacks" <?php if($type == 'snacks') {echo "selected=selected"; } ?>>
Snacks
</option>
<option value="other" <?php if($type == 'other') {echo "selected=selected"; } ?>>
Other
</option>
</select>
<label for="difficulty">Difficulty</label>
<select name="difficulty" class="required">
<option value="easy" <?php if($difficulty == 'easy') {echo "selected=selected"; } ?>>
Ease
</option>
<option value="moderate" <?php if($difficulty == 'moderate') {echo "selected=selected"; } ?>>
Moderate
</option>
<option value="hard" <?php if($difficulty == 'hard') {echo "selected=selected"; } ?>>
Hard
</option>
</select>
<label for="image">Image (jpg, png)</label>
<label for="upload_image" id="file_style">Choose image</label>
<input type="file" style="display:none;" id="upload_image" name="image" accept="image/*" onchange="loadFile(event)" class="required2">
<div class="send-btn">
<p id="placeholder-text"></p>
<input type="submit" name="add" id="add" value="Send">
<div class="send-block"></div>
</div>
</form>
<?php
}
mysqli_close($con);
}
display_mod_form();
?>
// Php/modify-recipes.php
<?php
$con = mysqli_connect("localhost", "root", "", "cookbook");
$id = $_POST["id"];
$name = $_POST["name"];
$description = $_POST["description"];
$type = $_POST["type"];
$difficulty = $_POST["difficulty"];
if ($_FILES['image']['name'] == ""){
$sql_var = "SELECT image FROM product where id = '$id'";
$var = mysqli_query($con,$sql_var);
while($row = mysqli_fetch_assoc($var)) {
$image = $row['image'];
}
} else {
$image = $_FILES['image']['name'];
}
$sql = "
UPDATE product SET
name = '$name',
description = '$description',
type = '$type',
difficulty = '$difficulty',
image = '$image',
last_mod_date = '$mod_date'
WHERE id = '$id';
";
$target = "../Uploads/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
}
$var = mysqli_multi_query($con,$sql); <!-- There are more queries -->
mysqli_close($con);
?>
(Sorry for any mistakes, it's a shortened version)
There is a third ajax function and PHP file, but it's not important (simple search bar). I tried other things like action="", no action at all, etc., but it didn't work.
How to fix this?
Edit: There is only one form (when you click on p.product it displays the form according to the data in the database). The problem occurs ONLY when I'm submitting the "add_recipes_form", there is no problem with the search box. Please don't mark this question as a duplicate of a 10 year old post that is irrelevant to my problem.

manipulate dynamic input with php mysql and js

I have a table named description:
CREATE TABLE description(
word_id int(11),
word varchar (50),
PRIMARY KEY (word_id)
);
and I try to get all word in this table and for every word I create a checkbox with value and id equal at a value of the word that I get from table description,
if the checkbox is checked, I save his value in var abcd.
<?php
///connection
$get_word = $bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<br>
<script>
$('#<?php $donnees["word"] ?>').on('change', function() {
var abcd= this.checked ? this.value : '';
});
</script>
<?php
}
?>
Now, I want to create a button out of boocle while , if this button is clicked,it must give me the value of checkbox checked.
Here's how you could do it using jQuery. As you already have the PHP logic, my example demonstrates the jQuery code only:
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
console.log($(el).val())
})
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" value="Item 1">Item 1
<input type="checkbox" value="Item 2">Item 2
<input type="checkbox" value="Item 3">Item 3
<button id="getCheckedBoxes">Get checked boxes</button>
hope this will solve your problem
PHP code
<?php
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
JS CODE
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
var check_val = document.getElementById('myid_'+word).value;
alert(check_val);
}
}
</script>
or you can do this
<script>
function myfunc(word){
if(document.getElementById('myid_'+word).checked == true){
alert(word);
}
}
</script>
add class name such as clickable to your input tag.
after all rendering in php add script that runs when any input with clickable class changed and you can get that tag!
<?php
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) { ?>
<input class="clickable" type="checkbox" id="<?php $donnees["word"] ?>" value="<?php $donnees["word"] ?>">
<?php } ?>
<script>
$('.clickable').on('change', function(item) {
console.log(item)
});
</script>
I try this
///connection
$get_word=$bdd->query("SELECT * FROM description");
while ($donnees = $get_word->fetch()) {
?>
<label><?php echo $donnees["word"] ?></label>
<input type="checkbox" id="myid_<?php $donnees["word"] ?>" onclick="myfunc(<?php $donnees["word"] ?>)" value="<?php $donnees["word"] ?>"><br>
<?php
}
?>
<button id="getCheckedBoxes">Get checked boxes</button>
<script type="text/javascript">
$(document).ready(function() {
'use strict';
$("#getCheckedBoxes").on('click', () => {
$('input[type="checkbox"]').each(function(i, el){
if($(el).is(':checked'))
alert($(el).val()) ;
})
})
})
</script>
And the alert message is empty,it don't show the value of checkbox chekced

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

How to check if a radio button is clicked?

My code looks like this:
form action="familytree.php" method="post">
<?php
foreach ($spouses as $spouse) {
if (!empty($spouse['mname'])) {
$name = $spouse['fname'].' '.$spouse['lname'].' ('.$spouse['mname'].')';
}
else {
$name = $spouse['fname'].' '.$spouse['lname'];
}
if ($spouse['ended'] == '1') {
$married = '';
$divorced = 'checked';
}
else {
$married = 'checked';
$divorced = '';
}
?>
<div class="form_section dates">
<h3><?php echo $name; ?></h3>
<p>
<input type="radio" id="married_option" name="married_divorced_options" <?php echo $married; ?> value="1"/>
<label for="edate">Married</label>
<input type="radio" id="divorced_option" name="married_divorced_options" <?php echo $divorced; ?> value="1"/>
<label for="sdate">Divorced</label>
</p>
<div class="half" style="display: inline">
<input type="text" name="sdate_<?php echo $spouse['individual_id']?>" id="sdate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['start_date']; ?>" placeholder="Rašykite sutuoktuvių datą čia"/>
<?php echo $this->formError->error("sdate_".$spouse['individual_id'].""); ?>
</div>
<div id="divorced" class="half" style="display:none">
<input type="text" name="edate_<?php echo $spouse['individual_id']?>" id="edate_<?php echo $spouse['individual_id']?>" value="<?php echo $spouse['end_date']; ?>" placeholder="Rašykite skyrybų datą čia"/>
<?php echo $this->formError->error("edate_".$spouse['individual_id'].""); ?>
</div>
</div>
<?php
}
?>
<p class="submit">
<input class="first-btn" type="submit" id="edit-relationship" name="edit-relationship" value="Edit"/>
</p>
</form>
jQuery("#divorced_option").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("#married_option").click(function() {
document.getElementById("divorced").style.display = "none";
});
What I would like to know is how to check if a radio button is clicked when you don't know its full name, only half of it. For example, #divorced_option is not full name, it should be something like this #divorced_option_161, #divorced_option_161... So, the code should check if the radio button that has divorced_option in its name is clicked. Is there a way to achieve this?
EDIT
It works with jQuery("[id^='married_option']").click(function(){}). But I forgot to mention in my original question that the element divorced isn't full name as well, it should be divorced_161, divorced_162, depending of the name of the radio button that is clicked. How can I hide the element that matches with the radio button?
Use the attribute starts with selector (ex. [name^="value"]):
jQuery("[id^='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id^='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
Have a look at the jQuery selectors.
The 'Attribute Contains' selector would be useful here, which means your code would be :
jQuery("[id*='divorced_option']").click(function() {
document.getElementById("divorced").style.display = "inline-block";
});
jQuery("[id*='married_option']").click(function() {
document.getElementById("divorced").style.display = "none";
});
You can select the elements based on the #divorced_option_[number] pattern while checking if they are selected like this:
$("input[id*=divorced_option]:checked");
If you would like to check wether the divorced_option substring is in the name="" attribute of the radio element, then change the id from the selector to name, like so:
$("input[name*=divorced_option]:checked");
After this, just check wether or not jQuery returned an actual element.

Pass form variables to php. Prevent page refresh

I am working on a web site which displays some data that is retrieved from a database using php. Now, there are also other chekcboxes, which are included in a form. Based on the user input on these checkboxes, i wanted the div displaying the data to reload. For example, after a user checks one of the boxes and clicks apply, the div displaying should recompute the results. I realise that the form data must be passed onto an ajax function. Which would convert this form data into a json object and send it across to a php file. The php file can then access the form variables using $_POST['var']. I hope i have got the theory correct. Nevertheless, i have a number of problems during execution.
Firstly, the php code that deals with the form variables in on the same page as the form. I want to know how to direct the form data from the ajax function to this code.
Secondly, the ajax function is getting executed alright, the form is getting submitted, the page isn't reloading (as desired) but however, I am not able to access the submitted variables in the php code.
Here is my code:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('#filter_form').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
});
});
</script>
<div style="float: left;margin-left: -175px;" class="box2">
<h2>Filter by :</h2>
<form id="filter_form" name="filter_form" href="#">
<!--<form id="filter_form" name="filter_form" action="<?php echo $_SERVER['PHP_SELF'];?>" method ="post" href="#">-->
<h3>Location</h3>
<?php
//Get all the distinct values for filter. For example, Get all the locations available, display them in a container. Similarly for the party type as well. Connect to to the database once, get all these values,
//store them in arrays and use the arrays to display on screen.
$query = "Select LOCATION, PARTY_TYPE, GENRE, HAPPY_HOURS, OUTDOOR_ROOFTOP from venue_list order by HAPPY_HOURS";
$result = mysqli_query($con,$query);
$filter_array = array(5);
for($i=0; $i<5; $i++){
$filter_array[$i] = array();
}
while($row = mysqli_fetch_array($result)){
array_push($filter_array[0],$row['LOCATION']);
array_push($filter_array[1],$row['PARTY_TYPE']);
array_push($filter_array[2],$row['GENRE']);
array_push($filter_array[3],$row['HAPPY_HOURS']);
array_push($filter_array[4],$row['OUTDOOR_ROOFTOP']);
}
for($i=0; $i<5; $i++){
$filter_array[$i] = array_unique($filter_array[$i]);
}
?>
<ul>
<?php
foreach($filter_array[0] as $location){
?>
<li>
<input type="checkbox" id="f1" name="location[]" value="<?php echo $location?>" <?php if (isset($_POST['location'])){echo (in_array($location,$_POST['location']) ? 'checked' : '');}?>/>
<label for="f1"><?php echo $location?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Party Type</h3>
<ul>
<?php
foreach($filter_array[1] as $party_type){
?>
<li>
<input type="checkbox" id="f2" name="party_type[]" value="<?php echo $party_type?>" <?php if (isset($_POST['party_type'])){echo (in_array($party_type,$_POST['party_type']) ? 'checked' : '');}?>/>
<label for="f2"><?php echo $party_type?></label>
</li>
<?php
}
?>
</ul>
<br><h3>Genre</h3>
<ul>
<?php
foreach($filter_array[2] as $genre){
?>
<li>
<input type="checkbox" id="f3" name="genre[]" value="<?php echo $genre?>" <?php if (isset($_POST['genre'])){echo (in_array($genre,$_POST['genre']) ? 'checked' : '');}?>/>
<label for="f3"><?php echo $genre?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Happy Hours</h3>
<ul>
<?php
foreach($filter_array[3] as $happy_hours){
?>
<li>
<input type="checkbox" id="f4" name="happy_hours[]" value="<?php if($happy_hours){ echo $happy_hours;} else {echo "Dont Bother";} ?>" <?php if (isset($_POST['happy_hours'])){echo (in_array($happy_hours,$_POST['happy_hours']) ? 'checked' : '');}?>/>
<label for="f4"><?php echo $happy_hours?></label>
</li>
<?php
}
?>
</ul>
<br>
<h3>Outdoor/Rooftop</h3>
<ul>
<?php
foreach($filter_array[4] as $outdoor_rooftop){
?>
<li>
<input type="checkbox" id="f5" name="outdoor_rooftop[]" value="<?php echo $outdoor_rooftop?>" <?php if (isset($_POST['outdoor_rooftop'])){echo (in_array($location,$_POST['outdoor_rooftop']) ? 'checked' : '');}?>/>
<label for="f5"><?php echo $outdoor_rooftop?></label>
</li>
<?php
$i=$i+1;
}
?>
</ul>
<br><br><br>
<div id="ContactForm" action="#">
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
</div>
<!--
<h2>Sort by :</h2>
<input type="radio" id="s1" name="sort" value="Name" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Name')?'checked':'';}?>/>
<label for="f1"><?php echo 'Name'?></label>
<input type="radio" id="s1" name="sort" value="Location" <?php if (isset($_POST['sort'])){echo ($_POST['sort'] == 'Location')?'checked':'';}?>/>
<label for="f1"><?php echo 'Location'?></label>
<br><br><br>
<input name="filter_button" type="submit" value="Apply" id="filter_button" class="button"/>
-->
</form>
</div>
<div class="wrapper">
<h2>Venues</h2>
<br>
<div class="clist" id="clublist" href="#">
<?php
?>
<table id = "venue_list">
<tbody>
<?php
//Functions
//This function builds the query as every filter attribute is passed onto it.
function query_builder($var_name){
$append = strtoupper($var_name)." in (";
$i=0;
foreach($_POST[$var_name] as $array){
$append = $append."'{$array}'";
$i=$i+1;
if($i < count($_POST[$var_name])){
$append = $append.",";
}
else{
$append=$append.")";
}
}
return $append;
}
//We first need to check if the filter was set in the previous page. If yes, then the query needs to be built with a 'where'. If not the query will just display all values.
//We also need to check if order by is required. If yes, we will apply the corresponding sort, else we will just sort on the basis of location.
//The below 2 variables do the same.
$filter_set = 0;
$filter_variables = array('location','party_type','genre','happy_hours','outdoor_rooftop');
$map_array = array();
if(isset($_POST['location'])){
$filter_set = 1;
}
if(isset($_POST['party_type'])){
$filter_set = 1;
}
if(isset($_POST['genre'])){
$filter_set = 1;
}
if(isset($_POST['happy_hours'])){
$filter_set = 1;
}
if(isset($_POST['outdoor_rooftop'])){
$filter_set = 1;
}
if($filter_set == 1){
$query = "Select * from venue_list where ";
$append_query=array(5);
$j=0;
foreach($filter_variables as $var){
if(isset($_POST[$var])){
$append_query[$j] = query_builder($var);
$j=$j+1;
}
}
$h=0;
//Once all the individual where clauses are built, they are appended to the main query. Until then, they are stored in an array from which they are
//sequentially accessed.
foreach($append_query as $append){
$query=$query.$append;
$h=$h+1;
if($h < $j){
$query=$query." AND ";
}
}
}
else{
$query = "Select * from venue_list";
}
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result))
{
$name = $row['NAME'];
$img = $row['IMAGE_SRC'];
$addr = $row['ADDRESS'];
$location = $row['LOCATION'];
echo "<script type='text/javascript'>map_function('{$addr}','{$name}','{$img}');</script>";
?>
<tr>
<td>
<img src="<?php echo $img.".jpg"?>" height="100" width="100">
</td>
<td>
<?php echo $name?>
</td>
<td style="display:none;">
<?php echo $location?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<br>
</div>
All the 3 components are part of index.php. Kindly notify me if the code is unreadable or inconvenient I will edit it. Awaiting a solution. Thank you.
in this case change your javascript code to
var submiting = false;
function submitmyforum()
{
if ( submiting == false )
{
submiting = true;
$.ajax({
type: 'post',
url: 'index.php',
data: $('#filter_form').serialize(),
success: function () {
alert('form was submitted');
submiting = false;
}
});
}else
{
alert("Still working ..");
}
}
and change the form submit button to
<input name="filter_button" type="button" onclick="submitmyforum();" value="Apply" id="filter_button" class="button"/>
don't forget to change submit button type="submit" to type="button"

Categories