开发者

PHP and Jquery - getting array value

I have a gallery where the user rates the images. I'm busy trying to get jquery going so it updates without reloading the page. So far, I've managed to get the selected radio button for the rating, so what I'm trying to do now is get the ID of the image, so I can post the rating and image id to a PHP function to handle updating the rating in the database.

My question is, how do I get the image id from the array in PHP, to Jquery?

Using Codeigniter 2.0.3

radio form:

echo form_open('home/rate_image/'.$image['image_id'], array('id' => 'form_rate');

$counter = 1;
$form = 1;
while($counter < 11){
    echo form_radio('rate', $form, FALSE).$form.' ';
    $counter ++;
    $form ++;
}

echo '<br />';
echo form_submit('submit', 'Vote');
echo 开发者_如何学JAVAform_close();

Jquery (which is wonky atm XP):

$(document).ready(function(){
    $('#form_rate').submit(function(e){
            e.preventDefault();

        var rating = $("input[name='rate']:checked").val(); 
        var image_id = (*where I want image ID from image array in PHP);

        // hide form
        $('#form_rate').hide();

        if(rating == null){
            $('#imageContainer').html('Please select a rating before voting');
            $('#form_rate').show();
        }else{
            $('#imageContainer').html('You have selected a rating of '+ rating + ' for the image '+ image_id);
        }

        // ajax code to post rating and image_id to update rating

    });
});

image id I want to pass to jquery:

$image['image_id']


Make the name of the radio buttons the ID. Or make part of it the ID, like <input type="radio" name="rating[<?=$id?>]" value="xxx>.

Send that to PHP as is (i.e. use the serialize function of jQuery).


As a general rule that I apply myself:

  • From Javascript to PHP => use hidden input fields.
  • From PHP to Javascript => print whatever you want to transfer to javascript somewhere in the head section and then read it with javascript.


The first part of the OPs question says "trying to get jquery going so it updates without reloading the page."

AFAIK the .submit() method in jquery will submit the form and thus reload the page.

You should be looking at the following methods to perform an AJAX request that will allow you to send the rating to the database without having to reload the page.

http://api.jquery.com/jQuery.ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜