Lancelot
Lancelot

Reputation: 1441

Post jQuery form serialized data to php

I'm trying to post a serialized data from jQuery to php like the following.

$.post(location.href, $('form').serialize(), function(data){
    // do something
});

It's working very well. But is there a way I can set a name to the serialized data, so I can use that name for isset() function? It'll look like this:

Let's assume the form has

<input type="text" name="input1">
<input type="text" name="input2">

file.js

$.post(location.href, {data:$('form').serialize()}, function(data){
    // do something
});

file.php

<?php
    if (isset($_POST['data'])) {
        // retrieve the data in the serialized string and use it in a function
        helperFunction($_POST['input1'], $_POST['input2']);
    }
?>

<html>
    // rest of the layout
</html>

I don't want to use a button to submit the form. The reasons I don't want it are:

  1. Using <button type="submit">Submit</button>, then submit the form to the same page will ask for re-submission when I refresh the page (which I don't want it) after I submit the form.
  2. Using jQuery to post the serialized data to the server will not ask for re-submission when I refresh the page after I post.

Upvotes: 1

Views: 1651

Answers (2)

zelibobla
zelibobla

Reputation: 1508

Since PHP parse arrays from submitted POST data you can manipulate like this:

<input type="text" name="inputs[data][1]">
<input type="text" name="inputs[data][2]">

<?php
    if( isset( $_POST[ 'inputs' ][ 'data' ] ) ) {
        helperFunction( $_POST[ 'inputs' ][ 'data' ][ '1' ], $_POST[ 'inputs' ][ 'data' ][ '2' ] );
    }
?>

But actually I don't see a reason why not to do more simple:

<input type="text" name="input1">
<input type="text" name="input2">

<?php
    if ( isset( $_POST[ 'input1' ] ) &&
         isset( $_POST[ 'input2' ] ) ){
        helperFunction( $_POST[ 'input1' ], $_POST[ 'ipnut2' ] );
    }
?>

Upvotes: 1

harry
harry

Reputation: 1007

you can add a hidden variable and check it in post value.

<input type="hidden" name="check_val" value="chek_val" />
<?php

if(isset($_POST['check_val'])) {

} ?>

Upvotes: 2

Related Questions