www.webdeveloper.com
Results 1 to 14 of 14

Thread: collecting Checkbox Array to pass to Ajax/php

  1. #1
    Join Date
    Jan 2011
    Posts
    62

    collecting Checkbox Array to pass to Ajax/php

    hi all, real js noob here and I'm sure this has been asked, I'm just not able to find a solution that works for me. I have been trying to find a way to collect all the values of a set of check boxes on a page I have and submit them to an ajax function to be processed in php. The problem is that I can not get the functions I have to pass anything other than an empty value.

    the functions I'm using to try and get these values read as below and work for all other elements on the form.

    Code:
    <script type="text/javascript">
    
    var req;
    var doesNotSupport = true; 
     
    function putData(url, id, col, data, elementid) 
    { 
        if (!doesNotSupport) 
            return; 
     
        if (window.XMLHttpRequest) { 
            req = new XMLHttpRequest; 
        } else if (window.ActiveXObject) { 
            req = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
         
        if (col == 'requests') {
        	data = checkboxValues('requests[]');
        }
        
        if (req) { 
           req.onreadystatechange = processReqChange(elementid); 
           req.open("POST", url + '?id=' + id + '&col=' + col +'&value=' + data, true); 
           req.send(null); 
        } else { 
           alert("Your browser does not support XMLHttpRequest technology!"); 
           doesNotSupport = false; 
        } 
    }
    
    function checkboxValues(name){
        var nodes = document.getElementsByName(name);
        var n;
        var values = new Array();
        for (var i = 0; n = nodes[i]; i++) {
            if (n.checked == true) {
                values[n]=n.value;
            }
        }
        return values;
    }
    
    
    function processReqChange(elementid) {
        // only if req shows "loaded"
        if (req.readyState == 4) { 
            // only if "OK"
            if (req.status == 200) { 
            	var returnData = req.responseText;
                document.getElementById(elementid).value = returnData;
                document.getElementById(elementid).title = returnData;
            } else { 
                alert("There was a problem retrieving the data:\n" + req.statusText);
                document.getElementById(elementid).value = req.statusText;
            } 
        } 
    }
    
    </script>
    the check box array is displayed like this and is created on the fly by php
    HTML Code:
    <table>
    <tbody><tr><th colspan="3">Requests</th>
    </tr><tr><td valign="top">
    		<ul>
    	<li>
    	<label><input name="requests[]" id="requests[]" value="6" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Ambulance</label>	</li>
    		<li>
    	<label><input name="requests[]" id="requests[]" value="2" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Backboard</label>	</li>
    
    		<li>
    	<label><input name="requests[]" id="requests[]" value="8" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Fire</label>	</li>
    		<li>
    	<label><input name="requests[]" id="requests[]" value="3" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Helicopter</label>	</li>
    	</ul></td><td valign="top" width="33%"><ul>	<li>
    
    	<label><input name="requests[]" id="requests[]" value="5" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Lift Evacuation</label>	</li>
    		<li>
    	<label><input name="requests[]" id="requests[]" value="10" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Off Site SNR</label>	</li>
    		<li>
    	<label><input name="requests[]" id="requests[]" value="11" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Oxygen</label>	</li>
    
    		<li>
    	<label><input name="requests[]" id="requests[]" value="7" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Police</label>	</li>
    	</ul></td><td valign="top" width="33%"><ul>	<li>
    	<label><input name="requests[]" id="requests[]" value="1" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Regular Sled</label>	</li>
    		<li>
    
    	<label><input name="requests[]" id="requests[]" value="9" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Ski Do</label>	</li>
    		<li>
    	<label><input name="requests[]" id="requests[]" value="4" onchange="putData('ajax/incidentReport.ajax.php', 'LLIR94080248', 'requests', '', this.id);" type="checkbox"> Truma Pack</label>	</li>
    	</ul></td></tr></tbody></table>

    Can anyone spot the error or know of a better way for me to get this array. In the end I need to be able to serialize the array in php any post it to the DB.

    Thanks.

  2. #2
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    Don't name the checkboxes "requests[]" (same for id). If you must, give them a name and id of "request_cb". You don't need the [] for a collection; every click automatically updates the checkbox array (it's not really an array so much as it is a comma-delimited list.)

    ^_^

  3. #3
    Join Date
    Jan 2011
    Posts
    62
    thanks, but that did not change anything, I'm still getting an empty return value.

  4. #4
    Join Date
    Dec 2002
    Location
    St. Louis, MO, USA
    Posts
    1,582
    You didn't rename the checkbox array in the function, itself. Also, you are passing '' (blank) as the data variable (attached to the URL parameter of "value" in the XMLHttpRequest.)

  5. #5
    Join Date
    Mar 2009
    Posts
    492
    You are trying to send your data by the POST method but you are doing it incorrectly.
    assuming 'obj' is your XMLHttpRequest object, and 'data' is the string you wish to send (ex. ?a=fred&b=mike ) you should do something like this:

    Code:
    	obj.open('POST', url, true);
    	obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    	obj.setRequestHeader("Content-length", data.length);
    	obj.setRequestHeader("Connection", "close");
    	obj.onreadystatechange = // function that handles the response
    	obj.send(data);
    There may be other things wrong with your code, but until this is fixed it won't work properly.
    Last edited by Tcobb; 01-07-2011 at 01:29 PM.

  6. #6
    Join Date
    Jan 2011
    Posts
    62
    if you mean
    Code:
     if (col == 'requests') {
        	data = checkboxValues('requests_cb');
        }
    then yes I did.

    The blank var ( data ) is meant to be there as the putData function gets this value from the checkboxValues function ( when its meant to anyways ) if the col value == 'requests' . The only thing I'm getting in the Db after this is s:0:""; telling me that the checkboxValues function is returning a null value. is there another way for me to get the check box array once its passed to the php code I can fix it up to meet my needs, its just getting it there via ajax that the problem. the [] was left over from the old method I was using to deal with this form. Now it all has to be updated live to the database so the user does not have to submit any forms and wait for page reloads.

  7. #7
    Join Date
    Jan 2011
    Posts
    62
    Quote Originally Posted by Tcobb View Post
    You are trying to send your data by the POST method but you are doing it incorrectly.
    assuming 'obj' is your XMLHttpRequest object, and 'data' is the string you wish to send (ex. ?a=fred&b=mike ) you should do something like this:

    Code:
    	obj.open('POST', url, true);
    	obj.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    	obj.setRequestHeader("Content-length", data.length);
    	obj.setRequestHeader("Connection", "close");
    	obj.onreadystatechange = // function that handles the response
    	x.obj.send(data);
    There may be other things wrong with your code, but until this is fixed it won't work properly.
    hi thanks for the reply. I'm sure I'm doing it wrong, but so far it has worked and I'm calling this function 30+ times for this page, but I will look into this as I need this work right for all data sent to it. Will changing to GET make a difference?

  8. #8
    Join Date
    Aug 2009
    Posts
    28
    From what I can tell, you're using the wrong variable for the index to your array:

    Your code:
    Code:
        for (var i = 0; n = nodes[i]; i++) {
            if (n.checked == true) {
                values[n]=n.value;
            }
        }
    New code (changed index to values array):
    Code:
        for (var i = 0; n = nodes[i]; i++) {
            if (n.checked == true) {
                values[i]=n.value;
            }
        }

  9. #9
    Join Date
    Jan 2011
    Posts
    62

    Solved

    Sweet, thanks I can not understand how I missed that, but it now works.

    for anyone interested here is the finished script. Its takes the given data, id and col from the element and passes them to the php script which then saves the data to the DB in a predefined table ( set col = data where id )it then sends the value back to the element to make sure it continues to display input-rd value

    Code:
    <script type="text/javascript">
    
    var req;
    var doesNotSupport = true; 
     
    function putData(url, id, col, data, elementid) 
    { 
        if (!doesNotSupport) 
            return; 
     
        if (window.XMLHttpRequest) { 
            req = new XMLHttpRequest; 
        } else if (window.ActiveXObject) { 
            req = new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
         
        if (col == 'requests') {
        	data = checkboxValues('requests_cb');
        }
        
        if (req) { 
           dataString = 'id=' + id + '&col=' + col +'&value=' + data;
           req.open("POST", url , true); 
           req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
           req.setRequestHeader("Content-length", dataString.length);
           req.setRequestHeader("Connection", "close");
           req.onreadystatechange = processReqChange(elementid); 
           req.send(dataString);
        } else { 
           alert("Your browser does not support XMLHttpRequest technology!"); 
           doesNotSupport = false; 
        } 
    }
    
    function checkboxValues(name){
        var nodes = document.getElementsByName(name);
        var n;
        var values = new Array();
        for (var i = 0; n = nodes[i]; i++) {
            if (n.checked == true) {
                values[i]=n.value;
            }
        }
        return values;
    }
    
    
    function processReqChange(elementid) {
        // only if req shows "loaded"
        if (req.readyState == 4) { 
            // only if "OK"
            if (req.status == 200) { 
            	var returnData = req.responseText;
                document.getElementById(elementid).value = returnData;
                document.getElementById(elementid).title = returnData;
            } else { 
                alert("There was a problem retrieving the data:\n" + req.statusText);
                document.getElementById(elementid).value = req.statusText;
            } 
        } 
    }
    
    </script>

  10. #10
    Join Date
    Jan 2013
    Posts
    3
    Could you be kind to post the .php file too, so I can see how exactly the database update is done.
    I have a similar task I have to do and I am a newbie, too.

  11. #11
    Join Date
    Jan 2011
    Posts
    62
    If you mean the PHP script that the javascript/ajax function sends the data to (URL in the code in my last post), then that can be any php file. You just collect the data from the POST/GET or $_REQUST array and then process it as you would a normal form submission. Any responce from the PHP script should be returned using the echo command or any method that would normaly display data on the page. The Ajax function will collect that responce data. you can then pass it to some other javascript that deals with displaying it where needed on you page.

    As the PHP script is executed on the server, you will need to include all the SQL classes and code to deal with the data being sent in to the named PHP script some how.

    Sorry but I can not include the PHP script refered to in the code as it does not belong to me any more. If you can be more presise on what it is your suck with I will gladly see if I can help you fix it though.
    Last edited by fideltfg; 01-30-2013 at 01:35 PM.
    Visit my live dev site @ http://knowcode.ca

  12. #12
    Join Date
    Jan 2013
    Posts
    3
    Ok, first of all thank you very much for your reply. Here's what I want to do in general:
    I have an html form which contains a 5x8 table.This table represents 40 seats in a concert hall.Each 'seat' has a checkbox which is checked if the user wants to book the seat. When the form is submited, a js function is called which atm looks like this:

    Code:
    function submit_tickets(form){
    	var count=0;
    	//var temp=new Array();
    	var booked_seats=new Array();
    	var c = document.getElementById(form).getElementsByTagName('input');
        for (var i = 0; i < c.length; i++) {
    		if (c[i].type == 'checkbox' && c[i].checked==true){
    			booked_seats[count]=c[i].id;
    		    count++;
    		}
    }
    This works fine and puts the reserved seats' ids in an array.
    My huge problem is how am I supposed to pass these booked seats as values to
    a querystring so I can update my localhost database, and specifically a table with 2 fields, SeatID and Availability.
    The difference from your project is that I want all these actions after the 'submit' button is clicked and not with a checkbox change event.
    I hope I'm clear with what I'd like to do and I'd appreciate any help.

  13. #13
    Join Date
    Jan 2011
    Posts
    62
    I think I get what your after. Do you want to stop for submission if there is a problem with the check boxes? ( none selected ) and use java to display errors before the form is submited or are you going to deal with error handeling after the form is submited?

    I ask because the solution depends on how the data is tranmited to the server from the form for processing.

    If you want Javascript to collect and verify the data before the form is sent then you need to somehow collect all the form eliments and then send them using Javascript instead of html submission. The Check box array should be sent as a JSON encoded string and decoded by PHP on the server. then you can explode the values for the check boxes. This is complex, but allows for better error handeling

    if you are going to use HTML to submit the form and PHP to deal with errors then you can A) use the built in checkbox array and then use PHP to step through that array pulling the needed values and building your sql string from them. This way you have tyo have an array of keys to match up with the check box array once its at the server os that the correct values can be match witht eh correct keys. or B) you can give each check box a unique name/ID and simply pull them from the $_REQUEST array and put them in the query string.

    In the code I posted I only wanted a JSON string to stor in the DB and used javascript to decode it when I was needed again. This made it easy to do, but made extending functionality and reusing that data else where much harder. in the ends I converted the JSON string to a comma deliminated string. that was then exploded and the vaules passed to an array with the needed keys. Then I steped through that array and build the SQL query.

    The final version was something like below. ( this is stripped down )
    As this form was NEVER designed to be submited, but rather to update the database 'live', I had to go with the onchange command to trigger the javascript. This way you could take the $formArray ['requests'] as your list of ALL room numbers and the $requestList as your list of selected rooms already stored in the DB.

    Code:
    $requestList = $reportObj->getRequestList ();
    $i = 0;
    $checkedArray=Array();
    if (isset ( $formArray ['requests'] ) && ! empty ( $formArray ['requests'] )) {
    	$checkedArray = explode(',', $formArray ['requests']);
    }
    foreach ( $requestList as $key => $request ) {
    	?><li><?php
    	if (isset ( $checkedArray ) && in_array ( $key, $checkedArray )) {
    		?><label><input TABINDEX='<?=$tabIndex++?>' class='comLog' type='checkbox' name='requests_cb' id='requests_cb' value='<?=$key?>' onchange="putData('ajax/accidentReport.ajax.php', '<?=$reportID?>', 'requests', '', this.id);" checked> <?=$request?></label><?php
    	}else{
    		?><label><input TABINDEX='<?=$tabIndex++?>' class='comLog' type='checkbox' name='requests_cb' id='requests_cb' value='<?=$key?>' onchange="putData('ajax/accidentReport.ajax.php', '<?=$reportID?>', 'requests', '', this.id);"> <?=$request?></label><?php
    	}
    		?>
    	</li>
    	<?php
    	
    	$i ++;
    	
    }
    The accidentReport.ajax file
    Code:
    if (isset ( $_REQUEST ['reportID'] )) {
    	$msg = "Report ID = {$_REQUEST['reportID']}";
    	config::writeLog($msg);
    	$reportID = $_REQUEST ['reportID'];
    } else {
    	$msg = "error no reportID Found";
    	config::writeLog($msg);
    	exit ();
    }
    
    // get value from post array
    if (isset ( $_REQUEST ['value'] )) {
    	$val = $_REQUEST ['value'];
    } else {
    	$msg = "error no value found";
    	config::writeLog($msg);
    	exit ();
    }
    
    // get the column to update
    if (isset ( $_REQUEST ['col'] )) {
    	$col = $_REQUEST ['col'];
    	
    	// fix for ems call times
    	switch ($col) {
    		case 'emsCallTime' :
    		case 'emsArrivalTime' :
    		case 'emsDepartTime' :
    			if ($val == false) {
    				$val = "";
    			} else {
    				$val = strtotime ( $val );
    			}
    			break;
    	}
    } else {
    	$msg = "error no colum name found";
    	config::writeLog($msg);
    	exit ();
    }
    
    // update the report where col to = val
    $query = "UPDATE " . config::table_prefix . "accident_log SET $col = '".mysql_escape_string($val)."' WHERE reportID = '$reportID' LIMIT 1";
    if($sqlObj->query($query)){
    	echo $val;
    }else{
    	$msg = "Error updating. $query";
    	config::writeLog($msg);
    }
    As you can see the $val is returned to the JS putData method using the echo command.

    I hope this helps, Its hard to apply these things to other peoples projects, but I think what you are after canbe achived using a method simler to this. Using these methods ( edited of course ) you should be easaly be able to create a live Ajax application that does not requier any real form submission and still the data updated on the DB.

    for your table I would say you need three colums id(int with auto incremented value), seatNumber (varchar(unique)) and booked(boolean or bit value)
    so your update stament would look somthing like this. ( guessing at the names you use)

    $query = "UPDATE seatBookings SET booked = '".$booked.'" WHERE seatNumber = '".$seatNumber."' LIMIT 1";

    Finaly please note I wrote this code a couple of years ago and I would not approch this problem in the same manner now as I did then. It works yes, but I was never happy with the code. The result was as desiered though, and in the end thats what matters to the client.
    Last edited by fideltfg; 01-30-2013 at 02:47 PM.
    Visit my live dev site @ http://knowcode.ca

  14. #14
    Join Date
    Jan 2013
    Posts
    3
    Do you want to stop for submission if there is a problem with the check boxes? ( none selected ) and use java to display errors before the form is submited or are you going to deal with error handeling after the form is submited?
    I think I can prevent the submission of a non-checked form using Javascript, I'm more used to this way of error-handling. So I guess,
    If you want Javascript to collect and verify the data before the form is sent then you need to somehow collect all the form eliments and then send them using Javascript instead of html submission. The Check box array should be sent as a JSON encoded string and decoded by PHP on the server. then you can explode the values for the check boxes. This is complex, but allows for better error handeling
    this is what I want to do.
    So do I need the JSON encoding/decoding to get the values of the javascript array I guess.
    In order to make it work, shall I keep my original function and add there the code (modified of course) you wrote? Or do I need a seperate php file?I'm doing this for the first time and I don't know exactly
    what to write (I'm really a newbie compared to you )
    Anywayz, I'll study the code and make a few tests, so I can ask you more specific things if I need.
    Thank you very much for your tips and help.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles