FabianCannes
FabianCannes

Reputation: 87

Ajax script is not updating PHP file and his var value

This is simple form, on click i need calculated value to be displayed in file process.php, but this is not working for me. It seems that "click" on "=" don't do anything, in process.php there is default value "0", no results.

 <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="//code.jquery.com/jquery-1.12.0.min.js">
$('#button').click(function() {
    var val1 = $('#text1').val();
    var val2 = $('#text2').val();
    $.ajax({
        type: 'POST',
        url: 'demo/process.php',
        data: { text1: val1, text2: val2 },
        success: function(response) {
            $('#result').html(response);
        }
    });
});
</script>

<input type="text" id="text1"> +
<input type="text" id="text2">
<button id="button"> = </button>

<div id="result"></div>
</body>
</html>

AND PHP

<?php
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
echo $text1 + $text2;
?>

Upvotes: 2

Views: 59

Answers (1)

Thibaut
Thibaut

Reputation: 180

first of all, are you using a php server?

if you do then try this (yes i used a different library):

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    </head>
    <body>
        <form>
            <input type="text" id="text1" /> 
            <input type="text" id="text2" />
            <button type="button" id="button"> = </button>
        </form>

        <div id="result"></div>    
        <script type="text/javascript">
            $('#button').click(function() {
                var val1 = $('#text1').val();
                var val2 = $('#text2').val();

                $.post( "demo/process.php", {text1: val1, text2: val2} ,     function(data){
                    $('#result').html(data);
                });
            });
        </script>
    </body>
</html>

in php:

<?php
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
echo $text1 + $text2;
?>

Tip: Always specify the type attribute for a element. Different browsers use different default types for the element.

Upvotes: 1

Related Questions