Paul
Paul

Reputation: 6737

Convert JavaScript object to JSON and POST it

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.

Upvotes: 0

Views: 937

Answers (1)

dfsq
dfsq

Reputation: 193261

Maybe serialize would be better in your situation:

var form = $(this).serialize();    
$.post("add_kind.php", form, function(data) {
    alert(data);
});

Upvotes: 2

Related Questions