balexander
balexander

Reputation: 24399

jQuery Ajax request to Web Method

I am trying to send data to my code behind method. It works except when I add to the data param.

function (obj) {
   $.ajax({
       type: "POST",
       url: "Pages.aspx/EditPage",
       data: "{'nodeID': '" + $(this).attr('id') + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
               // Replace the div's content with the page method's return.
       }
     });
    }

Why is the param i added causing the Web Method to not get hit?

UPDATE: After seeing what client side errors were being thrown it seems that the ID is undefined. Is my method of getting the elements ID incorrect? Keep in mind I am using jsTree and ca I possibly use (obj)?

Upvotes: 1

Views: 957

Answers (5)

Kyle
Kyle

Reputation: 22278

The 'this' reference you are using is referring to the jQuery 'this'. Therfore, your ID is not defined.

Assuming you are trying to get the id of 'obj' from your function argument, I would rewrite the function like this:

jQuery.fn.your_func_name = function(){

   $.ajax({
       type: "POST",
       url: "Pages.aspx/EditPage",
       data: "{'nodeID': '" + $(this).attr('id') + "'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
       // Replace the div's content with the page method's return.

  });

}//function

Use it like this:

$('#some_element').your_func_name();

Upvotes: 0

balexander
balexander

Reputation: 24399

After debugging in Chrome, I discovered the ID wasn't defined. I rewrote the date param to:

data: '{"nodeID": "' + obj.attr('id') + '"}',

because the obj is the node i'm currently on in jsTree.

Thanks to everyone reminding me to debug in either FF or Chrome and adjusting the quotation marks.

Upvotes: 0

Sang Suantak
Sang Suantak

Reputation: 5265

try this:

data: "{nodeID: '" + $(this).attr('id') + "'}",

Edit: as for getting id, you can use this.id

Upvotes: 0

David Glass
David Glass

Reputation: 2384

A few things to try

  1. Remove the contentType
  2. Remove the quotes around the JSON keys
  3. Swap the single and double quotes

It will look like this:

function (obj) {
   $.ajax({
       type: "POST",
       url: "Pages.aspx/EditPage",
       data: '{nodeID: "' + $(this).attr('id') + '"}',
       dataType: "json",
       success: function (msg) {
               alert('success!');
       }
   });
}

Upvotes: 0

kobe
kobe

Reputation: 15835

try something as below:

jQuery.parseJSON('{"name":"John"}');

Upvotes: 1

Related Questions