Zaki Aziz
Zaki Aziz

Reputation: 3852

Passing data through a jQuery .post() function

I usually pass data through .post() like this:

 $.post(
    "/ajax.php",
    $("#form").serialize(),
    function(responseJSON) {
        console.log(responseJSON);
    },
    "html"
);

Within my form "#form" I usually have a hidden input with the name "id" which holds a value to the id of the item I want to run queries on.

What I want to do is take out that hidden input and add in a data-id="$id" attribute in my submit button and have the jQuery function extract the data from there and send that along with the other #form fields.

In simple terms what I'm asking is how do I pass along $('#form').serialize() along with $('#button').data('id') over to my back end all in one $.post() function?

Upvotes: 0

Views: 381

Answers (3)

pocesar
pocesar

Reputation: 7050

you may try a library that does that for you automatically, you don't need to worry about the inner workings, using http://phery-php-ajax.net/

Phery::instance()->set(array(
   'function' => function($data){ 
       // $data['id'] = the hidden in your form
       return PheryResponse::factory()->json($your_array_that_will_be_turned_to_json);
   }
))->process();
<form data-remote="function" method="POST">
  <input type="hidden" name="id">
</form>

In your Javascript, you may deal with the JSON

$(function(){
  $('form').bind('phery:json', function(event, json_data){
    // deal with your json_data
  }
});

Upvotes: 0

alanmanderson
alanmanderson

Reputation: 8200

.serialize() just creates a string with the data. You just need to append &<variable>=<value> to the end.

Upvotes: 1

airyt
airyt

Reputation: 352

try this

var data = $("#form").serialize() + '&data-id=' + $('#button').data('id');
$.post(
    "/ajax.php",
    data,
    function(responseJSON) {
        console.log(responseJSON);
    },
    "html"
);

Upvotes: 1

Related Questions