Hongxu Chen
Hongxu Chen

Reputation: 5350

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"

Upvotes: 0

Views: 96

Answers (2)

Bharat Ranpariya
Bharat Ranpariya

Reputation: 1253

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.

Upvotes: 1

Yogesh Randive
Yogesh Randive

Reputation: 41

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;
}

Upvotes: 1

Related Questions