1
votes

I am trying to submit a form using jQuery's .ajax() function. It seems like it should be pretty simple but for some reason I can't get the type: "POST" to work correctly. Using type: "GET" works no problem, but "POST" doesn't seem to actually post anything to my accepting php script. When I do a print_r($_POST) it returns me an empty array. I've tried using both input type "submit" and "button" on the form input but it doesn't seem to change anything. Any ideas why it's not working?

Ps - there are more than 1 forms on this page.

Edit for Clarification
If I do a print_r($_GET) when i use type:"GET", it prints out all the correct data, but if i change the .ajax option to type:"POST" and try to print_r($_POST) it shows a blank array with no content.

Js Code:

var dataString = 'reply_text='+ test + '&post_id=' + post_id ;

$.ajax({
  type: "POST",
  url: "process.php",
  data: dataString,
  cache: false
  });
  return false;

Form Code:

<form action="" method="post">
<textarea id="textboxcontent" name="reply_text"/>
<input type="submit" name="reply_submit" value="submit comment"/>
</form>
4
Where does the dataString variable used in your ajax request come from?Darin Dimitrov
I was just about to ask the same thing.Jacob Relkin
Hi Darin, dataString comes directly before the .ajax request: var dataString = 'reply_text='+ text + '&post_id='+ post_id; And I know the dataString is working correctly because when I use GET it works fine. Should I be using a different string format?justinl
ps - I've added the dataString to the question abovejustinl

4 Answers

2
votes

This might work better:

var text = ...
var post_id = ...

$.ajax({
    type: 'POST',
    url: 'process.php',
    data: { reply_text: text, post_id: post_id }
});
0
votes

How do you hookup your event? Are you sure that it's beign triggered? Tried putting an alert or something in there, to make sure?

What does your dataString look like? type: 'POST' is enough to make the ajax callback a post, so it might be your data that's being passed in a bad manner.

0
votes

If you want to post forms with AJAX, I suggest the jQuery Form Plugin, which does so nicely and unobtrusively.

0
votes
var formData = {
    'test': $('input[name=text]').val(),
    'post_id': $('input[name=post_id]').val()
};

// process the form
$.ajax({
    type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
    url: 'process.php', // the url where we want to POST
    data: formData, // our data object
    dataType: 'html', // what type of data do we expect back from the server
    encode: true,
    success: function(updatedTable) {
        //alert(updatedTable);
        $('div#tableHolder').html(updatedTable);
    }
})