Issue with reading a file through AJAX

I need to read a file called config.txt on a button click

Host:www.fff.com
Username:root123
Password:root123

This is my submit part of html file

<input name="Submit" class="btn btn-primary" style="float:left;" onClick="contact_mailsend();" id="Submit" value="SUBMIT" type="submit" />

on click will trigger a JS function contact_mailsend():

function  contact_mailsend(){
    xmlHttp.onreadystatechange=function(){
        var tmpDoc, re=/^(.+)$/gm, arr=[], oP,arrSplit=[],arrSpl=[];
        if(xmlHttp.readyState===4){
            if(xmlHttp.status===200){
                tmpDoc=xmlHttp.responseText; arrSpl = tmpDoc.split(",");
                var arrGlobalHost = arrSpl[0].split(':');
                var arrGlobalUser= arrSpl[1].split(':');
                var arrGlobalPass= arrSpl[2].split(':');
                strGlobalHost = arrGlobalHost[1];
                strGlobalUser = arrGlobalUser[1];
                strGlobalPass = arrGlobalPass[1];
                alert(strGlobalHost);
                xmlHttp=null;
            }
        }
        xmlHttp.open("POST", fileName, true); //Use POST to prevent use of cached file
        xmlHttp.send(); 
    }; 
};
}

What's happening is that alert inside is happening not at the first time.

Submit click on first click never alert. If submit is clicked for second time, it will alert.

Please help me.

Answers


Here is a demo Plunker

Try moving the xmlHttp.send() out of onreadystatechange event handler. When you click, the form will be sent. When the response changes, your callback function will execute and alert.

function  contact_mailsend(){
    xmlHttp.open("POST", fileName, true); //Use POST to prevent use of cached file
    xmlHttp.send(); 
    xmlHttp.onreadystatechange=function(){
        var tmpDoc, re=/^(.+)$/gm, arr=[], oP,arrSplit=[],arrSpl=[];
        if(xmlHttp.readyState===4){
            if(xmlHttp.status===200){
                tmpDoc=xmlHttp.responseText; arrSpl = tmpDoc.split(",");
                var arrGlobalHost = arrSpl[0].split(':');
                var arrGlobalUser= arrSpl[1].split(':');
                var arrGlobalPass= arrSpl[2].split(':');
                strGlobalHost = arrGlobalHost[1];
                strGlobalUser = arrGlobalUser[1];
                strGlobalPass = arrGlobalPass[1];
                alert(strGlobalHost);
                xmlHttp=null;
            }
        } 
    }; 
};

Need Your Help

ImageMagick GrayScale

objective-c xcode macos cocoa imagemagick

How to convert image to grayscale with ImageMagick in objective-c? I load images to imageMagick and use them as OpenGL textures. I need to make image grayscale on load. I mean make grayscale subIma...

Mysql request cache

php mysql caching

I have created a small php code the request from MySQL a count of specific table.