简体   繁体   中英

Load wordpress page after an ajax call finish

I have an ajax call to an API and based on the response I want to redirect my users, the API call is pretty basic and works fine:

    jQuery(document).ready(function($){
      $.ajax({
        url: '//apicall-url',
        dataType: 'json',
        async: false,
        success: function(obj) {
           //redirect goes here
        }
      });
    }); 

My problem is that the current wordpress page is loading and then doing the redirect once the ajax call is "success" any suggestion on how to to this correctly (I'm a WP newbie)?

I also tried using the wp_enqueue_script function but got the same result.

I tried to do this in the header and body with no luck.

You need do your api call before page and scripts will be loaded. Try call your API from PHP side. Look template_redirect hook. This is the best hook to create redirects.

My issue here was the "document ready" waiting for the ajax call changing this worked fine, here is my code:

    (function($) { //<-This is an anonymous function that instantaneously runs.
      $.ajax({
        url: '//apicall-url',
        dataType: 'json',
        async: false,
        success: function(obj) {
          //redirect goes here
       }
      });
    })( jQuery );  //<----passing jquery to avoid any conflict with other libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM