I'm working on a project where I have an HTML file with 2 different divs: "product" and "price". The text inside these divs must come from a row into a database. I can easily access these text values with a php file. I'm also able to get just one of them using AJAX and I can put it inside one of the divs. The problem is I don't know how I can get both product and price and put them inside the divs. I've found some very similar questions but none of the answers have worked for me.
Here is the JS code that I have:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#product").html(response);
}
});
Here is the php (the columns I have are just id, product and price):
mysqli_query($link, $query);
$query = "SELECT * FROM products WHERE id = 1";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_array($result)) {
echo "{$row['product']}";
}
}
As I said, the code above works, but only for "product". I want to get both "product" and "price". I really appreciate any help you can provide.
You need to use JSON. Here is a simple example:
$.ajax({
type: "GET",
url: "url to the php file",
dataType: "html",
success: function(response){
$("#name").html(response.name);
$("#shoes").html(response.large);
},
dataType: 'json'
});
And then in the PHP to return back JSON use this approach:
$array = array('name' => 'Bob', 'shoes' => 'large');
echo json_encode($array);
You can amend my PHP so you return back whatever you query from your database.