0

Ok, so I've been trying to get this to work for a couple hours now....

Here is my simple ajax request:

function ajaxRequest() {

var xmlhttp;
var activexmodes = ["Msxm12.XMLHTTP", "Microsoft.XMLHTTP"];

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari

return new XMLHttpRequest();

}
else if (window.ActiveXObject)
{// code for IE6, IE5

    for(var i = 0; i < activexmodes.length; i++)
    {

        try
        {

            return new ActiveXObject(activexmodes[i]);

        }
        catch (e)
        {

            // Suppress

        }

    }

}
else
{

    return false;

}

}

Then I have this function calling it:

function run_ajax_form_submit_request(s_method, s_processor, s_params, b_syn) {

var request = new ajaxRequest();
var message = null;

    request.onreadystatechange=function()
    {

        if (request.readyState == 4)
        {

            if (request.status == 200 || window.location.href.indexOf("http") == -1)
            {

                if (request.responseText == 'true')
                {

                    message = 'true';

                }
                else
                {       

                    message = request.responseText;

                }

            }
            else
            {

                messge = "There was a problem processing this request.";

            }

        }
        else if (request.readyState == 0)
        {

            message = "Error: 0.";

        }
        else if (request.readyState == 1)
        {

            message = "Error: 1.";

        }
        else if (request.readyState == 2)
        {

            message = "Error: 2.";

        }
        else if (request.readyState == 3)
        {

            message = "Error: 3.";

        }

    }

switch (s_method)
{

    case 'POST':

        request.open("POST", "./scripts/pages/index/index/form_processor.php?", true);
        request.setRequestHeader("Content-s_input_type", "application/x-www-form-urlencoded");
        request.send(s_params);

        break;

    case 'GET':

        request.open(s_method, s_processor, b_syn, true);
        request.send();

        break;

}

return message;

}

which is being called by this statement:

var s_result = run_ajax_form_submit_request('POST', s_path, s_send_parameters, true);

!!! END CODE !!!

What's happening is the code is executing correctly until it gets to this line: request.open("POST", "./scripts/pages/index/index/form_processor.php?", true);

Then it's running the onreadystatechange function which, since nothing has run yet, is returning the "Error 1." message.

Then the rest of the post script continues and changes the state again, this time it runs 4, but the onreadystatechange fails to run again, resulting in a final message of "Error 1."... The code will run properly in a debugger, but fails to run in the browser... Here is the first page of javascript that calls everything else:

!!! INITIAL CODE !!!

function submit_post_form (s_form_name, s_path, b_restrict, s_success_response) {

var o_form = document.getElementById(s_form_name);
var oa_inputs = o_form.getElementsByTagName('input');
var oa_selects = o_form.getElementsByTagName('select');
var o_submit = form_find_submit(oa_inputs);
var o_messages = o_form.getElementsByClassName('messages')[0];

o_messages.className = 'messages';

switch (b_restrict)
{

    case true:

        for (i = 0; i < oa_inputs.length; i++)
        {

            oa_inputs[i].disabled = true;

        }

        for (i = 0; i < oa_selects.length; i++)
        {

            oa_selects[i].disabled = true;

        }

    break;

}

o_messages.classList.add('loading');

setTimeout(function(){

    o_messages.classList.add('active');

    setTimeout(function(){

        var sa_all_inputs_as_strings = new Array();

        var inputIDArray = new Array();
        var selectIDArray = new Array();

        var inputValArray = new Array();
        var selectValArray = new Array();

        var s_input_type = null;

        for (i = 0; i < oa_inputs.length; i++)
        {

            s_input_type = oa_inputs[i].type;
            var s_input_val_temp = null;

            if (s_input_type.trim() != 'button' && s_input_type.trim() != 'submit')
            {

                sa_all_inputs_as_strings[i] = new Array();

                sa_all_inputs_as_strings[i][0] = oa_inputs[i].getAttribute('name');

                if (s_input_type == 'text' || s_input_type == 'password')
                {

                    s_input_val_temp = oa_inputs[i].value;

                }
                else if (s_input_type == 'radio' || s_input_type == 'checkbox')
                {

                    if (oa_inputs[i].checked)
                    {

                        s_input_val_temp = 'true';

                    }
                    else
                    {

                        s_input_val_temp = 'false';

                    }

                }

                sa_all_inputs_as_strings[i][1] = s_input_val_temp;

            }

        }

        for (i = sa_all_inputs_as_strings.length; i < (sa_all_inputs_as_strings.length + oa_selects.length); ++i)
        {

            sa_all_inputs_as_strings[i] = new Array();

            sa_all_inputs_as_strings[i][0] = oa_selects.id;
            sa_all_inputs_as_strings[i][1] = oa_selects.options[(oa_selects[selectInterval]).selectedIndex].value;

        }

        var s_send_parameters = "form=" + s_form_name;

        for (i = 0; i < sa_all_inputs_as_strings.length; i++)
        {

            s_send_parameters +=  "&" + encodeURIComponent(sa_all_inputs_as_strings[i][0]) + "=" +  encodeURIComponent(base64Encode(sa_all_inputs_as_strings[i][1]));

        }

        var s_result = run_ajax_form_submit_request('POST', s_path, s_send_parameters, true);


        o_messages.classList.remove('active');

        setTimeout(function(){

            o_messages.className = 'messages';

            if (s_result == 'true')
            {

                o_messages.innerHTML = s_success_response;
                o_messages.classList.add('success');

            }
            else
            {       

                o_messages.innerHTML = s_result;
                o_messages.classList.add('error');


                for(i = 0; i < oa_inputs.length; i++)
                {

                    if (oa_inputs[i].type != 'submit')
                    {

                        oa_inputs[i].disabled=false;
                        oa_inputs[i].classList.remove('disabled');

                    }

                }

                for (i = 0; i< oa_selects.length; i++)
                {

                    oa_selects[i].disabled=false;
                    oa_selects[i].classList.remove('disabled'); 

                }

            }

            setTimeout(function(){

                o_messages.classList.add('active');

            }, 100);

        }, 200);

    },200);

},100);

}

I don't know what I'm doing wrong... maybe it's the timeouts (for animation), but I have no idea....

AotN
  • 548
  • 2
  • 11

1 Answers1

4

That's the way it works, the onreadystate event fires several times during the request, the first before anything is even sent, that's why you have to listen for the number 4, you're for some reason assuming 1, 2 etc. are errors, they aren't, they are just statuscodes for different stages of the request.

The status codes are as following

0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

You see why the 1 is firing, it's not an errorcode, it's the statuscode for when the connection is established.

You solve this by removing all the erroneous error handling you've added.

There's also another issue with your code, you're setting up the ajax this way

function run_ajax_form_submit_request(s_method, s_processor, s_params, b_syn) {
    var request = new ajaxRequest();
    var message = null;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            message = request.responseText;
        }
    }

    return message;
}

and you're calling it like

var s_result = run_ajax_form_submit_request('POST', s_path, s_send_parameters, true);

but that's never going to work because ajax is asynchronous, see this answer for a detailed explanation

How to return the response from an Ajax call

Community
  • 1
  • 1
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Alright, I took out all the error messages, but now it's simply not returning anything... Debugger still gets it right, however the browser still fails... Anything else wrong? – AotN Nov 17 '14 at 04:37
  • Yes, the ajax call is **async**, you can't do it that way at all. – adeneo Nov 17 '14 at 04:38
  • Thank you. I appreciate it a lot, I would have been here for a much longer time trying to figure this one out. – AotN Nov 17 '14 at 04:45
  • @Jingrah1: if the above solved your problem, please don't forget to accept it, by clicking the tick mark to the left. – halfer Nov 20 '14 at 01:05