K
K
kickass772021-07-30 04:35:56
AJAX
kickass77, 2021-07-30 04:35:56

How to correctly pass a variable through ajax?

Hello.
I have a form, I collect data and want to process it via ajax via GET, but there is a variable that was previously sent via POST, I changed the algorithm, but I don’t understand why it doesn’t work through this principle.

-----

Here I bind the id to get the data from the input and also upload the file:

<label class="contact-lable">Название</label>
<input name="name" id="my_name" class="form-control" type="text" />

<label for="exampleFormControlFile1">Загрузить файл</label>
<input type="file" name="path" class="form-control-file" id="file" accept=" .txt ">


Further actions:

<script>
         $(document).ready(function(){
            $("#start_function" ).click(function(){
                // start_function - это id кнопки при которой срабатывает код ниже

                var my_name = $("#my_name").val();
                // получаю данные из input
  
                var files; // переменная будет содержать данные файлов

                // заполняем переменную данными, при изменении значения поля file 
                $('input[type=file]').on('change', function(){
                  files = this.files;
                });
                
                $.ajax({
                    url: "include/ajax.php",
                    cache: false,
                    data: ({type:"upload", my_name:my_name,files:files}),
                    success: function(html){
                        $("#upload_ajax").html(html);
                        alert("ok");
                    }
                });
                return false;
            });
         });
      </script>


The ajax file itself, where I receive data and process it:

if($_GET['type'] == 'upload') {
    $my_name = $_GET['my_name'];
    $files = $_GET['files'];


    $data = array();
    $error = false;
    $files = array();

    // переместим файлы из временной директории в указанную
    foreach( $_FILES as $file ){
      
    	$uniqdir = "keys";
    	$uniqfile = base_convert(uniqid().rand(0,2000000000), 10, 36);

    $uploaddir = './'.$uniqdir; // . - текущая папка где находится submit.php
    
    // Создадим папку если её нет
    if( ! is_dir( $uploaddir ) ) mkdir( $uploaddir, 0777 );
  
      $type = pathinfo($file['name'], PATHINFO_EXTENSION);
          $file_name = $uniqfile .'.'. $type;
      
          if( move_uploaded_file( $file['tmp_name'], "$uploaddir/$file_name" ) ){
              $files[] = realpath( "$uploaddir/$file_name" );
          }
          else{
              $error = true;
          }

          // Здесь я получаю в переменную имя файла, чтобы сохранить
          $keys_file = $file_name;
    	}
  
      $data = $error ? array('error' => 'Ошибка загрузки файлов.') : array('files' => $files );
    
    echo json_encode( $data );

    // Сохраняю в базу данных
    $save = R::dispense('data');
        $save->my_name = $my_name;
        $save->keys_file = $keys_file;


      	R::store($save);
  }


The data from input with id = my_name is successfully saved to the database.
The algorithm for saving the file on the server is also correct - it works, but via POST.
The problem is that I used to pass the files variable via POST, but now I receive it via GET.

Why does this method work for id = my_name, but refuses to work for files, or did I make a mistake somewhere?

Purpose: following a similar structure for convenience, save the data from my_name and the file name to the database, and upload this file to the server.

Help sort out the problem.
Data from files to ajax file is passed empty.

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-07-30
@zkrvndm

The GET method involves passing data in the address bar. For example, when opening a link like this:

https://yousite.ru/include/ajax.php?per1=test&per2=test

Your PHP handler will receive this data as $_GET['per1'] and $_GET['per2']
I think it's obvious that the GET method can only pass text? And at the same time, the size of the text is very limited, since links physically cannot be more than 2048 characters.
If you want to send a file using the GET method, you need to convert the file to base64 text and send this text, but not as a variable, but directly in the request body, while the content type of the request must be plain / text - in the request body already there will be no restrictions on the amount of transmitted information.
However, wouldn't it be easier to send the file by POST, why did you refuse it?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question