Question

As the title states my Ajax call is actually causing the form to be submitted to its default action, why? I've never come across this before, all my other ajax calls have never done this.

function newAjax(t,u){ //t = type(post/get), u = url
    var resource = null;
    if (window.ActiveXObject) { 
        resource = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    else if (window.XMLHttpRequest) { 
        resource = new XMLHttpRequest(); 
        resource.overrideMimeType('text/html');
    }
    resource.open(t,u,false);
    resource.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    return resource;
}

function send_newsletter(){
    formObj = document.getElementById("news_form");
    var inputs = formObj.getElementsByTagName("INPUT");
    var parameters = "";
    for(i = 0; i < inputs.length; i++){
        parameters += inputs[i].name+"="+encodeURI(inputs[i].value);
        if(i != inputs.length-1){
            parameters += "&";
        }
    }
    var url = "whereitshouldbegoing.com";
    var ajax = newAjax("POST",url);
    ajax.onreadystatechange = ajaxResult;
    ajax.setRequestHeader("Content-length", parameters.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.send(parameters);
}

It all works fine upto the .send line, which is the bugger which is causing the form to submit aswell(I also have no idea if the ajax request actually gets off).

The send_newsletter function is called from an input type="image" element with onclick="send_newsletter()"

Please don't tell me to use jQuery or another library, as much as I would love to, we can't use any external librarys, corporate guidelines and whatnot.

Was it helpful?

Solution

An input of type "image" will behave the same as a submit button. Use an anchor or button type input to trigger your method.

<input type="button" onclick="send_newsletter()" value="Send" />

<button onlclick="send_newsletter()">... </button>

<a href="#" onclick="send_newsletter(); return false;"><img src="... /></a>

OTHER TIPS

Are you using a submit button to call send_newsletter?

onreadystatechange callback function 'ajaxResult' is not called because you're doing a synchronous call to the server:

resource.open(t,u,false);

if you want ajaxResult to be called change it to :

resource.open(t,u,true);

for now that's what I see. You have to provide more info like how do you call send_newsletter?


EDIT:(following author comment)

an INPUT of type image is a graphical submit button.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top