How to send a post request to a specific url, so that along with the sent request the user is on the page to which the request was sent?

While there is such code:

$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); 

This code supposedly works))

Only he gets the answer to the $results variable, and it’s necessary that the user goes to this page along with the request.

  • 2
    Well, if the user has to go there with the request, then this should be done on the client side, and not on the server side. On the server, you can either generate the form with the necessary values, show this form to the client and submit this form immediately, or return the generated url to which the client will be redirected to, but then the post request will be not a post, but a BOPOH
  • one
    @BOPOH is sensible. Issue as an answer. - tutankhamun
  • @BOPOH Thank you, at first I didn’t realize at all that if the client should see it, then it should be on his side. - Artem Bogdanov

2 answers 2

  1. create a form filled with incoming POST data;
  2. JavaScript send this form with the visitor to the final site.

Approximate php:

 $url = 'http://ya.ru'; // ссылка, куда надо сделать POST запрос $dataFields = array( // ассоц. массив данных, которые нужно передать 'shopId' => $user->Shop->shop_id, 'scid' => $user->Shop->sc_id, ); $html = sprintf( '<form name="formPost" id="formPost" action="%s" method="post">', $url); foreach( $dataFields AS $key=>$value) { $html .= sprintf( '<input type="hidden" name="%s" value="%s">', $key, $value); } $html .= '</form>'; 

And add the dispatch immediately, or by the UI event. Something like:

 $html .= <<<EOFJS <script> document.formPost.submit(); </script> EOFJS; echo $html; 

    ajax ohm can be implemented.

      <form target="_blank" action="https://demomoney.yandex.ru/eshop.xml" style="border:1px solid #c2c2c2; padding:20px 15px;" name='paymentForm' method="post"> <input type="hidden" name="shopId" value="XXXXXXX"> <input type="hidden" name="scid" value="XXXXXXXx"> <input type="hidden" name="customerNumber" value="XXXXXXX"> <input type="hidden" name="payTime" value="<?= time(); ?>"> <label>Способ оплаты</label> <select name="paymentType"> <option value="PC" selected="selected">Оплата из кошелька в Яндекс.Деньгах</option> <option value="AC">Оплата с произвольной банковской карты</option> <option value="MC">Оплата со счета мобильного телефона</option> <option value="GP">Оплата наличными через кассы и терминалы</option> <option value="WM">Оплата из кошелька в системе WebMoney</option> <option value="SB">Оплата через Сбербанк: по смс или Сбербанк Онлайн</option> <option value="MP">Оплата через мобильный терминал (mPOS)</option> <option value="AB">Оплата через Альфа-Клик</option> <option value="MA">Оплата через MasterPass</option> <option value="PB">Оплата через интернет-банк Промсвязьбанка</option> <option value="QW">Оплата через QIWI Wallet</option> <option value="KV">Оплата через КупиВкредит (Тинькофф Банк)</option> <option value="QP">Оплата через Доверительный платеж на Куппи.ру</option> </select> <label>Цена</label> <input type="text" name="sum"> <br> <div id="pay" class="btn btn-success" >Оплатить</div> </form> 

    JQuery itself:

      <script> (function ($) { /* * Делаем глобально, для того чтобы переменная была доступна для callback функции */ form = $('form[name=paymentForm]'); $('#pay', form).click(function () { var data = $(this).serialize(); $.ajax({ url: '/saveData.php/', type: 'POST', data: data, dataType: 'json', success: function(responce){ if(!responce.error){ /* * Если данные сохранены успешно отправляем форму с перенаправлением на целевую страницу * в данном случае https://money.yandex.ru/eshop.xml */ form.submit(); }else{ alert(responce.msg); } } }); }); })(jQuery); </script> 

    In the saveData.php handler

      <?php if(isset($_POST)){ //сохранение в БД } //после сохранения в БД возвращаете ответ так echo json_encode(array('error' => false, 'msg' => 'Данные сохранены')); //или echo json_encode(array('error' => true, 'msg' => 'Данные не сохранены')); ?> 

    Checked by me personally. Works)