Jquery with Ajax post not working

2.5k Views Asked by At

I am trying to make a simple game and I'm not very good with jQuery. The code I have is:

<script type="text/javascript">
$(document).ready(function(){
    $('#deposit').click(function(){       
        $.ajax({
            type: 'POST',
            url: 'update.php',
            dataType: 'json',
            data: {
                Money : $('#input_money').val()
            },
            success: function(data){ 
                $('#display').html(data.value);
            }
        });
    });
});
</script>

And the display is this:

<input id="input_money" name="input_money" type="text" size="40"><br><br>
<button id="deposit">Deposit Money</button>
<div id="display"></div> 

For the back end, I am using this:

if(isset($_POST['Money'])){
    $value = $_POST['Money'];   
} else {
    $value = "";
}
echo json_encode(array("value"=>$value));  

Can anyone help me out? I plan to add the $value into a database after it shows up on the main page.

Thanks

2

There are 2 best solutions below

6
On

I fired this on my serv, find it at: this link

It works just fine. Heres the source, just like yours.

<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
   $('#deposit').click(function(){      
  $.ajax({
            type: 'POST',
            url: 'update.php',
            dataType: 'json',
            data: {
                Money : $('#input_money').val()
            },
            success: function(data){ 
                $('#display').html(data.value);
            }
        });
   });
});
  </script>


<input id="input_money" name="input_money" type="text" size="40"><br><br>
<button id="deposit" type="button">Deposit Money</button>

<div id="display"></div> 

Hope youll get it to work. Best regards Jonas

0
On

Try this (untested and without Json, but should work straight).

HTML:

<form method="post" action="" id="myform">
<p><input id="input_money" name="input_money" type="text" size="40"></p>
<button id="deposit" type="submit" name="deposit">Deposit Money</button>
</form>

<div id="display"></div> 

JS:

    <script type="text/javascript">
      $(document).ready(function()
      {
       $('#myform').submit(function()
       {   
        var dataString = $(this).serialize();   
        $.ajax({
            type: 'POST',
            url: 'update.php',
            data: dataString,
            success: function(response){ 

                $('#display').html(response);
            },
            error: function(){
            alert('There was an error in AJAX call!');
            }
        });
        return false;
       });
    });
</script>

PHP:

echo isset($_POST['input_money']) ? htmlentities($_POST['input_money']) : 'no value';