简体   繁体   中英

Is there a way to use jQuery and AJAX to post a form without any serialization?

I have a form containing dynamically created checkboxes that filter data to be displayed:

$html .= "<form id='optionsForm'action='filter.php' method='post'>";
foreach($selectValues as $key => $value){
    $title=new MODEL\String($key);
    $html.= "<fieldset class='optionsBox'>";
    $html.= "<legend>".$title->friendlify()."</legend><br/>";
    foreach($value as $option){
            $html .= "<input type='checkbox' name='".$key."[]' value='$option'>".htmlspecialchars($option)."</input>";
    }
    $html.= "</fieldset>";
}
$html .= "</select><input type='submit' value='submit'></form></div>";

This builds multiple arrays containing the values of the checkboxes, eg

 name =>
      [0] value1
      [1] value2

 newname =>
      [0] value1
      [1] value2

Once it is submitted the arrays are passed to a php function that breaks them apart and then uses the data to run queries.

My problem is that when I use a jQuery .ajax function it serializes the data and I can't work with it the way I want.

What is the easist way to use the same form action I have to process the form but have the results displayed in a div below the checkboxes?

I guess the better question is when filter.php which is used in the form action gets the information what is the variable name going to be when it comes from ajax? right now i just use the _POST variable and set that equal to my new array name.

$('#optionsForm').submit(function() {

    $.ajax({
        url: this.action,
        type: "POST"
        data: $(this).serialize(),
        // ...
        // add success/complete/error handlers
    });
    return false;

});

.serialize() will format the data just as if it were a standard form submitted with a submit button.

Clicking your submit button will execute this ajax and prevent the default form action.

If you don't like the way jQuery serializes the data you can prepare your own payload based on the form values before you POST to the server. You should be able to format the data however you wish.

you can simply use

$.post("test.php?data1=1&data2=2", function(data) {
   alert("Data Loaded: " + data);
 });

and from server side you will need to request each varable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM