Yanick Schraner
Yanick Schraner

Reputation: 315

jquery ajax post not executed

I have a little problem with jQuery ajax. I want to send a POST to a .php file and afterwards change the current URL. I tried the following code:

<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> 
<script>
window.onload = function () {
    $.ajax({
        type: "POST",
        url: "sample.php",
        data: {'username': "STRING"},
        timeout: 1000,
        complete: function(){
            window.location.href = 'http://127.0.0.1/sample/another.php';
        }
    });
}
</script>

So, as I can see in the chrome developer tools Network tab, no POST is executed. Although the URL changed to another.php

Can you tell me what I am doing wrong or how I can solve this issue?

Upvotes: 3

Views: 146

Answers (3)

xCNPx
xCNPx

Reputation: 605

Alternatively, you can use .done() as well. You may also think about scoping this inside a self executing function instead of a window.onload event.

    (function($){

    // Make an object for your param values. 
    var ajaxData = {
        username: 'STRING',
        anotherParam: 'STRING',
        andanotherParam: 'STRING',
        yetanotherParam: 'STRING'
    };

    $.ajax({
        type: "POST",
        url: "sample.php",
        data: ajaxData
    }).done(function(){
        window.location.href = 'http://127.0.0.1/sample/another.php';
    }).fail(function(jqXHR, textStatus) {
        alert( "Request failed: " + textStatus );
    });

}(jQuery));

Upvotes: 0

Ritikesh
Ritikesh

Reputation: 1228

You will never see the POST. cause the url changes and remember the another.php hasn't made any AJAX requests! so you'll never find anything there. try changing the JS code in the success method to something like an alert to know if it works! and maybe then you'll find the POST method in the console!

Upvotes: 0

Anri
Anri

Reputation: 1693

use success instead of complete

 $.ajax({
        type: "POST",
        url: "sample.php",
        data: {'username': "STRING"},
        timeout: 1000,
        success : function(){
            window.location.href = 'http://127.0.0.1/sample/another.php';
        }
    });

Upvotes: 2

Related Questions