JQuery Ajax is sending GET instead of POST

JqueryAjax

Jquery Problem Overview


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/'.

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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!

Solution 3 - Jquery

The URL './api/add' actually got redirected to './api/add/index.php'. therefore this bizarre side-affect which the new request after the redirect sent using GET instead of POST

Solution

  • use the full url './api/add/index.php'
  • or add a slash './api/add/' .

Solution 4 - Jquery

I noticed this behavior as well where my POST was sending a GET. The scenario's pretty unique, but maybe it will help someone.

This was happening to me on my User Role-edit page, where I was using ajax (post) as an immediate action when a role was checked or unchecked.

I also had the server configured to re-authenticate the user (and redirect them) whenever their role information changed so that their claims would be refreshed.

The brutal cycle ended up as:

  1. First Role Update -- POST -- 200 success

  2. Next Role Update -- POST -- 302 Found -> Redirect (I did not notice this until I used Fiddler rather than Chrome's network monitor)

  3. Redirect Call from (2) (Same URL) -- GET -- 404 Not Found (since I only allowed Post)

  4. GOTO (1)

I ended up changing the server to bypass re-authentication/claims update when it detected an ajax request (based on the Accept Types).

Solution 5 - Jquery

I found that when using dataType: 'jsonp' it converts the request to a GET. I changed it to dataType: 'json' it changed from GET to POST.

Solution 6 - Jquery

I had a similar issue and it started working for me as soon as I removed the hardcoded https:// from my url.

jQuery.ajax({
 type: "POST",
 url: "www.someurl.com",//instead of "https://www.someurl.com"
 data: { foo:"bar"},
 success: function(d){ console.log(d); },
 dataType: "JSONP"
});

Solution 7 - Jquery

For me, your piece of code look OK, but if you want to be sure, you can use $.post instead of $.ajax

$.post('ajax/test.html', function(data) {
 $('.result').html(data);
});

jquery link : http://api.jquery.com/jQuery.post/

Solution 8 - Jquery

I had the same problem and found this question but answers didn't solve my problem. I eventually solve it by removing contentType field in ajax request.

contentType: "application/json",

Solution 9 - Jquery

Check out your .htaccess file or search for some other thing that may redirect your request

Solution 10 - Jquery

I had this issue, and it turned out to be a URL Rewrite module in IIS.

I'm using ASP.NET MVC and WebAPI. I created rule to force lowercase URLs so social networks don't view the same URL as two different pages.

For example:

"http://url.com/View/Something/123GuidIdSomething"

vs

"http://url.com/view/something/123guididsomething"

This however, was somehow messing with my ajax requests. I disabled the rule and the problem was resolved.

Solution 11 - Jquery

a very common mistake is that we are using button type as submit and not changing the method for form (which is get by default)

make sure you don't use button type submit and if you do you have changed the form method to post

Solution 12 - Jquery

I came across this issue and the problem seemed to be with encoding of the url parameters taken from inputs. Chrome's dev tools where still showing a POST request, but the values were being received as a GET request.

The code giving problems was:

$.ajax({
    method: 'POST',
    type: 'POST',
    url: '/ajax/test.php?firstname=' + $('#fname').val()+ "&lastname=" + $('#lname').val()+ "&email=" + $('#email').val(),
    success: function(msg) {

        alert("Success");          
    },
    error: function() {

        alert("Failure");
    }
});

And the fix was to move the to use the data parameter instead of putting the values into the url:

$.ajax({
    method: 'POST',
    type: 'POST',
    url: '/ajax/test.php',
    data: {firstname: $('#fname').val(), lastname: 
    $('#lname').val(), email: $('#email').val()},
    success: function(msg) {

        alert("Success");
                            
    },
    error: function() {
        alert("Failure");
    }
 });

Solution 13 - Jquery

In my case, it turns out that the problem wasn't in the AJAX request.

I had attached submit into the type attribute of my input button, so, when the form was submitted, it was by default a GET request to the / path.

Eventually, I replaced the type attribute by button and it worked.

$.ajax({
          url: "login.php",
          type: "POST",
          data: $("#form").serialize(),
          success: (param) => {},
          error: (param) => {} 
 })

<form id="form">
    <label for="foo">Foo</label>
    <input type="text" name="foo" id="foo">
    <br>
    <label for="password">Password</label>
    <input type="password" name="password" id="password">
    <br>
    <input <!--type="submit"--> type="button" value="Send" id="submit">
</form>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTimoth&#233;e HENRYView Question on Stackoverflow
Solution 1 - JqueryPiotr KulaView Answer on Stackoverflow
Solution 2 - JquerytexelateView Answer on Stackoverflow
Solution 3 - JqueryJossef Harush KadouriView Answer on Stackoverflow
Solution 4 - JqueryemraginsView Answer on Stackoverflow
Solution 5 - JquerytonejacView Answer on Stackoverflow
Solution 6 - JqueryParhamView Answer on Stackoverflow
Solution 7 - JqueryMr_DeLeTeDView Answer on Stackoverflow
Solution 8 - JqueryFarid MovsumovView Answer on Stackoverflow
Solution 9 - JqueryViktor S.View Answer on Stackoverflow
Solution 10 - JqueryCallanView Answer on Stackoverflow
Solution 11 - JqueryJunaid MasoodView Answer on Stackoverflow
Solution 12 - JqueryAndrewView Answer on Stackoverflow
Solution 13 - Jquerytesting_22View Answer on Stackoverflow