Calculate input of html text fields with php - javascript

At the moment, I try to create a survey in a webpage. At the end of the survey, users are able to fill two text fields with values. With these values, my plan is to calculate an output, displayed for them at the same page. So:
Input: a
Input: b
Result: ab+b-ab (do not concentrate this please, its just an example)
My plan is that the user is able to fill the two input fields and by a buttonclick, a php function is calculating the result field (by my own algorithm depending on input - this is already working) and fills this field. Do i have to link to another webpage for this purpose?
And how is it possible to grab the two input values and give it to my php function?
And as last thing, how is it possible to start a php function either embedded in html or in an own file?
I tried your solution and some others as well (fetching inputA and inputB from the DOM with document.getElementById does not work. Below is my code
<form>
InputA:<br>
<input type="text" id="inputA"/></br>
InputB:<br>
<input type="text" id="inputB"/></br>
Output:<br>
<input type="text" id="output"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
<script type="text/javascript">
$("#calculate").click(function(){
$.get( "submit.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
</script>
submit.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$output = $value1 + $value2;
echo($output);
}
?>
When I check with firebug the error, i get a: no element found exception in both (html and php) files. Seems like the problem is, that with: value1: $("#inputA").val(); no value is givent to the server or it can not be handled there.
If i grab the value from the DOM, I can "bring" the value inside the .click function but there is still a "no element found exception" by calling the submit.php.
I have no idea what i am doing wrong, any suggestions? Do i need to install/bind anything in for using JQuery?
After some additional changes, it finally worked (one thing was the header line in the submit.php file):
<form>
WorkerID:<br>
<input type="text" id="workerId"/></br>
CampaignId:<br>
<input type="text" id="campaignId"/></br>
Payment Code:<br>
<input type="text" id="payCode"/>
</form>
<input name="go" type="button" value="Calculate" id="calculate" >
<script type="text/javascript">
$("#calculate").click(function(){
$.get( 'submit.php', { wId: $('#workerId').val(), cId: $('#campaignId').val()} )
.done(function( data ) {
$('#payCode').val(data.payCode);
});
});
and submit.php:
<?php
header('Content-Type: text/json');
$workerId = $_GET['wId'];
$campaignId = $_GET['cId'];
$payCode = $campaignId . $workerId;
$result = array("status" => "success",
"payCode" => $payCode);
echo json_encode($result);
?>

To simplify, i am using jQuery, doing this in vanilla JS is a real pain in the a** in my opinion.
You can use .get(), which is the GET shorthand for .ajax().
With that code, you bind a handler on your submit button and make a AJAX request to your PHP and fill the result your PHP gives into your result field asynchronously.
$("#calculate").click(function(){
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
$("#output").val(data);
});
});
Also change your submit to something like this:
<input name="go" type="button" value="Calculate" id="calculate" >
Like that, your button won't submit a form and therefore synchronously load your PHP.
Since you seem new to JavaScript and you had this comment
my button, but here i got redirected to submit, no idea how i can go back to page before with filled textfield
in your question, i'll tell you, JavaScript works while the DOM (Document Object Model) is loaded, means you can access your elements when already loaded and alter them.
Getting the value of a input is as easy as that in jQuery:
$("#inputA").val();
With the AJAX you get what your php will return in data.
// the { value1: $("#inputA").val(), value2: $("#inputB").val() } object
// is what you send to your PHP and process it
$.get( "path/to/your_php.php", { value1: $("#inputA").val(), value2: $("#inputB").val() } )
.done(function( data ) {
// data is what your php function returned
});
Using JS you can now change your elements as just said, effectively meaning to change the value of your output here:
$("#output").val(data);
"Working" Example: JSFiddle (There is no PHP to access to, so it will not do anything actively)

Related

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

Return two database results with the one jQuery AJAX form (or response)

What I have:
I have a form that uses jQuery AJAX to query a database and returns a series of <option> elements that are appended to a <select> element.
What I need:
Using the same form, I need to run a second query on a different table in the same database which will determine which radio button is checked in a radio button group. A URN is sent via AJAX to return which radio button should be selected.
My code:
HTML:
<form type="post" method="post" action="<?php $_SERVER['PHP_SELF']; ?>" id="adddetailstoanexistingclient_form" name="adddetailstoanexistingclient_form">
<input type="hidden" id="sendingclienturn_js" name="sendingclienturn_js"/>
<select id="factivity_buildproject_a" name="factivity_buildproject_a">
<option selected="selected"></option>
<!--AJAX HTML RESULTS GO HERE-->
<option value = "Build / Project non-specific">Build / Project non-specific</option>
</select>
<input type="radio" name="factivity_prospectstrength" value="1" /> 1
<input type="radio" name="factivity_prospectstrength" value="2" /> 2
<input type="radio" name="factivity_prospectstrength" value="3" /> 3
<input type="radio" name="factivity_prospectstrength" value="4" /> 4
<input type="radio" name="factivity_prospectstrength" value="5" /> 5
<input type="hidden" name="action" value="buildorprojects_ajax"/>
</form>
jQuery/AJAX:
$('#sendingclienturn_js').on('change keyup paste input',ajaxSubmit);
function ajaxSubmit(){
var adddetailstoanexistingclient_form = $('#adddetailstoanexistingclient_form').serialize();
$.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: adddetailstoanexistingclient_form,
success:function(data){
if (!$.trim(data)){
$('#factivity_buildproject_a').hide();
$('[name=factivity_buildproject_ro]').show();
}
else{
$('#factivity_buildproject_a').show();
$('[name=factivity_buildproject_ro]').hide();
}
$("#factivity_buildproject_a option.filterable_option").remove();
$("#factivity_buildproject_a option:first").after(data);
},
error: function(errorThrown){
alert(errorThrown);
alert("There is an error with AJAX!");
}
});
return false;
}
PHP:
function buildorprojects_ajax(){
global $wpdb;
$sendingclienturn_js = $_POST['sendingclienturn_js'];
$query_buildsorprojects = $wpdb->get_results(
"
SELECT *
FROM wp_crm_bplist
WHERE clienturn = '$sendingclienturn_js'
AND deleted <> '1'
ORDER BY buildorproject, recorddateandtime DESC
"
);
if($query_buildsorprojects===FALSE){
echo "Error";
}
else {
foreach ( $query_buildsorprojects as $query_buildorproject ) {
echo '<option class="filterable_option" value="'.$query_buildorproject->recordurn.'" data-clienturn="'.$query_buildorproject->clienturn.'">'.$query_buildorproject->buildprojecturn.' - '.$query_buildorproject->buildorproject.' ('.$query_buildorproject->buildorprojecttype.')</option>';
}
}
die();
}
add_action('wp_ajax_buildorprojects_ajax', 'buildorprojects_ajax');
add_action('wp_ajax_nopriv_buildorprojects_ajax', 'buildorprojects_ajax');
What I've tried:
I've duplicated the above code (HTML, jQuery AJAX and PHP), changing the necessary titles of ids, names, functions and variables which works but at the cost of my first AJAX function failing.
I've deduced that the problem occurs when adding the second hidden field to my HTML code. The second AJAX form submission breaks the first.
i.e.
Works with one hidden field:
<input type="hidden" name="action" value="buildorprojects_ajax"/>
Does not work with second hidden field:
<input type="hidden" name="action" value="buildorprojects_ajax"/>
<input type="hidden" name="action" value="prospectstrength_ajax"/>
yes, you can encode two segments into one response. All you then need to do is to decode the response into two segments. This could be done with substr, but as this is AJAX, you're perhaps just looking to create an array and json_encode it, so you've to two strings after json decoding.
Alternatively:
If you want to share the same response with multiple segments of data you want to pass along, you can create multiple segments with the help of JSON and PHP's global static state.
JSON should be handy because most AJAX javascript routines offer to parse it directly.
Global static static on the other hand is used big time in Wordpress, so you won't break with that.
For example at different places you could add to the response:
function ajax_callback_red() {
...
JsonResponse::add('<options/>');
}
function ajax_callback_green() {
...
JsonResponse::add('<checkboxes/>');
}
When the request finishes, that JsonResponse (here statically accessed) the can turn such into JSON:
[
"<options\/>",
"<checkboxes\/>"
]
Such code can be quickly written. Either with a class destructor or you register some shutdown action:
class JsonResponse
{
static $instance;
private $segments = array();
/**
* conditionally assign class instance to global variable and
* return it.
*
* #return JsonResponse
*/
public static function getInstance() {
self::$instance || self::$instance = new self;
return self::$instance;
}
public static function add($segment) {
self::getInstance()->addSegment($segment);
}
public function addSegment($segment) {
$this->segments[] = $segment;
}
public function __destruct() {
echo json_encode($this->segments, JSON_PRETTY_PRINT);
die();
}
}
Hope this helps.
Your approach of setting the action with hidden fields is flawed. If you need to run two queries on each change, keyup, paste, or input, then try something like
$('#sendingclienturn_js').on('change keyup paste input',function(){
ajaxSubmit('buildorprojects');
ajaxSubmit('prospectstrength');
});
function ajaxSubmit(action){
type:"POST",
url: "admin-ajax.php?action="+action,
data: [pull in the correct data for the action],
Better yet, if these two requests are always done together, you really need only one request and for your PHP to run the two actions and return a single object. Like Hakre says in his comment, you have the power, use it.

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Display JSON data on HTML page

This project is dealing with database of scientific papers and citations.
I correctly implemented some PHP to use a users input (DOI) and search our database and pass the data to javascript. The javascript gets the data like so:
function getMETA() {
var json = <?php echo json_encode($data); ?>;
}
Using an HTML form with an onClick="getMETA()" the variable is correctly filled with the data and here is an example:
var json = [{"doi":"10.1103\/PhysRevB.79.054101","pub_date":"2009-02-02","journal":"Phys. Rev. B","title":"Absence of superconductivity in the high-pressure polymorph of MgB_{2}","authors":"Y. Ma, Y. Wang, and A. R. Oganov","metainfo":"79, 054101 (2009)"}];
This database query just contains meta data of the paper selected, I want to just display it on the webpage. This is what I tried:
Title: <span id="title"></span><br />
Authors: <span id="authors"></span><br />
Publish Date: <span id="pubdate"></span><br />
Journal: <span id="journal"></span><br />
Then I used document.getElementById("journal").innerHTML but this is not working at all. I even tried to just set it to a string like so: document.getElementById("journal").innerHTML = "test"; and nothing is displayed on the webpage. I also tried this as a test:
HTML:
<span id="title">TEST</span>
JAVASCRIPT:
var val = document.getElementById("title").innerHTML.value
alert(val);
And I get an alert box that says "undefined"
How can I get this document.getElementById to work? Or do you recommend another way to parse and display the json data on the webpage? Maybe in a border-less table format?
Thanks!
You're likely trying to query #title before it's actually available. To ensure a reference to the DOM element you're after gets returned when you ask for it, execute your code inside a DOMContentLoaded handler:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('title').innerHTML = 'test';
});
Make sure you're running your Javascript after the DOM has been loaded:
$(document).ready(function() {
$("#title").text("test");
});
Plain JS:
window.onload = function() {
document.getElementById("title").innerHTML = "test";
};
This would be because document.getElementById("title").innerHTML is returning a string.
It does not have a value property.
http://jsfiddle.net/UAQFJ/1/
Try this:
$.each(json[0],function(f,v){
$("body").append("<div class='row'><span class='field'>"+f+": </span><span class='value'>"+v+"</span></div>");
})
DEMO here.
http://jsfiddle.net/KkgS7/
The jsfiddle shows what I currently have. Here is the full code in the order on my HTML page:
<script type="text/javascript">
function getMETA() {
var json = <?php echo json_encode($data); ?>;
}
document.addEventListener('DOMContentLoaded', function(json) {
document.getElementById("title").innerHTML = "test title";
document.getElementById("authors").innerHTML = json[0];
document.getElementById("pubdate").innerHTML = json[0];
document.getElementById("journal").innerHTML = json[0];
});
</script>
</head>
<body>
<h1>PRAEDICIT</h1>
<h2>How successful your paper will be?</h2>
<form name="inputdoi" id="doi_input" action="" method="post">
<input name="doi_input" id="searchfield" placeholder="Search by DOI" />
<input type="submit" id="button" name="submit" value="Look Up" onclick="getMETA()" />
</form><br><br>
Title: <span id="title">test title</span><br />
Authors: <span id="authors"></span><br />
Publish Date: <span id="pubdate"></span><br />
Journal: <span id="journal"></span><br />
The "test title" correctly writes to the HTML as you can see. I know that json[0] is not the correct way to get the object out of the json data, this is the last step I need that I can't figure out.
Am I able to pass the json variable like that from getMETA to the new function? Assume the json variable looks like the example in the first post:
var json = [{"doi":"10.1103\/PhysRevB.79.054101","pub_date":"2009-02-02","journal":"Phys. Rev. B","title":"Absence of superconductivity in the high-pressure polymorph of MgB_{2}","authors":"Y. Ma, Y. Wang, and A. R. Oganov","metainfo":"79, 054101 (2009)"}];
The Webpage Shows this after looking up a paper:
Title: test title
Authors: undefined
Publish Date: undefined
Journal: undefined

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources