A
A
Anton2021-07-03 05:19:31
PHP
Anton, 2021-07-03 05:19:31

Why is the variable not being passed through ajax?

Greetings, tell me why the data is not transferred to the variable, the variable is simply empty.
jsjquery:

$(document).on('click', '#button', function(){
  let txt = 'Hello';
  $.ajax({
    url: 'test.php',
    type: 'POST',
    data: txt,
    success: function(data){
     $('p.out').text(data);
   },
    error: function(){
  console.log('ERROR');
    }
 })
})

test.php:
<?
$txt = $_POST['txt']; //Почему-то пусто...
echo $txt;
?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-07-03
@boypush

Because data must be an object, not a string:

$(document).on('click', '#button', function(){
  let txt = 'Hello';
  $.ajax({
    url: 'test.php',
    type: 'POST',
    data: { txt },
    success: function(data){
     $('p.out').text(data);
   },
    error: function(){
  console.log('ERROR');
    }
 })
})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question