Wordpress with jquery add items to an array and post it for php

77 views Asked by At

I'm creating a wordpress plugin that will get all the schools and choose 3 of them in a rankings box. So I'm trying to get all the post_ids from a group of checkboxes using jquery and post them for my php function. From my code below, how should I do it?

Here's my HTML and PHP code:

<?php foreach ($all_schools as $data):?>            
<div class="rank_box">
    <div class="left">                                          
        <div class="checkbox">
            <label class="pull-left"><input type="checkbox" name="nationality" value="<?php echo $data->post_id; ?>"></label>
        </div>  
    </div>
    <div class="right">
        <p><?php 
                if(strlen($data->school_name) >= 30){
                    echo substr($data->school_name,0,30)."…";
                }else{
                    echo $data->school_name; 
                }
            ?><br>                  
        </p>
    </div>
</div>

<?php endforeach;?>

<div id="divnationality">   
</div>

And my jquery:

$(document).ready(function(){
    $('input[name="nationality"]').click(function () {              
            getSelectedBoxes('nationality');
    });

    var getSelectedBoxes = function (groupName) {
        var result = $('input[name="' + groupName + '"]:checked');
        if (result.length > 0) {
            var resultString = result.length + " checkboxe(s) checked<br/>";
            result.each(function () {
                resultString += $(this).val() + "<br/>";
            });
            $('#div' + groupName).html(resultString);
        }
        else {
            $('#div' + groupName).html("No checkbox checked");
        }
    };
});
1

There are 1 answers

3
Matt On

Within the .click function, I would just do:

var is_checked = $(this).prop("checked");

if (is_checked) ...

$(this).val() should also get the input value, regardless of whether it's checked or not.

To post the value data to PHP, use $.ajax() (more info here) like this:

var post_data = {};

if (is_checked) {
    var value = $(this).val();
    post_data[value] = value;
}

$.ajax({
    url: 'YOUR_POST_URL',
    type: 'POST',
    data: post_data,
    error: function(jqXHR, textStatus, errorThrown) {
        alert(errorThrown);
    },
    success: function(data) {

    }
});