Storing selected checkboxes in array and use it with facebox - php

I'm having some trouble using jQuery's plugin Facebox to process some data from a form.
What I'm trying to accomplish is basically get the values of the number of selected checkboxes into an array and have it available in my popup to process it with PHP.
I have something like this on a form page:
form.html
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="checkbox" name="equip" value="<?php echo $equip_id; ?>" />
<input type="button" name="replace" onClick="replace_equip()" />
There are more checkboxes, but I think these are enough to get started.
Here is replace_equip()
function replace_equip() {
var nArr = new Array();
$("input:checkbox[name=equip]:checked").each(function() {
nArr.push($(this).val());
$.facebox(function() {
$.ajax({
data: { name : nArr },
error: function() {
$.facebox("err");
},
success: function(data) {
$.facebox(data);
},
type: "post",
url: "test.php"
});
});
});
}
I'm trying to save the selected checkboxes into an array, in a way that I can use it for PHP processing in test.php.
I'm just getting started with jquery and javascript in general, so forgive any monster mistakes you may find!

To get started, there are a few stylistic issues with your code. First, you should opt not to use new syntax with Arrays, Objects, etc. Instead, declare your Array with something like var array = [];. Second, you're using an inline onClick, which should be avoided if you're using jQuery already. Instead, use something like $('input[name="replace"]').on('click', function() {...});. You should also consider using camelCase with your functions, and if you like underscores, use them with vars.
Now onto the meat of your question. I refactored your code like so:
$('input[name="replace"]').on('click', function() {
replaceEquip();
});
function replaceEquip() {
var array = [];
$("input:checkbox[name=equip]:checked").each(function() {
array.push($(this).val());
});
$.facebox(function() {
$.ajax({
type: "POST",
url: "test.php",
data: { name : array },
error: function() {
$.facebox("err");
},
success: function(data) {
$.facebox(data);
}
});
});
}
In your PHP code, you would json_decode() this array and work with it how you want. I also moved the type and url params to the top, as your error and success functions may get quite lengthy.
I would consider reading JavaScript Patterns (at least the Essentials chapter).

Related

php+jquery get values from serialized form with input name array

I'm developing a PHP+jQuery application. I'm quite noob with PHP.
Anyway, I'm trying to send a serialized form to a PHP page that will store data to session, via jQuery.
This is a dynamic form, where I could have many input like this:
<input type="text" name="name[]" />
And this is an example of my serialized form:
name[]=name1&name[]=name2
I've tried to get the array with $_POST["name"] from the PHP page, but it did not work.
How can I get this array from the PHP page?
Are you doing something like this???
$(function() {
$('.submit').click(function() {
var names = $('input[name="name[]"]').map(function(){
return this.value;
}).get();
$.ajax({
type: 'POST',
url: url,//this should link to your page
data: {
'name[]': names,
// other data
},
success: function() {
}
});
});
});
</script>

Autocompleting textboxes with AJAX using variables from a PHP file

I am doing a project where I need to make sure that my form instantly autofills 2 textboxes based on input from the first textbox. Right now I am just testing. I can't use database entries to populate my form, only PHP variables. My logic needs to be like this: user types in a specific 10 digit number into a textbox on my form (specified in a PHP file), then the other two textboxes get autofilled with specific entries after an AJAX call to that PHP file. This is definitely one of the more complex tasks that I've encountered so far (noob). My code doesn't work, so I would really appreciate any help with getting it to function properly.
HTML is like this:
<!--load scripts, libraries, etc.-->
<form method="GET">
Number: <input type="text" name="num" id="num">
First Name: <input type="text" name="first" id="first">
Last Name: <input tupe="text" name"last" id="last">
</form>
PHP:
<?php
$num=$_GET["num"];
$first=$_GET["first"];
$last=$_GET["last"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
jQuery:
$(document).ready(function () {
$("#num").keyup(function () {
var el = $(this);
if (el.val().length === 10) {
$.ajax({
url: "http://localhost/test.php",
cache: false,
dataType: "json",
type: "GET",
data: "npi=" + el.val(),
success: function (result) {
$("#first").val(result.firstname);
$("#last").val(result.lastname);
}
});
}
});
});
in ajax change like this it'll be easy to understand
type: "GET",
data:{num: el.val()},//if multiple then like this->data:{attr:val1,attr2:val2,...},
in php
<?php
$first["John"]="john";//i hope you have these two values defined
$last["Smith"]="smith";
$num=$_GET["num"];
if ($num=="0123456789")
{
$fill = array(
'firstname' => $first["John"],
'lastname' => $last["Smith"],
);
echo json_encode($fill);
}
else
{
echo "Bad input.";
}
?>
explanation
see the process is like
first the number will go to php with the help of ajax(through the
ajax request)
type: "GET",,
data: {num: el.val()},
so as we are sending the number as GET request to php, in php we get this number with $_GET['num'] so now this value will have 0123456789 value in it.
now we are checking with if condition in php
if ($num=="0123456789")
{
//here we need to send the firstname and lastname values BACK TO THE AJAX REQUEST
so we need to have these first and last names here in php defined somewhere manually or get it from database(if you have these first,last names in DB)
echo json_encode($fill);
}

Grab the name of an element with jquery

I have a series of Form Elements each with different names, I'll post one as an example. I cannot hard code the name into Jquery because unless I inspect the element, I won't know the name.
With that aside heres the element:
<label class="checkbox">
<input type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="package_Aisis-Related-Posts-Package-master" checked="" />
Aisis-Related-Posts-Package-master
(Disable)
</label>
The catch is to do this:
Grab the name of this element - upon clicking disable - and do two things, one - if the element is checked, which in this case it's not, unchecked it, two pass the name to a php variable, which then can do processing.
How would I do this? Jquery is not my strong area.
Here is a example without knowing more of your code:
$(function () {
$('input:checkbox').click(function () {
$(this).prop('disabled', true);
var iName = this.name;
$.ajax({
url: "file.php",
data: {
'inputname': iName
},
success: function (data) {
alert(data.returned_val);
}
})
})
})
Demo here
If you want to reach the input via name directly you need to use double backslasshes to escape the square brackets and reach that input via name. Use:
$('input[name=aisis_options\\[package_Aisis-Related-Posts-Package-master\\]]')
You can add an onchange with checkbox
onchange="f(this);"
in js f() function you can use this.name to get the name, this.value to get value etc and do whatever you want.
To check/unckeck, you can use $element.prop('checked', true/false); like this (fiddle):
HTML
<input
type="checkbox"
name="aisis_options[package_Aisis-Related-Posts-Package-master]"
value="...."
checked="checked"
/> Aisis-Related-Posts-Package-master
(Disable)
JS
$('.trigger').click (function () {
closest_checkbox = $(this).siblings('input[type=checkbox]');
closest_checkbox.prop('checked', !closest_checkbox.prop('checked'));
});
JS part 2: AJAX
You can build an object with all your name:value combinations using the jQuery plugin serializeObject, your form submission event handler would be something like:
$('form').submit( function (e) {
// Prevent the form from being sent normally since we want it ajaxified
e.preventDefault();
// Send request to php page
$.ajax({
type: "POST",
url: "some.php",
data: $('form').serializeObject() // <== Magic happens here
});
});
PS. Don't forget to include the serializeObject plugin and give a unique id to the form, $('#unique_id') is way better than $('form') which will match all the forms in the page.
To grab the value of name attribute, you can use:
$(this).attr('name');

Reading serialized jquery data in PHP (multiple checkboxes)

JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.
Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.
Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.
The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()
there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name

Fetch input value from certain class and send with jquery

<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});

Categories