I am desperately trying to manually create a JSON-style array in Javascript to send over the network via jQuery's AJAX method.

var fieldsobj = {fields:[]}
$(".fact_field", fact).each(function(index, field){
    var index  = $(field).attr("data-index");
    var name  = $(".fact_field_label", field).text().trim();
    var value  = $(".fact_field_value", field).text().trim();
    fieldsobj["fields"].push({index:index, name:name, value:value});
});
//...
$.ajax({
    type: 'PUT',
    url: url,
    data: fieldsobj,
    success: function(data){...
    },
    complete: function(){...
    }
});

What I want is the following:

{fields => [{index:0, name:1, value:2},{...},{...}]}

What I get is this:

 {"fields"=>{"0"=>{...}, "1"=>{..}, "2"=>{...}, "3"=>{...}}

What am I doing wrong?

share|improve this question

2 Answers

up vote 5 down vote accepted

When you pass an object as the data property, jQuery will pass it as url-encoded form parameters (e.g. foo=bar&moo=too) in the body. I think what you want is to pass JSON through the body.

Grab the json2.js written by uncle Crockford and use JSON.stringify (that library provides the functionality for browsers that still don't support it):

$.ajax({
    type: 'PUT',
    url: url,
    data: JSON.stringify(fieldsobj),
    contentType: "application/json",
    success: function(data){...
    },
    complete: function(){...
    }
});

And don't forget to set the contentType property! On the PHP side, you can use json_decode to decode the raw body content:

$fieldsobj = json_decode(@file_get_contents('php://input'));
share|improve this answer
@Darko Z: Thanks for correcting serialize to stringify. – Ates Goral Feb 18 '11 at 5:44
Great! I tried JSON.stringify before but I forgot about the content type. – Denny Feb 18 '11 at 6:20

May be this helps.

<ul>
    <li id="p1" data-age="40">John</li>
    <li id="p2" data-age="28">Jack</li>
    <li id="p3" data-age="50">Nash</li>
</ul>

<script>
var a = [];
$("li").each(function(i){
    var o = {};
    o.id = $(this).attr("id");
    o.age = $(this).attr("data-age");
    o.name = $(this).text();
    a.push(o);
});
console.log(a);
//var a = [{id:"p1",age:40, name:"John"},{id:"p2",age:28, name:"Jack"},{id:"p3",age:50, name:"Nash"}];
</script>
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.