Doubt about $.post and $.ajax behavior

Asked

Viewed 80 times

6

I’ve always been used to using $.ajax() for all my requests of the type, and this works perfectly. An example that is even occurring now is the following:

 $.ajax({
        type: "POST",
        url: "XmlTree.aspx/GetChildren",
        data: {id : teste},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            if (callback) {
                callback(msg);
            }
        },
        error: function (msg) {
            if (callback){
                callback(msg);
            }
        }
    });

Calling so, it falls into the method I intended. Everything works right as the image below shows:
inserir a descrição da imagem aqui

However, I did read about the $.post and your syntax seemed to me much simpler, and I decided to test, in the following way:

$.post( "XmlTree.aspx/GetChildren", { id : "S1000" } );

the problem is that regardless of my parameters, using $.post it always falls in Page_load, as shown in the image:

inserir a descrição da imagem aqui

I am aware of the existence of this question: What are the advantages of using the right HTTP methods?.

But still I could not understand the reason for this behavior. The $.post should also not fall directly into my method GetChildren?

  • Using the function $.post you need to serialize the data on your own. Try ordering the address and pass a string as parameter -> $.post( "XmlTree.aspx/GetChildren", JSON.stringify({id : "S1000" }) );

  • @LINQ he accepts a PlainObject also.

  • @Andersoncarloswoss But it will probably send as formdata and the backend will not deserialize it

  • Artur, this is Webforms?

  • @LINQ tried to pass the data as a string, but still fell into Load :/. Yes, it’s Webforms

  • You would need to see how are the two requests, have something that differentiates the two and makes the backend treat them differently.

  • @LINQ went to analyze the payload in the Network tab of Chrome devtools, and although both are equal, the $.post appears as Formdata, even though I put it in string form, and the $.ajax string.

  • @Arturotemplario Apparently you have no choice, $.post will always send a formdata.

  • @LINQ understood, so I assume the situations in which the $.post can be used correctly are answered in the question I mentioned

Show 4 more comments

1 answer

1

The method post accepts 4 parameters, according to the documentation.

jQuery.post( url [, data ] [, success ] [, dataType ] )

So you can make the same call setando the data type sent as json thus:

$.post('XmlTree.aspx/GetChildren', { id : 'S1000' }, 
    function (msg) { ... }, 
    'json'
);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.