Home » Php » php – Send and receive data in same ajax request with jquery

php – Send and receive data in same ajax request with jquery

Posted by: admin July 12, 2020 Leave a comment

Questions:

What is the best way to send data and receive a response dependent on that data?

Consider the PHP file used for the request:

$test = $_POST['test'];

echo json_encode($test);

I have tried unsucessfully to achieve this with:

$.ajax({
    type: "POST",
    dataType: "json",
    data: '{test : worked}',
    url: 'ajax/getDude.php',
    success: function(response) {
        alert(response);
    }
});
How to&Answers:

Lose the quotes to pass the object:

$.ajax({
  type: "POST",
  dataType: "json",
  data: {test : worked},
  url: 'ajax/getDude.php',
  success: function(data) {
    alert(data);
  }
});

Answer:

Instead of this

data: '{test : worked}'

try

data: {"test" : worked} // Worked being your data you want to pass..
 data: {"test" : "worked"} // Else enclose worked in quotes

Answer:

The problem appears to be that you’re submitting a string rather than a json object – change data: '{test : worked}' to data: {test : 'worked'}