building a query string with jquery and checkboxes - php

I'm building a search form with several filter options on the results page.
It's a basic search form, results show in an friendly url such as: domain.com/resuts/country/age/type/
The filters are simply checkboxes which on click, should reload the page with a query string to identify what has been checked/unchecked. (there is no submit, preferably the update would rebuild the query string with every check box click).
So, for example, on click of some checkboxes we'd build a query string on the end,
eg:domain.com/resuts/england/20-29/female/?scene=hipster&status=single
Can anybody point me to a jquery resource or a code snippet which may assist in getting this done?
Many thanks,
Iain.

The jQuery.get function will automatically handle creating and building the query string when you pass a key-value pair:
http://docs.jquery.com/Ajax/jQuery.get
You can use this selector for checked checkboxes:
$('input:checkbox:checked')

If your html looks like
<input type="checkbox" name="scene" value="hipster" />
I guess you can use something like
var tmp = [];
$('input:checkbox:checked').each(function(){
tmp.push($(this).attr('name') + '=' + $(this).val());
});
var filters = tmp.join('&');

$('.checkbox_class').change(function () {
let filter = $('.checkbox_class');
let types = [];
$.each(filter, function( index, input ) {
if(input.checked)
{
types[index] = input.value;
}
});
let typeQueryString = decodeURIComponent($.param({type:types}));
console.log(typeQueryString);
});

Is this what your looking for? When you click the checkboxes it shows the selected values up top. when you submit the form it shows you the same value in an alert
<div id="buffer" style="height:2em; border:1px solid black; margin-bottom:1em"></div>
form action="#" method="get">
input type="checkbox" id="j" name="state" value="state">state
input type="checkbox" name="city" value="city">city
input type="checkbox" name="type" value="type">type
input type="submit" value="click me">
/form>
$().ready(function(){
//just a simple demo, you could filter the page by the value of the checkbox
$('form input:checkbox').bind('click',function(){
if($(this).attr('checked')==false){
//remove it from the query string
var pieces=$('#buffer').text().split('/');
var $this_val=$(this).val();
for(var i=0;i<pieces.length-1;i++){
//console.log($(this).val());
//console.log(pieces[i]);
if(pieces[i]==$this_val){
//remove value from the buffer
pieces.splice(i);
}
$('#buffer').text(pieces.join('/')+'/');
}
}else{
//add the value to the query string
$('#buffer').append($(this).val()+'/');
}
});
//on form submit
$('#filterWrapper form').submit(function(){
var queryString='';
$.each($('form input:checkbox:checked'),function(){
queryString+=$(this).val()+'/';
});
alert('this will get send over: '+queryString);
return false;//remove this in production
});
Sorry about the broken HTML, the editor doesnt like form tags and input tags

Related

Check which dynamic buttons (input type button) the user has click on server side php

First of all I want to thanks all of you guys for helping every day , answering questions. You have save me a lot of time and I have learn a lot.
I have let's say this buttons on a form.
<button type="button" value="Adventurous" name="adv" id="adv">Adventurous</button>
<button type="button" value="Discovery" name="disc" id="disc">Discovery</button>
<button type="button" calue="Easy-going" name="easy" id="easy">Easy-going</button>
When the user clicks on a button to specify how he feels in our example I have the follow code on jquery to change the state of the button as checked and change the class (to be shown with different colors etc)
$(".tailor_field .tailor_mood_btn button").click(function() {
var checked = $(this).attr('checked');
$the_image = $(this).find("img");
if(checked){
$(this).removeClass("mood_on");
$(this).attr('checked', false);
$the_image.attr("src", templateDir+"/images/btn_on.png");
}
else{
$(this).addClass("mood_on");
$(this).attr('checked', true);
$the_image.attr("src", templateDir+"/images/btn_off.png");
}
});
So when the user press submit I want to check on server side (php) which buttons the user clicked ?
Second I would like to insert the buttons dynamically. Ie to have a string on my DB, explode it to an array and loop each element to create the buttons etc. How I will know what to check if I don't know how many buttons will be and their names from the beginning ? Maybe with sessions (I would like to avoid it if there is another solution)?
Thanks a lot!
I would do it this way:
var checkedButtons = $(".tailor_field .tailor_mood_btn button[checked=true]");
$("form").submit(function() {
var data = [];
checkedButtons.each(function(index, element) {
var name = element.attr('name');
var value = element.val();
data[name] = value;
});
$.post('file.php', data);
});
The data variable is an array with keys as the names of clicked buttons, an values of values of those buttons. Later an ajax request is made to the file that needs this data (file.php) where the data array is available in the superglobal $_POST (ex. $_POST['adv'] = "Adventurous")
I think the best answer is to just use a list of checkboxes. It is what they were made for.
If you want to use the special buttons though, here is one way using the hidden filed as the input, rather than the actual button. I don't know if the element "button" has a checked attibute.
I just used a simple little javascript to change the values of the input, you can adapt your current function. Just notice that I gave the clickable buttons a new id, appending "_button" to the name from your database.
<?php
$string = "Adventerous,Discovery,Easy-Going"; /* this is from your database */
$delimiter = ",";
$button_values = explode($delimiter, $string);
?>
<html>
<body>
<script type="text/javascript" >
function checkbutton(id) {
var val = document.getElementById(id).value;
if (val == 0)
val = 1;
else
val = 0;
document.getElementById(id).value = val;
alert("Clicked: " + id);
}
</script>
<form action="form-catch.php" method="post">
<?php
foreach($button_values as $value) {
echo '<button type="button"
onClick="checkbutton(\''.$value.'\')">'.$value .'</button>
<input type="hidden" name="'.$value.'" id="'. $value .'" value="0" ><br>';
}
?>
<input type="submit" value="submit">
</form>
</body></html>
Then on the server, the form will send the button names from the string and the 0 or 1 if that button was checked.
<?php
/* quick form checker to show what was clicked in the other form */
foreach($_POST as $key => $val)
echo "<br> $key : $val";
?>
Even if you do not use the exact code, I hope the concept will get you in the right direction.
1) Send the data as a form input.
2) Loop through whatever was sent over and check for set values.

Jquery - How to get current input value from a repeating from

I have a comment system in which i want to add delete option, for this i have implemented a POST form in each comment which posts comment-id to delete.php, it is working in php, but not in jquery.
i.e in order to delete comment a comment id must be posted to delete.php file which handles deletion of comment from database.
i am trying to fetch that comment-id from input value to post with jquery like this but it gives me the first comment-id value not the selected value.
Jquery
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]").val();
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
repeating form is like this
<form name="comments" action="../../delete.php" method="post">
<input name="comment-delete" type="hidden" value="<?php echo $list['comment-id']; ?>" />
<input value="Delete" type="submit" />
</form>
if i use .each() or .map() it gives me all the comment-id values.
Please see and suggest any possible way to do this.
Thanks.
To find the relevant input, that is the one of the form you submit, you could use this :
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
BTW, I'm not totally sure of what you do but you might be missing a .val() to get the value of the input.
You have the same name on each hidden input, naturally you get all those inputs as you have not targeted the correct form when doing:
$("input[name=comment-delete]");
"this" whould point to the form inside your submit function. Try this.
$('form[name=comments]').submit(function(){
var comment_delete = $(this).find("input[name=comment-delete]");
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
As dystroy said, you are probably missing .val().
var commentId = $(this).find("input[name=comment-delete]").val();
try this
$('form[name=comments]').submit(function(){
var comment_delete = $("input[name=comment-delete]", this);
//$.post('../../delete.php', {value1:comment_delete}, function(data){alert('deleted')});
alert(comment_delete);
return false;
});
this refers to the form being submitted (more generally, to the event source).
$(...) accepts a second parameter, which is then used as a context for the selector. $(selector, context) is equivalent to $(context).find(selector)

store the option of a selectlist added by jquery into database using PHP

I found a jquery snippet to add and remove options from a select box from box 1 to box 2. This works great. However, when i try to print_r in PHP of the box where the new options are added then it won't show. I cant even see it on the resource after submit. Any solution?
$('#btn-add').click(function(){
$('#select-from option:selected').each( function() {
$('#select-to').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
$('#btn-remove').click(function(){
$('#select-to option:selected').each( function() {
$('#select-from').append("<option value='"+$(this).val()+"'>"+$(this).text()+"</option>");
$(this).remove();
});
});
});
and html of the two select lists
<select class="gen" name="selectfrom" id="select-from" multiple size="6" style="width: 150px;">
</select>
<input name="" id="btn-add" type="button" class="add_list" style="vertical-align: top;">
<input name="" id="btn-remove" type="button" class="remove_list" style="vertical-align: top;">
<select class="gen" name="selectto" id="select-to" multiple size="6" style="width: 150px;">
</select>
upon submit i check the $_POST['selectto'] from the selectto box. Any idea's?
EDIT: the foreach in php;
$articles_ary = array();
foreach ($_POST['selectto[]'] as $options)
{
if (!empty($options))
{
$articles_ary[] = $options;
}
}
print_r($articles_ary);
when you POST a select the form submits only the selected option and bare in mind that it must be selected.
with your code you are just adding the options to the selectto, but you're not:
a) chosing one of them (if you want a single value posted)
b) chosing all of them to be posted on the PHP page. (if you want multiple values posted)
in the second case (i thought it's the one you need) you can use this simple jQuery function:
$("#buttonusedtosendform").click(function(e){
e.preventDefault();
$('#select-to option').each( function() {
$(this).attr('selected', true); //with this you select all the option
});
$('formname').submit();
});
bare in mind that if you want to retrieve all the options of a select with PHP you will have to use a little trick by naming the select with square bracket at the end (it's a feature that PHP offer, where it will overwrite the former variable with the latest parsing each one separately):
eg. selectto => selectto[]
this way php will handle it as an array and let you retrieve all the value as if it is one:
foreach($_POST['selectto[]'] as $options){}
When you enter data from one select box to second selectbox, you need to have items selected in second select box to show when you do print_r in php.
For this, after items are added to second select box say with id selectbox2, then you could select all items of second selectbox and then submit the form
for (var i = 0; i < selectbox2.options.length; i++) {
selectbox2.options[i].selected = true;
}
//then Submit form like this, assuming your form name is form1
document.form1.submit();
Hope this helps

Collect checkbox values in jQuery and POST them on submit

I've referred to this post:
Post array of multiple checkbox values
And this jQuery forum post:
http://forum.jquery.com/topic/checkbox-names-aggregate-as-array-in-a-hidden-input-value
I am trying to collect an array (or concatenated string with commas, whatever) of checkbox values in a hidden input field using jQuery. Here's the script code I'm using:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val(function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
});
});
</script>
A snippet of the relevant HTML:
<form id="advancedSearchForm" name="advancedSearchForm" method="post" action="<?php echo site_url('/magcm/advancedSearch#results'); ?>">
<input type="checkbox" name="FCM" id="FCM" class="chk" value="FCM" <?php echo set_checkbox('FCM', 'FCM'); ?>/>
<input type="hidden" name="specialty" id="specialty" value="" />
<input class="button" name="submit3" id="submit3" type="submit" value="Search" />
I've tried changing "submit" to "submit3" in the jQuery, which breaks (obviously). When I print_r($_POST), the checkboxes POST correctly but the condensed hidden variable does not. (It posts, but a blank value.) The checkboxes persist correctly using CI's hacked set_value() function (Derek needs to implement this in the main trunk... but that's another story)
I'm sure I'm doing something that is wrong and easy to point out. I've just been banging my head against the wall for the past 2 hours on it, trying various functions and changing a ton of things and analyzing it in Chrome dev tools (which don't show any errors).
Help is appreciated. :)
Let's say you applied an class, maybe "tehAwesomeCheckboxen" to every checkbox. Then
<script>
$("#advancedSearchForm").submit(function() {
var chkbxValues = $(".tehAwesomeCheckboxen").val();
$("#specialty").val( chkbxValues.join(",") );
});
</script>
EDIT:
I don't think the $_POST array is getting populated, since the submit is being handled locally by the JavaScript engine. SO... let's try this:
<script>
var chkbxValues = new Array();
$(".tehAwesomeCheckboxen").live("change", function(e){
var val = $(this).val();
if( $(this).is(":checked") ) {
if( chkbxValues.length == 0 || chkbxValues.indexOf(val) == -1){
// Add the value
chkbxValues.push(val);
}
}
else {
// remove the value
chkbxValues.splice( chkbxValues.indexOf(val), 1 );
}
$("#specialty").val( chkbxValues.join(",") );
});
</script>
This adds an event handler the checkboxes themselves, such that checking/unchecking the box alters the hidden element. Then your form handles its submission as normal.
Is this more in line with what you're trying to do?
P.S. Those who upvoted this, please note I have modified my answer. Please verify whether you still find it useful and adjust your vote accordingly.
I ended up solving it using PHP arrays rather than jQuery:
<input type="checkbox" name="chk[]" id="RET" class="chk" value="RET" <?php echo set_checkbox('chk', 'RET'); ?>/>
I changed the name to an array and POSTed it to my script, where I looped through the array and handled it there. Still not sure what the problem was with the jQuery-based solutions, but I figured I'd post this for everyone to refer to in the future.
You've got lots of nested functions() in your JavaScript, makes it hard to follow what you're doing.
However, it seems that you're just passing a function to .val() rather than an actual value. Try this instead:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
$(form).find("input[name=specialty]").val((function() {
return $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
})());
});
</script>
Or even better, calculate the value first:
<script type="text/javascript">
$("#advancedSearchForm").submit(function() {
var form = this;
var value = $("input:checkbox",form).map(function() {
return $(this).attr("name");
}).get().join();
$(form).find("input[name=specialty]").val(value);
});
</script>

How to pass multiple selected (through checkboxes) row ids to a php script in jQuery?

I'm generating an html file which looks like:
<tr id="ID001" property1="PROPERTY001"><td><input type="checkbox"
name="row_checkbox_ID001"></td><td>...</td><td>...</td></tr>
<tr id="ID002" property1="PROPERTY002"><td><input type="checkbox"
name="row_checkbox_ID002"></td><td>...</td><td>...</td></tr>
When the user selects individual rows for deletion, how can I (through jQuery), pass this to a php script?
I will need to build something like this:
$(document).ready(function () {
$('#contact-form input.contact-delete').click(function (e) {
e.preventDefault();
$.get("deleterecord.php", ...);
});
});
There can be 0, 1 or multiple rows... The HTML being generated is under my control and can be modified.
Clarification:
I want to have a button above all these rows which the user can click on AFTER he has selected the rows from the table.
<div id='contact-form'><h2>Contacts</h2>
<input type='button' name='contact-delete' value='Delete Record(s)'
class='contact-delete'/>
The TRs need to be deleted, but BEFORE that, the deleterecord.php script needs to be called with the TR ids.
Use HTML arrays
<input type="checkbox" name="chk[]" value="01234">
<input type="checkbox" name="chk[]" value="98765">
You could create a JSON object containing details of any rows selected (ID's or whatever you need) and send that to your php script. Check out this article on json, php + jquery.
I believe, you are looking for similar behavior:
$('#contact-form input.contact-delete').click(function (e) {
var $this = $(this);
// find the table row, in which are elements contained
var $tr = $this.closest('tr');
// take id
var id = $tr.attr('id');
// ajax with id
$.get("deleterecord.php?id="+id, function (data) {
// remove table row on success
$tr.remove();
});
e.preventDefault();
});
Sorry for answering my own question, but the SO post at: Getting all selected checkboxes in an array neatly solves my problem!
For future visitors to this page, pay attention to variable names in your HTML and how you're accessing the input checkboxes in jQuery!

Categories