unexpected url changes when post request done

I am writing a simple web service and on the web UI (the url is "localhost:9001") there is a button that triggers function indexIt, which raise a POST request and the server respond with json.

<button type="submit" id="indexButton" class="btn btn-primary" onclick="indexIt()">Index</button>

The relevant code is:

function displayResponse(msg) {
    var shown = JSON.stringify(msg, null, 2);
    $(hintTextSelector).text(shown);
}

function indexDoneHint(response) {
    console.log(JSON.stringify(response));
    displayResponse(response);
}

function getLOptions() {
    return {
        "stem": $("#cb-index-stem").is(":checked"),
        "ignore": $("#cb-index-ignore").is(":checked"),
        "swDict": $("#lb-index-stopwords").val()
    }
}

function indexIt() {
    var indexOptions = getLOptions();
    var privateParam = {
        "method": "POST",
        "url": _getUrl("indexDoc"),
        "data": JSON.stringify(indexOptions)
    };
    $.extend(privateParam, commonParam);
    $.ajax(privateParam).done(indexDoneHint).error(onError);
}

The problem is that when I trigger the request by pressing the button, the url would change to "localhost:9001/?" (trailing /?) was added.

Strangely when I'm using the developer console and invoke indexIt(), the page remains "localhost:9001"

Answers


If you use button<button> in your form then on click it automatically submit form. instead of button tag use input tag i.e <input type="button" id="indexButton" class="btn btn-primary" onclick="indexIt()" value="Index It" />

OR use return keyword

  1. <button type="submit" id="indexButton" class="btn btn-primary" onclick="return indexIt()" >Index</button>

  2. in your javascript function "indexIt()" at the end use "return false" so it will run your js code and stop execution.

    function indexIt() {
    var indexOptions = getLOptions();
    var privateParam = {
        "method": "POST",
        "url": _getUrl("indexDoc"),
        "data": JSON.stringify(indexOptions)
    };
    $.extend(privateParam, commonParam);
    $.ajax(privateParam).done(indexDoneHint).error(onError);
    
   return false;
}

Just make button as simple button instead of submit button, type="button"

<button type="button" id="indexButton" class="btn btn-primary" onclick="indexIt()">Index</button>

OR

<input type="button" id="indexButton" class="btn btn-primary" onclick="indexIt()">Index</button>

Because when you make button as submit it will submit your page to action written in Form tag.


Need Your Help

Very bizarre Python 3 Byte to String failure

python string python-3.x base64 byte

Well I hope this is a problem you didn't see before.