1

I have a simple thing. HTML code for the message sending form in telegram bot. Code in Js And php code.

But about sending the form gives an error POST http://127.0.0.1:5500/ajax.php 405 (method not allowed)

How to fix? HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="./main.css">
</head>
<body>
<div class="container">
    <div class="log-form">
        <h2>Отправка формы в телеграм</h2>
        <form class="telegram-form">
          <input type="text" name="name" placeholder="Имя" autocomplete="off" />
          <input type="text" name="phone" placeholder="Телефон" autocomplete="off" />
          <input type="text" name="email" placeholder="Email" autocomplete="off" />
          <textarea name="text"></textarea>
          <input type="file" name="file">
          <button type="submit" class="btn">отправить</button>
        </form>
      </div>
</div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="./main.js"></script>
</body>
</html>

PHP:

<?php
// Токен телеграм бота
$tg_bot_token = "5300693289:AAG-3R2gy2qSO_ZfBgTo_4XB_4fCe0w3f-s";
// ID Чата
$chat_id = "-600004198";

$text = '';

foreach ($_POST as $key => $val) {
    $text .= $key . ": " . $val . "\n";
}

$text .= "\n" . $_SERVER['REMOTE_ADDR'];
$text .= "\n" . date('d.m.y H:i:s');

$param = [
    "chat_id" => $chat_id,
    "text" => $text
];

$url = "https://api.telegram.org/bot" . $tg_bot_token . "/sendMessage?" . http_build_query($param);

var_dump($text);

file_get_contents($url);

foreach ($_FILES as $file) {

    $url = "https://api.telegram.org/bot" . $tg_bot_token . "/sendDocument";

    move_uploaded_file($file['tmp_name'], $file['name']);

    $document = new \CURLFile($file['name']);

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, ["chat_id" => $chat_id, "document" => $document]);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    $out = curl_exec($ch);

    curl_close($ch);

    unlink($file['name']);
}

die('1');

JS:

$('.telegram-form').on('submit', function (event) {

    event.stopPropagation();
    event.preventDefault();

    let form = this,
        submit = $('.submit', form),
        data = new FormData(),
        files = $('input[type=file]')


    $('.submit', form).val('Отправка...');
    $('input, textarea', form).attr('disabled','');

    data.append( 'name',        $('[name="name"]', form).val() );
    data.append( 'phone',       $('[name="phone"]', form).val() );
    data.append( 'email',       $('[name="email"]', form).val() );
    data.append( 'text',        $('[name="text"]', form).val() );
    data.append( 'file',        $('[name="file"]', form).val() );
   

    files.each(function (key, file) {
        let cont = file.files;
        if ( cont ) {
            $.each( cont, function( key, value ) {
                data.append( key, value );
            });
        }
    });
    
    $.ajax({
        url: 'http://127.0.0.1:5500/ajax.php',
        method: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false,
        contentType: false,
        xhr: function() {
            let myXhr = $.ajaxSettings.xhr();

            if ( myXhr.upload ) {
                myXhr.upload.addEventListener( 'progress', function(e) {
                    if ( e.lengthComputable ) {
                        let percentage = ( e.loaded / e.total ) * 100;
                            percentage = percentage.toFixed(0);
                        $('.submit', form)
                            .html( percentage + '%' );
                    }
                }, false );
            }

            return myXhr;
        },
        error: function( jqXHR, textStatus ) {
            // Тут выводим ошибку
        },
        complete: function() {
            // Тут можем что-то делать ПОСЛЕ успешной отправки формы
            console.log('Complete')
            form.reset() 
        }
    });

    return false;
});

I tried to search on the Internet but could not find a solution. In a good way, the code should send the form data to the telegram bot and clear the form itself.

Laplas
  • 91
  • 5

1 Answers1

0

I guess the problem is that the server that is supposed to run your php code does not accept POST requests. Try issuing a GET request, if it works without problems - you need to change your server configuration. If you GET request is unsuccessful too - check that url on server and url at which you are sending the request are matching.

Edit:

After figuring out the source of problem, the answer on this question is here: How to use php on visual studio code

VSCode serves only static files, which means that it does not accept request types other than POST. You should use some web server that will run you code. Here is an instruction on How to install Apache on your Windows computer

Edit 2:

Seems like a new problem is appeared, which lies in php script:

file_get_contents($url); - Here php tries to open the file instead of sending request. Seems like you need to reconfigure your php interpreter or send this request in a different way.

Reconfiguring the interpreter is not quite easy, so you can send POST request as in this StackOverflow answer

David
  • 272
  • 2
  • 8
  • No nothing is happening – Laplas Apr 22 '22 at 20:42
  • You get 2xx as response, or 4xx? – David Apr 22 '22 at 20:44
  • nothing at all. Provided that I changed everything in the right places. – Laplas Apr 22 '22 at 20:48
  • I guess it means that the request is successful. Please provide the way you running your php scripts (Apache, or something different). By the way, you can doublecheck that response is successful by getting into Developer tools of your browser and Network tab – David Apr 22 '22 at 20:55
  • php runs sort of like I have through a regular live server in VS code, or does it need to be run through something else? – Laplas Apr 22 '22 at 20:58
  • Yes, you need some server engine to run your php. Please refer to edited answer. – David Apr 22 '22 at 21:08
  • no it doesn't work. The server console in PHP says [Sat Apr 23 00:20:48 2022] 127.0.0.1:55030 Closure [Sat Apr 23 00:20:48 2022] 127.0.0.1:55077 Accepted [Sat Apr 23 00:20:48 2022] 127.0.0.1:55078 Accepted [Sat Apr 23 00:20:48 2022] 127.0.0.1:55077 [200]: GET /main.js [Sat Apr 23 00:20:48 2022] 127.0.0.1:55077 Closure [Sat Apr 23 00:20:48 2022] 127.0.0.1:55079 Accepted [Sat Apr 23 00:20:48 2022] 127.0.0.1:55079 [200]: GET //ws [Sat Apr 23 00:20:48 2022] 127.0.0.1:55079 Closure [Sat Apr 23 00:20:48 2022] 127.0.0.1:55080 Accepted – Laplas Apr 22 '22 at 21:22
  • and i have this WebSocket connection to 'ws://127.0.0.1:5500//ws' failed: – Laplas Apr 22 '22 at 21:25
  • Please add screenshots of everything you mentioned in your question – David Apr 22 '22 at 21:28
  • just that the errors just disappeared and the console gives the code 200. But the message in the telegram never arrives. – Laplas Apr 22 '22 at 21:29
  • Does your php script runs when you sending a request? – David Apr 22 '22 at 21:34
  • Warning: file_get_contents(): Unable to find the wrapper "https" - did you forget to enable it when you configured PHP? in C:\Users\Алексей\Desktop\telegram-sender-main\ajax.php on line 25 end Warning: file_get_contents(https://api.telegram.org/bot5300693289:AAG-3R2gy2qSO_ZfBgTo_4XB_4fCe0w3f-s/sendMessage?chat_id=-600004198&text=%0A127.0.0.1%0A22.04.22+21%3A34%3A41): Failed to open stream: No such file or directory in C:\Users\Алексей\Desktop\telegram-sender-main\ajax.php on line 25 – Laplas Apr 22 '22 at 21:35
  • the strangest thing is that it came code 200 and is written successfully in the console But there is no message. – Laplas Apr 22 '22 at 21:38
  • how i need to reconfigure my php interpreter or send this request in a different way. Sorry but i not have idea how fix that – Laplas Apr 22 '22 at 21:50
  • by the way, I noticed that if you send an image through the form, it appears in the project files – Laplas Apr 22 '22 at 21:52