Sky
Sky

Reputation: 7711

It's not working using 'a' to submit the form in HTML

I tried to submit the request with post method by clicking the element a in HTML. But it always refreshes current page, even the action is updated with correct value.

This is how I submit the request.

$(function() {
    $('.detail a').click(function() {
        $('#cityId').val($(this).data('cid'));
        $('#cityName').val($(this).data('cn'));
        $('#parentIds').val($(this).data('pids'));

        $('#cityForm').submit();
    });
});

I passed the values to the hidden elements for submitting with POST method. Before the submit(), I checked and the action attribute of form is the right URL I want. But, after it, it didn't redirect to the URL I set, it just refreshed the current page.

This is the a in my code:

<a href data-cid="<c:out value='${cc.id}'/>" data-pids="<c:out value='${cc.type}'/>"

This is how the form looks like:

<form id="cityForm" method="post" action="<%=basePath%><c:out value='${sp}'/>">

It did work in IE. I searched online and found some solutions saying that it's caused by Chrome takes it as the same request, so I need to add a timestamp after the URL, but didn't work for me.

Upvotes: 1

Views: 93

Answers (3)

Alfred
Alfred

Reputation: 21396

Try;

<a href="" data-cid="<c:out value='${cc.id}'/>" data-pids="<c:out value='${cc.type}'/>" >Submit Form</a>

Upvotes: 1

Gerald Schneider
Gerald Schneider

Reputation: 17797

Use an <input type="submit"> or a <button type="submit"> instead of a link. You can use CSS to style the input exactly like an a tag and it will still work when JavaScript is disabled on the browser, which is not possible with your current solution.

button[type=submit].link {
  display: inline;
  border: none;
  background-color: transparent;
  cursor: pointer;
}
button[type=submit].link:hover {
  text-decoration: underline;
  color: blue;
}
<button type="submit" class="link">This is a submit button</button>

You should always build websites to be completely functional without JavaScript, then you can add JS to improve the comfort of navigating the site.

Upvotes: 2

Michał Perłakowski
Michał Perłakowski

Reputation: 92521

If you have a link with empty href attribute, it will become current page URL, so when you click such link, page just refreshes. If you want to bind some action to a element, you have to prevent its default behavior, using event.preventDefault():

$(function() {
    $('.detail a').click(function(event) {
        event.preventDefault();

        $('#cityId').val($(this).data('cid'));
        $('#cityName').val($(this).data('cn'));
        $('#parentIds').val($(this).data('pids'));

        $('#cityForm').submit();
    });
});

Upvotes: 4

Related Questions