M
M
methodPOST2019-11-17 18:12:30
PHP
methodPOST, 2019-11-17 18:12:30

How to find a line in a file, change the data attribute, save and close the file in php?

Hello! I have nothing to do with php and would not have, if not the implementation of this task. Using AJAX, I am loading data and displaying it in the parent when the page loads. Each child element that was placed in the parent has two buttons responsible for changing the status of the order. By clicking on the button, I pass the parameters to the URL string and send a request to the handler file. The parameters look like this: ?done=89991234567 or ?nope=89991234567. The file handler takes a phone number from a string and looks it up in the file. Further, if the parameter is "done" in the address bar, then change the content of the found line attribute data-status="wait" to data-status="done", and vice versa, if "nope" - change to data-status="nope " and save the changes in the file, preferably on the same line. Presently, I've been up all night on the forums looking for information and all I could do was search for a line in a file, change data-status="wait" to data-status="done" and output the same line with "echo $order". I have two problems: 1) how to get the parameter after the question mark (done/nope(not phone number)); 2) how to change the data attribute parameter in the HTML file, and then save the changes in the file;

Here is what I have for coding:

JS

change_status.forEach(function(e){ // change_status = document.querySelectorAll('.change_status')
  e.addEventListener('click', function(){
    xhr = new XMLHttpRequest;
    xhr.open('get', 'resource/change_status_order.php?' + e.classList[1] + '=' + e.dataset.phone, true); // class имеет вид class="change_status done(или nope)", получаю второй класс в элементе для параметра url
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.onreadystatechange = function(){
      if(xhr.readyState == 4 && xhr.status == 200){
        if(xhr.responseText == 'true'){ // написал изначально, чтобы проверить работу запроса сейчас всегда вернет ошибку
          window_popup('done'); // функция попап уведомления
        }else{
          window_popup('nope')
        }
      }
    }
    xhr.send();
  })
})


And the PHP code itself:

<?php
  $searchthis = $_GET['done']; // Здесь я получаю номер из параметров в ручную...

  $base = fopen("html/allorders.html", "r"); // мой файл
  
  if ($base)
  {
      while (!feof($base))
      {
          $buffer = fgets($base);
          if(strpos($buffer, $searchthis) !== FALSE)
        $order = $buffer;

        $DOM = new DOMDocument();
                          $DOM->loadHTML($order);

          	foreach ($DOM->getElementsByTagName("div") as $status){
          		$status->setAttribute("data-status", "done");
          		echo $DOM->saveHTML();
          		exit;
          	}
          	
      }
      fclose($base);
  }

  echo $order; // здесь выводится моя найденная строка с уже измененным атрибутом.
// Именно её я не знаю, как сохранить в файле на той же строке
// Я пробовал $fwrite($base, $order), но выдает куча не понятных мне ошибок, да и я уверен, что если и запишет, то запишет в конец файла, а нужно в данном случае в блок class="orders".
// Использовал r+ и a+ для файла. Пишет фатальная ошибка....
?>


And here is how the parameters are stored in the file:

<div class="orders"> <!-- при записи, строка не должна уходить дальше этого блока -->
      <div data-k="000" data-g="001" data-s="051" data-status="wait" data-person="2" data-price="1200" data-tel="8999123456" data-time="23:00" data-date="17 Ноября" class="myOrder"></div>
    </div>


Where data-status="wait" is the same attribute whose content needs to be changed to the parameter from the url. Let me remind you that if url = my.site?done=8999123456, then in the line of the file with the number 8999123456, data-status="wait" should change to data-status="done".

Help me please. And remember, I don't know php AT ALL and it's not necessary for me to learn. I love front-end=)

UPD I want to be understood correctly: I'm not asking to "do it for me". I ask for any keywords for searching on the Internet (I myself, of course, searched), links, and if it’s not difficult for you to finish the code, then I’ll be glad only for this.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question