Post an object as data using Jquery Ajax

I will leave my original answer in place but the below is how you need to approach it. (Forgive me but it is a long time since I have used regular asp.net / web services with jquery:)

You need to use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.

var dataO = {
    numberId: "1", 
    companyId : "531"
};

var json = JSON2.stringify(dataO); 

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: json,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert('In Ajax');
    }
});

UPDATE: Same issue / answer here


All arrays passed to PHP must be object literals. Here's an example from JS/jQuery:

var myarray = {};  //must be declared as an object literal first

myarray[fld1] = val;  // then you can add elements and values
myarray[fld2] = val;
myarray[fld3] = Array();  // array assigned to an element must also be declared as object literal

etc...`

It can now be sent via Ajax in the data: parameter as follows:

data: { new_name: myarray },

PHP picks this up and reads it as a normal array without any decoding necessary. Here's an example:

$array = $_POST['new_name'];  // myarray became new_name (see above)
$fld1 = array['fld1'];
$fld2 = array['fld2'];
etc...

However, when you return an array to jQuery via Ajax it must first be encoded using JSON. Here's an example in PHP:

$return_array = json_encode($return_aray));
print_r($return_array);

And the output from that looks something like this:

{
    "fname":"James",
    "lname":"Feducia",
    "vip":"true",
    "owner":"false",
    "cell_phone":"(801) 666-0909",
    "email":"[email protected]", 
    "contact_pk":"",
    "travel_agent":""
}

{again we see the object literal encoding tags} now this can be read by JS/jQuery as an array without any further action inside JS/jQuery... Here's an example in jQuery ajax:

success: function(result) {
    console.log(result);
    alert( "Return Values: " + result['fname'] + " " + result['lname'] );
}

Is not necessary to pass the data as JSON string, you can pass the object directly, without defining contentType or dataType, like this:

$.ajax({
    type: "POST",
    url: "TelephoneNumbers.aspx/DeleteNumber",
    data: data0,

    success: function(data)
    {
        alert('Done');
    }
});