Jquery on page load set page state

- 1 answer

Ad

I am trying to use states to handle different ajax data and calls. On the initial page load I want to load a certain state. This works the ajax call returns some html and puts it in a table.

However once I interact with the page it attempts to load correctly but then reloads first state and sets a "?#" in url. The second time I try then the state changes and new html is added. If I remove the ?# and reload it resumes the weird behavior. Is it because of how I am declaring? Thanks in advance!

Code:

 var state = "images";
 var items = [];

 $(document).ready(function(){
   getData();
 });

var getData = function () {
            $.ajax({
            type: "POST",
            url: "handler.php",
            data: {data: items, state: state},
            cache: false,
            success: function (data) {
               updateTable(data);
            },
            abort: function (data) {
               alert('abort');
            },
            error: function (data) {
               alert('error');
            }
            });
   }

    var updateTable = function(data) {
            $("#dataHolder").empty();
            $("#dataHolder").append(data);
            $("h2").html(state);
    }

    $("#view").on("click", function() {
            items = $("#slide").val();
            state = "videos";
            getData();
    });
Ad

Answer

Ad

Use the preventDefault() method to prevent the default behavior on the link click , which is navigating to a new page. If you do that your page will not be reloaded.

$("#view").on("click", function(e) {
  e.preventDefault();
     items = $("#slide").val();
     state = "videos";
     getData();
});

Also, global variables is not a good idea to transfer data. It is better to update your getData method to accept 2 parameters

var getData = function (state,items) {
  //use state and items as needed
}

And when you call, pass the values

$("#view").on("click", function(e) {
  e.preventDefault();
     var slideItems= $("#slide").val();       
     getData("vides",slideItems);
});
Ad
source: stackoverflow.com
Ad