Php post запрос ссылкой

POST from an tag

Is it possible to do a POST from just an tag? I know anchor tags are usually just for GETs, and I know I can use javascript to do this (like in JavaScript post request like a form submit) but to me that seems a little messy. Is there a way to do this with straight HTML?

11 Answers 11

Not really, no. You can, however, do something like this:

You should find a better way, though. This one does not degrade gracefully.

onclick=»this.parentNode.submit()» should be onclick=»event.preventDefault(); this.parentNode.submit()» using jQuery. It will be better.

@ThếAnhNguyễn: Hardly matters, since the form is being submitted. Again, ideally, you would not do this at all, and style a button to look like a link instead.

There is no way to POST an a element using only HTML.

As can be seen from this DTD fragment (HTML 4.01 spec):

There is no attribute that controls whether to use POST or GET with an a element.

You have to script it, if you want to abuse the semantics.

I like how you concluded with «if you want to abuse the semantics», i.e one shouldn’t do this and should use the recommended way of doing such things, i.e using a form to submit data.

Basically, you can’t use an anchor tag for a POST request. However, there is a simple hack to achieve this.

You can use CSS to make an look like a hyperlink.

In case it serves somebody:

Simple answer: no. You need to use javascript to do this kind of thing; since when you do a POST what you’re doing is sending the data in the HTTP request. With get you’re just sending it as part of the string (thus you can do it through the href value).

No clearly not without a javascript submit().

No there’s no way to do this without the use of scripting. Although you can use CSS to style a standard Submit button to look and act more like an tag.

Читайте также:  Java map foreach print

The 2 ways I think about are with JavaScript (as you said) or through server-scription.

You’d basically send the GET request (with the A) to some server file, which would change the GET vars to POST and then re-submit instantly (redirect location). But that would mess the referer stats I think.

You should to add data-method=»post»

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

How do you post data with a link

I have a database which holds the residents of each house in a certain street. I have a ‘house view’ php web page which can display an individual house and residents when given the house number using ‘post’. I also have a ‘street view’ web page which gives a list of houses. What I want to know is if you can have links on the street view which will link to the house view and post the house number at the same time without setting up a form for each? Regards

7 Answers 7

If you want to pass the data using POST instead of GET, you can do it using a combination of PHP and JavaScript, like this:

function formSubmit(house_number)

Then in PHP you loop through the house-numbers, and create links to the JavaScript function, like this:

That way you just have one form whose hidden variable(s) get modified according to which link you click on. Then JavaScript submits the form.

Oh — the capital letter was just a typo, really — I didn’t let go of the shift key quickly enough! :o) I guess maybe I misunderstood the OP’s question, but I thought he was specifically looking for a way to do it using POST.

Читайте также:  PHP-сессии - создание

I assume that each house is stored in its own table and has an ‘id’ field, e.g house id. So when you loop through the houses and display them, you could do something like this:

Then in house.php, you would get the house id using $_GET[‘id’] , validate it using is_numeric() and then display its info.

Just open your house.php , find in it where you have $house = $_POST[‘houseVar’] and change it to:

isset($_POST[‘houseVar’]) ? $house = $_POST[‘houseVar’] : $house = $_GET[‘houseVar’]

And in the streeview.php make links like that:

Or something else. I just don’t know your files and what inside it.

This is an old thread but just in case anyone does come across i think the most direct solution is to use CSS to make a traditional form look like an anchor-link.

@ben is correct you can use php and javascript to send a post with a link, but lets ask what the js does — essentially it creates a form with style=’display:none’ sets an input/text line with value=’something’ and then submits it.

however you can skip all this by making a form. setting style=’display:none’ on the input/text lines (not the form itself as above) and then using CSS to make the button look like a normal link.

here is an example is i use:

public function styleButton($style,$text)< $html_str = "
"; $html_str .= ""; $html_str .= ""; $html_str .= "
"; return $html_str; >

Then in the CSS set «display:inline;» and in the CSS set to something like: «background:none;border:none;color:#fff;cursor:pointer»

Источник

Отправить post запрос с переходом на искомую страницу

Как отправить post запрос на определенный url, чтобы вместе с отправленным запросом пользователь оказался на странице, на которую запрос был послан? Пока есть такой код:

$postdata = http_build_query( array( 'shopId' => $user->Shop->shop_id, 'scid' => $user->Shop->sc_id, 'CustomerNumber' => $user->id, 'sum' => $pay->sum, 'orderNumber' => $pay->id, 'cps_phone' => '79110000000', 'cps_email' => 'user@domain.com', 'paymentType' => $_POST['paymentType'], // //PC - Со счета в Яндекс.Деньгах (яндекс кошелек) // 'paymentType' => 'PC', // //AC - С банковской карты // 'paymentType' => 'AC', ) ); $opts = array('http' => array( 'method' => 'POST', // 'header' => 'Content-type: application/x-www-form-urlencoded', 'content' => $postdata ) ); $context = stream_context_create($opts); $result = file_get_contents('http://example.com/submit.php', false, $context); 

Этот код, предположительно, работает)) Только он получает ответ в переменную $results , а нужно чтобы пользователь отправлялся на эту страницу вместе с запросом.

Читайте также:  Абсолютный путь до папки python

Ну так если пользователь должен вместе с запросом туда идти, то это надо на стороне клиента делать, а не на стороне сервера. На сервере вы можете либо сгенерировать форму с нужными значениями, показать эту форму клиенту и засабмитить эту форму сразу же, либо возвращать клиенту сгенерированный url, на который он будет перенаправлен, но тогда будет не post, а get-запрос

Источник

Вызов метода POST через ссылку

Вызывает метод doGet по умолчанию. Возможно ли его изменить на метод doPost ? И если да, то как будет выглядеть код ссылки?

а в чем проблема вместо ссылки поставить обычную форму. для этого даже javascript’a писать ненадо 2-3 хтмл строчки. но мухин достоин уважения, постарался 🙂

Вопрос вызван вообще незнанием как интернет работает. Разберитесь вообще что такое GET и POST, и что такое ссылки, браузер и HTML. А уже потом занимайтесь Java и сервлетами. И тогда не будет фраз вроде «a href вызывает метод doGet», да ещё и по умолчанию.

2 ответа 2

function postToUrl(path, params, method) < method = method || "post"; // Устанавливаем метод отправки. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) < var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", paramsPhp post запрос ссылкой); form.appendChild(hiddenField); >document.body.appendChild(form); form.submit(); > 

UPD1:
Забыл пример вызова оставить:

UPD2:
Такс. У меня такое чувство сложилось, что вы очень слабо представляете что такое клиентская часть и HTML-страница.
Ну так вот. Серверная часть тут не причем, когда задача стоит в отправке на сервер от клиента запрос. На вашей HTML или ‘JSP’ странице может присутствовать код HTML (как вы это прекрасно знаете), а также код JavaScript . Я не могу тут описать основы его работы и основы динамического ‘HTML’ или как там его еще называют. Приведу просто пример использования.

    , 'POST'");"> 

Вот как-то так. Ну и, можете посмотреть информацию про динамический HTML, JavaScript. Без этого сайты уже никак не обходятся на сегодняшний день.

Источник

Оцените статью