0

I have a form that I'm trying to submit via AJAX. The easiest way for me to pass the data would be using $("#myForm").serialize(), however, when doing so, the page to which I'm posting to doesn't receive the data.

Here's my form:

<form id="myForm">
    <input name="field" id="field">
    <button id="submitBtn" type="button">
</form>

And this is my function:

$("#submitBtn").click(function(){

    alert($("#myForm").serialize()) //For testing – does alert "field=value"

    var post = $.post("actions.php", $("#myForm").serialize());
    post.done(function(d){alert(d)}); //Only alerts [PHPSESSID]

    var post = $.post("actions.php", {field:"fieldVal"});
    post.done(function(d){alert(d)}); //Alerts [PHPSESSID] and ['field']

});

This is my whole actions.php file:

<?php
print_r($_REQUEST);
exit();

Why is passing the values as JSON working but .serialize() isn't??

Emilio Venegas
  • 546
  • 5
  • 22

2 Answers2

0

Looks like I just had to pass the serialized form as a variable instead of serializing it inside the $.post() function. As so:

var postData = $("#myForm").serialize()

var post = $.post("actions.php", postData);
post.done(function(d){alert(d)});

Not sure why it works when established outside and not inside the function, maybe a conflict issue. Thanks to everyone anyway

Emilio Venegas
  • 546
  • 5
  • 22
-1

Use serializeArray() instead: https://api.jquery.com/serializeArray/

phirschybar
  • 8,357
  • 12
  • 50
  • 66