user8108238
user8108238

Reputation: 79

javascript - jquery $.post doesn't work

I just get started in Ajax and httpRequest. While I was playing around with the code, I noticed that $.get works fine but $.post doesn't work. Here's my code:

$(document).ready(function() {
    $.post('hello.txt', function(data) {
        alert(data);
    }).fail(function() {
        alert('fail');
    });
});

It always gives me a fail, and I cannot figure it out. Thanks

Upvotes: 0

Views: 882

Answers (1)

Jonathan Michalik
Jonathan Michalik

Reputation: 1532

Barmar is correct in the comments, but for an answer, let's go over what it is these functions are doing.

When you're using the jQuery AJAX methods, they are performing HTTP requests to the resource you're providing in the url parameter for the function. As long as the value is something sitting on your server (an endpoint) the function will hit it.

$.get() performs an HTTP GET action which is how we'd fetch data over HTTP. In your example, you specify hello.txt as the url, which as long as that is a file sitting on your server, the application will make a GET request to that resource. If it is found, the contents of that resource are returned. This can be done with a text file, a JSON payload, HTML web pages, etc. As long as the resource has returnable content, it will return that content.

$.post(), on the other hand, performs an HTTP POST action which sends data up to a resource to be processed. A POST action is not intended to fetch a resource's data, but to push data into it. Canonically, you would use a POST to create something with the data you push to the resource (as opposed to PUT for modifying and DELETE for removal, but that's beyond this answer).

So, the GET works because the action is intended to fetch data and the resource you provided has data to return. The POST fails because it is intended to give data to the resource to process, which your text file is not equipped to handle.

Hope this sheds a bit of light on the problem.

Upvotes: 1

Related Questions