user1763295
user1763295

Reputation: 1098

<button> always redirecting after clicked

My button:

<button onclick="return DeleteImg(this,event);">Delete</button>

My code:

function DeleteImg(Obj,e) {
    if (!confirm('Are you sure you want to delete the file?')) return false;
    var n = new PostData('/Pictures/Delete/', 'Type=Home&Name=' + window.LargeImage.src.split('/')[5]);
    n.onResponse = function (t) {
        var n = JSON.parse(t);
        if (n.Success) ShowMsg('Image Deleted, it will be gone when you refresh.');
        else ShowMsg(n.Msg);
    };
    e.preventDefault();
    return false;
}

Post data function:

function PostData(e, t) {
    var n = false;
    this.onResponse = function (e) {};
    if (window.XMLHttpRequest) n = new XMLHttpRequest;
    else if (window.ActiveXObject) n = new ActiveXObject('Microsoft.XMLHTTP');
    else {
        this.onResponse(JSON.stringify({
            Success: false,
            Msg: 'Your browser does not support AJAX, please upgrade to Google Chrome, Mozzila Firefox or Internet Explorer 10',
            ElementId: undefined
        }))
    }
    n.open('POST', e, true);
    n.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var r = this;
    n.onreadystatechange = function () {
        if (n.readyState == 4 && n.status == 200) r.onResponse(n.responseText)
    };
    n.send(t)
}

Whenever the button is clicked and the user clicks okay to the confirmation box, the page redirects to another page (No idea what, my FCP just redirects it to page not found though so it doesn't exist) and the code isn't ran.

What can I do to fix this?

Upvotes: 0

Views: 71

Answers (1)

Cfreak
Cfreak

Reputation: 19309

By default a button is a submit button which causes your page to redirect. You can fix by setting the button type.

<button type="button" onclick="return DeleteImg(this,event);">Delete</button>

Upvotes: 4

Related Questions