0

I have to parse my html from and POST it to another script. When I use JSON.stringify to serialize object with parsed data, $_POST array in the receiving script is empty:

$("#addQueryForm").submit(function(event){
  event.preventDefault();
  result = {}     
  result['kindArr'];
  result['factor'];
  $("[rel=my-form]").each(function() {
    result[$(this).attr("name")] = $(this).attr("value");
  }); 
  var form = JSON.stringify(result);    
  $.post("add_kind.php", form , function(data) {
    alert(data);  
    //data shows me that $_POST array is empty
  }); 
});

But if I write json string into the query manually, it would be correct:

$.post("add_kind.php", {"kind":"Var1","kindArr":"Var12345","factor":"Var0","synonym1":"Var1","synonym2":"Var2","synonym3":"Var3"} , function(data) {
    alert(data);  
    //data shows me that $_POST contains posted data
});

What am I doing wrong?

P.S: stringify was excess.

5
  • you can use $('#form').serialize() Commented Feb 7, 2013 at 12:05
  • 2
    Your second version isn't a JSON string, it's a Javascript object. jQuery converts it to www-form-urlencoded format, not JSON. Commented Feb 7, 2013 at 12:07
  • You don't need to stringify the result, jQuery handles everything correctly for you. So handing in result should work just fine. However, strings work too, so there might be something wrong how you build it. Does ("[rel=my-form]") yield the desired result-set? Commented Feb 7, 2013 at 12:07
  • @Christoph yes, all data is correct, but when I send them with var, something goes wrong. Commented Feb 7, 2013 at 12:10
  • @Barmar yes, it was my mistake. You're right. Thanks! Without stringify it works. :) Commented Feb 7, 2013 at 12:13

1 Answer 1

2

Maybe serialize would be better in your situation:

var form = $(this).serialize();    
$.post("add_kind.php", form, function(data) {
    alert(data);
});
Sign up to request clarification or add additional context in comments.

2 Comments

No, I append some inputs after page loads and form = $(this).serialize(); cannot get them, isn't it?
If they are part of your form - serialize will get them too.

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.