skip to Main Content

I have a code that do a load in Jquery and loads a page and after this page has been loaded I have to execute some functions, but the functions is been runned before all the page has been loaded, giving me a error.

async function edit_matrix(id){
    const response = await fetch(`http://127.0.0.1:8000/apps/edit/matrix/${parseInt(id)}`)
    const data = await response.json()
    if(data.determinant){
        $(".cont").load("http://127.0.0.1:8000/apps/determinant");
        console.log("JQuery")
        $(document).ready( 
            select_grid(data.number_rows_a) //The code that must be executed after the load of the page
        ); 
        
    }else{
        //another part of the code
    }
}

I try to add the await element to make the code stop and just run before that actions ends and I tried to add the method ready of Jquery, but it is not working.

2

Answers


  1. Utilize a callback function with in load ();

    $(".cont").load("http://127.0.0.1:8000/apps/determinant", function() {
        console.log("Content loaded!");
        select_grid(data.number_rows_a);  // Execute code after content is loaded
    });
    
    Login or Signup to reply.
  2. If you check the jQuery documentation for load() you can see that the second argument is a callback function which will be executed after the AJAX request completes.

    As such, you can place your logic there:

    async function edit_matrix(id) {
      const response = await fetch(`http://127.0.0.1:8000/apps/edit/matrix/${parseInt(id)}`)
      const data = await response.json()
      if (data.determinant) {
        $(".cont").load("http://127.0.0.1:8000/apps/determinant", () => {
          select_grid(data.number_rows_a);
        });
      } else {
        // another part of the code
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search