Two xmlHttpRequests on one page

I am new to ajax, but trying to implement two simple calls to dynamically change two separate divs on a page using javascript. I have no problem using one call at a time, but when I use two, it seems that the second xmlhttprequest takes over the first and writes to both divs.

I read and tried to use the fixes listed in these two other posts, and both don't seem to work in my case:

Sending two Ajax requests to two different PHP scripts from one javascript function

Using two xmlhttprequest calls per page

And here is my corresponding code:

function request_handler(url, params, changed_div) {
    if(window.XMLHttpRequest) {
            try {
                    req = new XMLHttpRequest();
            }catch(e) {
                    req = false;
            }
    }else if(window.ActiveXObject) {
            try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e) {
                    try {
                            req = new ActiveXObject("Microsoft.XMLHTTP");
                    }catch(e){
                            req = false;
                    }
            }
    }

    if(req) {
              req.onreadystatechange = function(){
                    if (req.readyState == 4 && req.status == 200){
                                    document.getElementById(changed_div).innerHTML = req.responseText);

                    }
            }

            req.open("POST", url, true);
            req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            req.send(params)
            return true;
    }

    return false;
}

Below is the basic format of each request using the function above:

request_handler("sample.php", parameters , "sample_div");

Sorry if I pass something simple here, I just can't get it to work.

+3
3

xmlhttprequest

.

request_handler req, , .

, :

function request_handler(url, params, changed_div) {
    var req;
    // Rest of your function
}

, . req , request_handler .

, JQuery, Prototype Dojo, Ajax? , , , .

+3

req - , var, .

, . ( ) XMLHTTPRequest. , . .

, , , div . , .

+2

, , . , , " Ajax", .

jQuery has a plugin for queuing, and I'm sure most other JavaScript frameworks like Prototype and MooTools will also. If you want to stick with raw JavaScript, I would look at this web page:

http://www.cmarshall.net/MySoftware/ajax/index.html

It implements the queue very efficiently and has a great example of its use.

0
source

Source: https://habr.com/ru/post/1786724/


All Articles