coiso
coiso

Reputation: 7479

Send and receive data in same ajax request with jquery

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);
    }
});

Upvotes: 7

Views: 12192

Answers (3)

user1757786
user1757786

Reputation:

Lose the quotes to pass the object:

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

Upvotes: 8

Kelvin
Kelvin

Reputation: 5307

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

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

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

Upvotes: 5

Related Questions