views:

182

answers:

2

Is it possible to access $_POST variables without appending all the form elements into the data attribute?

Ajax call:

$.ajax({
       type: "POST",
       url: "ajax/user.php",
       data: {**data**},
       success: this.saveUserResponse
     });

Accessing variables:

if(isset($_POST['saveUser']) && $_POST['saveUser']){
  $user = $_POST['username'];
  ...
  ...  
  exit;
}

Or do i need to append all form elements to the data attribute, like:

var userId = $('#userId').val();
$.ajax({
       type: "POST",
       url: "ajax/user.php",
       data: {user : userId, etc...  },
       success: this.saveUserResponse
     });

Thanks for your help

+1  A: 

You can use the .serialize() method on the form to do that for you.

$.ajax({
       type: "POST",
       url: "ajax/user.php",
       data: $("#formid").serialize(),
       success: this.saveUserResponse
     });

See Help with Jquery and multiple forms on a page.

You can also use the jQuery Form plugin to make this work a lot simpler. Using that, you can create a normal form in HTML (which you already have), set it up using method="POST" and action="ajax/user.php", and then call $("#formid").ajaxForm(this.saveUserResponse) on load. This sets up everything and has the additional advantage that it will probably also work (in most rudimentary form) when JavaScript is disabled.

MvanGeest
thanks for posting the link. very helpful!
Kel
+1  A: 

jQuery will only send data that you explicitly pass to the server.

You can pass the values of all of the form elements by passing $('form').serialize().

SLaks
thank you very much!
Kel