1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.