How to execute a javascript code received by an AJAX request?

1

I have this code in the database:

<script type="text/javascript">
    alert("teste script-1");
    var axel = Math.random() + "";
    var a = axel * 10000000000000;
    document.write('<iframe src="https://....;ord='+a+'?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
</script>
<noscript>
    <iframe src="https://...;ord=1?"width="1" height="1" frameborder="0" style="display:none"></iframe>
</noscript>

Responding to some events (page load or btn click), I have an AJAX function that goes to the database and retrieves the script. See below:

$.getJSON( "returnScript.php", {objEvent: btn_id}, function() {
            })
            .done(function(dataset) {          
                //console.log(dataset);                  
                //console.log(dataset.length);  
                if(dataset.length>0){
                    for (var index in dataset){ 
                        console.log(dataset[index].script);
                        $("body").append(dataset[index].script);
                    }                
                }
                else{
                  console.log("sem script para ser executado");
                }              
            });

In this code, after consulting the database, if there is any script to execute (according to the criteria) it should retrieve all the code to make an append before finishing the body tag. As seen above, the code has a script part and an iframe part.

The fact is that if I paste this code into the page it fits well. But if I use $("body").append(dataset[index].script); alert("teste script-1"); runs correctly but the rest of the code makes the page all white (WSOD) with the following message in the browser console:

Uncaught TypeError: Cannot read property 'style' of null
    at (index):551
    at (index):551
    at XMLHttpRequest.xhr.onreadystatechange ((index):551)

Clearly what is happening is that when the code is retrieved by AJAX it does not work.

Would anyone know how to solve this?

I'm using win7 + php5.3 + symfony.

    
asked by anonymous 27.01.2017 / 17:17

1 answer

1

If you use document.write after the HTML page has been loaded, the browser will overwrite the current content with the contents of document.write .

In your case, when you run ajax the page has already been loaded, then document.write of the content of the asynchronous request, which is entered in the body ( $("body").append(dataset[index].script); ), overwrites the entire document.

You can replace the document.write call with:

document.body.innerHTML += '<iframe src="https://....;ord='+a+'?" width="1" height="1" frameborder="0" style="display:none"></iframe>';

As you are using jQuery on the page where the code is to be embedded, you can also use:

$('body').append('<iframe src="https://....;ord='+a+'?" width="1" height="1" frameborder="0" style="display:none"></iframe>');
    
30.01.2017 / 20:29