Bruno Alex Bruno Alex - 17 days ago 6
Ajax Question

ajax post to php and retrieve sql result

im using ajax and php on my android app to query my database.

i am able to retrive all the results but dont know how to send a variable to my php so that i can use it as a custom query and retrive the results... something like this :

$id = $_POST['id'];

$sql = "SELECT * FROM mobile_app WHERE nome LIKE '{%id%}'";


but cant make my ajax post the variable and retrive the result...

this is my code :

my mobile app:

$.ajax({
url: "http://www.example.com/mobile_read.php", // path to remote script
dataType: "JSON", // data set to retrieve JSON
success: function (data) { // on success, do something...
// grabbing my JSON data and saving it
// to localStorage for future use.
localStorage.setItem('myData', JSON.stringify(data));
}
});


my php:

$sql = "SELECT * FROM mobile_app";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$output[] = array (
"nome" => $row['nome'],
"status" => $row['status'],
"hentrada" => $row['hentrada'],
"evento" => $row['evento']
);
}



} else {
echo "0 results";
}


$conn->close();
echo json_encode($output);

Answer

You need to add the following additional options to your $.ajax object:

type: 'post'

and

data: {
    id: whateverVariableHasID
} 
Comments