1

I've dealt with javascript in the past, but I'm trying to relearn it. For that reason I'd like to come up with a javascript solution without the use of libraries like JQuery.

I've come across several threads, and they have been close but not a perfect match to my situation.

I have a form generated dynamically by PHP, it grabs info from the database, and echoes out all the form inputs. They are all checkboxes representing the entry in the database. Normally I would use name="id[value]" where value is the id of the current entry being looped through.

So I would have something like this:

<input type="checkbox" name="del[1]"/>
<input type="checkbox" name="del[2]"/>
<input type="checkbox" name="del[3]"/>

When I would post this on form submit, I would just get the value of $_POST['del'] and call it a day. However, I'm trying to send it to a PHP page with an AJAX function so i can perform the functions without changing the page or refreshing.

My question is: How do I get all of the checkboxes(that are checked) and send them to the PHP page so it can understand which ones were checked. My understanding is that this will require some kind of conversion. My first though was to loop through each checked box, and grab its index (or give them all Ids and grab the id) and put it into a string that I could then explode PHP side.

Any thoughts? Thanks, sharf.

3 Answers 3

1
var i, child, str='', arr = Array(),
    form = document.getElementById('form')

for(i=0; i<form.childNodes.length; i++) {
    // grab the element
    var child = form.childNodes[i];
    // make sure it is an input and a checkbox
    if(child.tagName!='INPUT' || child.getAttribute('type')!='checkbox') continue
    // if the checkbox is checked, add the name and value to a url string
    if(child.checked)
        arr.push(child.getAttribute('name')+'='+encodeURIComponent(child.value))
    }
}

// make the URL string
str = arr.join('&')

// now you can use this as a url: 
SomeAjaxUrl + str

Then, in PHP:

<?php
    $checked_options = $_REQUEST['del'];
    print_r($checked_options);
?>
Sign up to request clarification or add additional context in comments.

4 Comments

I like this approach, but it's not behaving the way I think it should, perhaps I'm doing something wrong. It doesn't seem that str ever has anything in it. I have tried to get the results of str multiple times and nothing happens.
I ended up using a modified version of this. I concatenated everything into one string to pass, then exploded on the PHP end.
@sharf: If the action done is about sensitive/important information, I suggest you not to use a $_GET or encoded URL, unless you added several security processes to counter any possible external user interaction.
@JeffNoel I am passing via $_POST, not $_GET.
0

You can use jquery like you said and loop though

http://api.jquery.com/attribute-starts-with-selector/

But for ease i would look at something similar to backbone forms https://github.com/powmedia/backbone-forms

which manages your model for you and lets you send by ajax easily.

Their github has much more info on there along with some examples. This puts the checkboes in an array which you can handle php side easily

edit: pure javascript

var pairs = [];
var form = document.getelementbyid("form");
for ( var i = 0; i < form.elements.length; i++ ) {
   var e = form.elements[i];
   pairs.push(encodeURIComponent(e.name) + "=" + encodeURIComponent(e.value));
}
var output= pairs.join("&");

You should be able to modify that pretty easy

3 Comments

I said I didn't want to use a library, ie. jquery
re learning javascipt without jquery is a mistake. The above way is the "hard" way to go about it. $('#myFormId').formSerialize(); is much easier and will give you exactly what you need. jquery is open source so look at how the serialize method works
it should be noted encodeURIComponent(e.name) may not give the expected result as it will turn [] into %5B%5D
0

Use JSON.stringify()(MDN) to fix your problem. You can convert an Array or an Object to a valid JSON Object which can be sent through AJAX.

2 Comments

Why do you post 'Solution' in your answer? The question asker will device if it is a solution..
Usualy I also post examples and thorough explanations, leading to sections with separators. That's a formatting habit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.