开发者

Insert Form Input values into array AND retain custom Key indexes

I am working with a form with elements like this:

<form id="post">
   <div id="related_posts">
        <input type="hidden" class='related' name="reladded[72]" value="12" />
        <input type="hidden" class='related' name="reladded[34]" value="21" />
        <input type="hidden" class='related' name="reladded[46]" value="33" />
   <div>
</form>

When I submit this using the standard form process, I get an array, which looks like:

array('72'=> '12,'34'=> '21,'46'=> '33')

which I then serialize and save to a database.

How can I use JQuery to collect the same elements from those fields and convert them to a serialized array, so I can submit via AJAX POST?

I have all the AJAX开发者_StackOverflow code covered, but I can't yet iterate the elements to collect the correct array values. There are other elements in the form, but these ones are the only ones I want to submit.

I have tried methods like the following, to no avail:

var serialrel = $('#post input:hidden[name="reladded"]').serialize();

Please help!


You can use .serialize() on the form element

$("#post").serialize();


Here's what I came up with, to get the formatted array as per above:

reladded = new Array();
jQuery("#related-posts").find('input.related').each(function() {
    jQuery.each(this.attributes, function(i, attrib){
     var name = attrib.name;
     var value = attrib.value;
     if( name=='name' ){
         arrayNameAndKey = value; //get 'reladded[*]' (key for array)    
    }
     if( name=='value' ){
        arrayValue = value; //get input value
     }
    });
    //add entry to 'reladded' array from name attr. and input values
    eval(arrayNameAndKey +"='"+arrayValue+"'");
}); 

After I submitted the array via AJAX, I then had to remove all the 'undefined' array values that javascript added in, between mine. Here's the code I used for that:

<?php
    $related = $_POST['reladded'];
    //clean javascript crud
    if(is_array($related)){
            foreach($related as $key=>$value){
        if($value=="undefined")
        unset($related[$key]);
    }
?>

Definitely open to more elegant ways to do this...

Note - I actually didn't need to serialize the array in JQuery, since I was just passing it through to PHP with AJAX. I did the serialization there instead.

My main goal was retaining the custom key indexes in the retrieved array - that is what I want suggestions on how to do more easily, if possible....thanks!!!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜