var num = ''; window.uid = ''; //function getId(){ (function($){ num = $('#statUid').data('uid'); $.ajax({ type: "POST", url: 'http://......./file.php', data: { 'num': num }, success: function(response) { uid = response; console.log('Π²Π½ΡƒΡ‚Ρ€ΠΈ ajax: '+uid); }, error: function() { // console.log('ошибка!'); } }); })(jQuery); //};// end getID console.log('послС ajax: '+uid); //setTimeout(function(){ var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u+'piwik.php']); //---- // getId(); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+num); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+uid); //---- _paq.push(['setSiteId', uid]); //'1' var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); //}, 1000); 

How to make that starting with var _paq = _paq || []; var _paq = _paq || []; or at least below where //---- not executed, but waited for a response from the server, to get the value of the uid variable. Wrapping this code into nothing can not work. Tell me what you can do in this situation. ps zamenkochennye lines, it tried various options.

 var num = ''; window.uid = ''; (function($){ var post = $.ajax({ type: "POST", url: 'http://............/file.php', data: { 'num': num } }); post.done(function(response){ uid = response; console.log('Π²Π½ΡƒΡ‚Ρ€ΠΈ ajax: '+uid); var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u+'piwik.php']); //---- // getId(); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+num); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+uid); //---- _paq.push(['setSiteId', uid]); //'1' var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); }); post.fail(function(){ //ΠžΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ошибок alert("error!"); }); })(jQuery); 

  • why won't it work if wrapped? without wrapping in any way. - Artem Gorlachev Sep.
  • Try using promises. $.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) { alert( jqXHR.status ); // Alerts 200 }); - Igor Lut
  • I can not understand why it does not work in a wrapper. This is piwik site analytics. I connect this code with a file, but I do not immediately insert it into the head. I am trying to dig into piwik files, but have not yet found where this code is formed from them. I tried to wrap in setTimeout, the variable comes at the right time in the end, but the script itself does not work, the statistics do not come. - medvedev
  • "It cannot be wrapped, it will not work" - some of your variables, declared in the global scope, disappear after wrapping from it. Find them and fix them. - Igor
  • Possible problem with var _paq = _paq || []; var _paq = _paq || []; I will try to declare it in advance as global. - medvedev

4 answers 4

It is difficult to test for performance, try to work with a minimum number of variables and manipulations with them. If everything works out, go ahead and add functionality.

 (function($){ var num = $('#statUid').data('uid'); var post = $.ajax({ url: "http://......./file.php", data: {'num': num} , type: "POST" }); post.done(function(response){ var uid = response; var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); var u = "//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u + 'piwik.php']); _paq.push(['setSiteId', uid]); //'1' var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); }); post.fail(function(){ //ΠžΠ±Ρ€Π°Π±ΠΎΡ‚ΠΊΠ° ошибок alert("error!"); }); })(jQuery); 

  • Unfortunately, this does not work at all, an example of what I added to the question. Look, maybe I misunderstood something? And it turns out everything in the wrapper, not even once (( - medvedev

Found such a way out. Split code in different files. In the file with my code inside ajax, after receiving the variable, I call the function connecting file with piwik code.

  • And other answers did not help at all? - 0xdb
  • Unfortunately not. The whole problem is that the piwik code does not work in any wrapper, which is why I did not understand it, the removal of variables from the wrapper did not help. But to everyone who responded thanks a lot !!! - medvedev

You can create a request termination identifier (in this case, done ) and check it either by timer, or in recursion, or in an infinite loop. When he is able to "request completed" ( true in our case), you can do whatever you want next.

 var num = ''; window.uid = ''; var done = false; // <---------------------------------- //function getId(){ (function($){ num = $('#statUid').data('uid'); $.ajax({ type: "POST", url: 'http://......./file.php', data: { 'num': num }, success: function(response) { uid = response; console.log('Π²Π½ΡƒΡ‚Ρ€ΠΈ ajax: '+uid); done = true; // <---------------------------------- }, error: function() { // console.log('ошибка!'); } }); })(jQuery); //};// end getID console.log('послС ajax: '+uid); var intId = setInterval(function(){ // <---------------------------------- if(done) { // <---------------------------------- var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u+'piwik.php']); //---- // getId(); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+num); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+uid); //---- _paq.push(['setSiteId', uid]); //'1' var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); clearInterval(intId); // <---------------------------------- } // <---------------------------------- }, 1000); // <---------------------------------- 

Through while

 var num = ''; window.uid = ''; var done = false; // <---------------------------------- //function getId(){ (function($){ num = $('#statUid').data('uid'); $.ajax({ type: "POST", url: 'http://......./file.php', data: { 'num': num }, success: function(response) { uid = response; console.log('Π²Π½ΡƒΡ‚Ρ€ΠΈ ajax: '+uid); done = true; // <---------------------------------- }, error: function() { console.log('ошибка!'); } }); })(jQuery); //};// end getID console.log('послС ajax: '+uid); while(!done) { // <---------------------------------- var _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); (function() { var u="//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u+'piwik.php']); //---- // getId(); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+num); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+uid); //---- _paq.push(['setSiteId', uid]); //'1' var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); } // <---------------------------------- 

But if you use fetch or some kind of lib that returns promis, then everything can be done even shorter and clearer. Of course, provided that you use some kind of transpiler (for example babel ).

You can try something like this (wrote from a notebook, you need to test)

 let num = ''; let uid = ''; (async () => { num = document.getElementById('statUid').data('uid'); uid = await fetch("http://......./file.php", { method: "POST", body: {num} }) let _paq = _paq || []; /* tracker methods like "setCustomDimension" should be called before "trackPageView" */ _paq.push(['setDocumentTitle', document.domain + "/" + document.title]); //добавиляСт ΠΏΠΎΠ΄Π΄ΠΎΠΌΠ΅Π½Ρ‹ _paq.push(['trackPageView']); _paq.push(['enableLinkTracking']); let u="//widget.minsocium.ru/modules/stat/"; _paq.push(['setTrackerUrl', u+'piwik.php']); //---- // getId(); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+num); console.log('Π² piwik ΠΊΠΎΠ΄Π΅: '+uid); //---- _paq.push(['setSiteId', uid]); //'1' var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0]; g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s); })(); 
  • Thanks for the advice, but as I wrote above, any wrapper makes the piwik code not working. - medvedev
  • Well, go through the cycle and not through the interval (although there is a question in the consumption of resources) added an option in response - torokhkun
  • So there too the wrapper turns out! Code starting with var _paq = _paq || []; var _paq = _paq || []; can not wrap. Thanks again for trying to help, the question was solved in its own way, maybe it can be more correct, but there were no other options. - medvedev

Make the request synchronous. Parameter in the request:

 $.ajax({ type: "POST", url: 'http://......./file.php', data: { 'num': num }, success: function(response) { uid = response; console.log('Π²Π½ΡƒΡ‚Ρ€ΠΈ ajax: '+uid); done = true; // <---------------------------------- }, error: function() { console.log('ошибка!'); } }); 

Here is the parameter to be added in the ajax request - async:false and the program will wait to receive data from the server