cagin
cagin

Reputation: 5920

$(document).ready doesn't work however page is loaded

As you can understand my title, browser doesn't call the GetReleatedProducts method. I put breakpoint $(document).ready(function () line but it doesn't enter into ajax call. I checked that I have jquery reference. Do you have any idea?

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "http://localhost:2782/AjaxCallPage.aspx/GetReleatedProducts",
        data: "{productId:" + productId + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {...}

Upvotes: 0

Views: 137

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

You've told the server you're sending it JSON:

contentType: "application/json; charset=utf-8",

...but what you're sending it:

data: "{productId:" + productId + "}",

...is not valid JSON. To be valid JSON, the key productId must be in double quotes:

data: '{"productId":' + productId + '}',
//      ^         ^

(Here I'm assuming productId is a number. If it's a string, it will also need to be in double quotes.)

So I suspect the server side is rejecting the call because the JSON is invalid.

It's also a bit unusual to send JSON to the server, although it's perfectly valid if that server is coded to expect it and if you send it correctly. It's more typical to send data to the server using the default application/x-www-form-urlencoded.

So unless you've coded your server side to expect to receive JSON, remove the contentType option from your $.ajax call and change data to:

data: {productId: productId}

...which tells jQuery to do the encoding for you.

Upvotes: 2

Related Questions