Search code examples
javascriptstringfunctionxmlhttprequestglobal-variables

why i can't define out side of a function followed by =?


the code i am trying to run

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>

<script> 
var http = new XMLHttpRequest();
var params = 'frashnum=&action=login&Frm_Logintoken="+results+"&Username=admin&Password=test';
var url = 'http://page/';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');


 http.onload = function () {

let str = (http.responseText);
    alert(str)
    let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
    let results = console.log(str.match(pattern)[1]);
    return results;

 } 
 console.log(results);
http.send(params);
</script>
</body>
</html>

i am trying to return the results variable to use it in Frm_Logintoken from the params but it says results is not defined . where clearly it's defined... so i tried to remove the equals sign before the

function and this part too http.onload = and it worked but the rest of code didn't ... so is there a way to fix this ?

i have already tried a lot of the answers from other questions but non worked for me ... and i am too Beginner to understand not well Simplified answers.

so please don't mention links or mark it as duplicated and just answer it


Solution

  • an quick fix would be changing

    http.open('POST', url, true);
    

    to http.open('POST', url, false);

    to make the request synchronous . and instead of return results;

    add results1 = results;

    and then

    console.log(results1);
    

    should work .. and if not add just add

    var results1;
    

    at the start of the code

    so the full code should look like this

    <!DOCTYPE html>
    <html>
    <body>
    <p id="demo"></p>
    
    <script> 
    var http = new XMLHttpRequest();
    var url = 'http://page/';
    var results1;
    http.open('POST', url, false);
    //Send the proper header information along with the request
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    
     http.onload = function () {
    
    let str = (http.responseText);
        alert(str)
        let pattern =/\bgetObj\("Frm_Logintoken"\)\.value = "([^"]+)";/;
        let results = console.log(str.match(pattern)[1]);
        results1 = results;
    
     } 
     console.log(results1);
    var params='frashnum=&action=login&Frm_Logintoken='+results1+'&Username=admin&Password=test';
    http.send(params);
    </script>
    </body>
    </html>
    

    and the results in the params should be in Apostrophe not double quotes so it should look like this 'results1'