Charles Van Norman
Charles Van Norman

Reputation: 1

Using JS variable inside $.ajax function - null?

I've seen lots of similar questions but I can't find an answer! I am trying to open a PHP file, passing some Javascript variables into the URL, using $.ajax. But, when I define the variable in Javascript then try to use it inside $.ajax, it returns null and the variable is not defined. How can I pass this variable?

Thanks in advance! -C

var searchTerm = "startups";
function Initialize() {
  PopulateTable(searchTerm);
 }
function PopulateTable(searchTerm) {
    $.ajax({  
            type: "POST",
            dataType: "text",
            data:   "tableName=Events&searchTerm=" + searchTerm, 
            // It's not recognizing my JS variables inside Ajax. Has it always been this way?           
            url: "/php/postData.php",  
            success: function(data, textStatus, jqXHR){ 
                alert(data);
            }
        });
    window.location.reload();
}

Upvotes: 0

Views: 574

Answers (1)

Milimetric
Milimetric

Reputation: 13549

$.ajax({ ... will spawn an asynchronous request to your php resource. window.location.reload(); will reload your page before that request is received and anything can be done with it. If you need to reload the page, do it inside here:

        success: function(data, textStatus, jqXHR){ 
            alert(data);
            window.location.reload();
        }

Upvotes: 7

Related Questions