Pascal Pascal - 6 months ago 21
Ajax Question

Updating div content with jQuery ajax function over PHP

I am trying to update my div content (#update_div) by sending the value of two input fields to a php file (search_value.php) using the .ajax() function from jQuery.

It works, if I just redirect the two values of the input fields using the html form POST method. So the search_value.php should be correct.




My HTML Code:

<form id="my_form">
<input id="food" name="food">
<input id="amount" value="amount in gram" name="amount">
<input type="button" value="Update" id="submit" name="submit" />
</form>

<div id="update_div">
</div>





My Javascript Code:

$("#submit").click(function() {
var food = $("#food").val();
var amount = $("#amount").val();
$.ajax({
url: 'search_value.php',
type: 'GET',
data: {"food":food,"amount":amount},
success: function(data)
{
$('#update_div').html(data);
}
});
});





My PHP Code:

<?php
$pdo = new PDO('mysql:host=localhost;dbname=calotools', 'root', '');

$food = $GET_['food'];
$amount = $GET_['amount'];

$query="SELECT * FROM nahrungsmittel WHERE name = '$food'";

$user = $pdo->query($query)->fetch();
echo $user['name']."<br />";
echo $user['kcal'] / 100 * $amount;
?>





I do not really get a feedback by clicking the button. Maybe you guys can tell me why?

Answer

For GET request, there should not be data part, make it as a query string as below js code:

$("#submit").click(function() {
   var food = $("#food").val();
   var amount = $("#amount").val();
   $.ajax({
   url: 'search_value.php?food='+ food + '&amount='+amount,
   type: 'GET',
   datatype: "html",   
   success: function(data)
   {
     $('#update_div').html(data);
   },
   failure : function(ex)
   {
      console.log(ex);
   }
  });
});

And use $_GET instead of $GET_ in php