38

My code that I tried is as follows:

var dataO = new Object();
dataO.numberId = 1;
dataO.companyId = 531;

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

I would like to pass the object dataO as the ajax data, how can I do it?

6 Answers 6

50

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

Sign up to request clarification or add additional context in comments.

3 Comments

@plattsy the param method was not the best when this was written. Changed in 1.4
I assume it is no longer needed to use JSON2 instead of JSON, as of 2015 (unless requiring compatibility with old browsers). Is that right?
Correct @Janos unless you targeting ie8 etc
10

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'] );
}

2 Comments

Also this is a very old post, but in newer Server Applications, you don't need JSON to post requests. For Example in CQmvc (github.com/mohamad-z/CQmvc) one can leave dataO object be dataO.numberId:1 and dataO.companyId:531 and post the data. In the Server side, your Action's argument should be DeleteNumber(ObjectRepresentingYourSpecificType dataO) and thats it
Plus one for using plain English without ambiguity when describing your example.
9

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');
    }
});

Comments

5

Just pass the object as is. Note you can create the object as follows

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

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

UPDATE seems an odd issue with the serializer, maybe it is expecting a string, out of interest can you try the following.

data: "{'numberId':'1', 'companyId ':'531'}",

4 Comments

the data is the request looks like numberId=1&companyId=531 and i get "Message":"Invalid JSON primitive: numberId.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer .DeserializePrimitiveObject()
can you try it with the quotes like the amended above
can you try the above? I know its not an answer but just out of interest
Yeah I did try it got the same message.
3

[object Object] This means somewhere the object is being converted to a string.

Converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product + ''); 

Not converted to a string:

//Copy and paste in the browser console to see result

var product = {'name':'test'};
JSON.stringify(product);

Comments

2

You may pass an object to the data option in $.ajax. jQuery will send this as regular post data, just like a normal HTML form.

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

1 Comment

I've already tried this and my .net webmethod has issue's deserialising the request.

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.