Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax is sending GET instead of POST

Tags:

jquery

ajax

The following code triggers a GET instead of a POST HTTP request.

function AddToDatabase() {   this.url = './api/add'; }  AddToDatabase.prototype.postData = function(dataToPost) { $.ajax({     type: "POST",     url: this.url,     data: dataToPost,     context: this,     success: this.onSuccess   }); };   var AddToDatabase = new AddToDatabase(); data = {data: 'coucou'}; AddToDatabase.postData(data); 

Why, and how can I get a POST ?


I see in Google Chrome Inspect and Firefox Inspect that the browser sends a GET. Here is from Chrome:

Request URL:http://localhost/SAMPLE-CODES/UPDATE%20MYSQL/api/add/ Request Method:GET Status Code:200 OK


SOLVED

The URL called './api/add' was to actually post to './api/add/index.php'. Turns out that calling './api/add/index.php' or './api/add/' gives me a POST request.

It was just a wrong URL, but for some reason I was getting a successful GET request to '.api/add/'.

like image 668
Timothée HENRY Avatar asked Aug 30 '12 11:08

Timothée HENRY


People also ask

Does Ajax use Get or Post?

GET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.

How to send data using POST method in ajax?

The jQuery. post( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request. data − This optional parameter represents key/value pairs or the return value of the .

How to GET response from ajax POST?

You should probably just include it in the json you send out. Otherwise, it will just be returned to you as text. Show activity on this post. Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.


2 Answers

Some problem on MVC. For some reason when I remove the [HttPost] it works as expected, even though I am telling ajax to use POST .

  • It turns out you need to use

type: "POST"

  • Even though the example on jQuery page says to use

method : "POST"

Now it POST's

But after digging in the documentation I found this.

enter image description here

like image 86
Piotr Kula Avatar answered Oct 12 '22 06:10

Piotr Kula


I had this issue and per @FAngle's suggestion it was because my .htaccess was removing trailing slashes — and I had set the url to /ajax/foo/bar/ and not/ajax/foo/bar. The redirect changes the request from POST to GET. Remove the / and problem solved!

like image 35
texelate Avatar answered Oct 12 '22 07:10

texelate