jcadima
2/10/2017 - 10:20 PM

Simple PHP Ajax return addition of values

Simple PHP Ajax return addition of values





<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>jQuery Ajax test</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
	</head>
	<body>


<form id="calc">
	<div class="row">
		<div class="container">
			<div class="col-md-3">
				<div class="form-group">
				  <label for="usr">A:</label>
				  <input type="text" class="form-control" name="a" id="a">
				</div>				
			</div>

			<div class="col-md-3">
				<div class="form-group">
				  <label for="usr">B:</label>
				  <input type="text" class="form-control" name="b" id="b">
				</div>
			</div>

			<div class="col-md-3">
				<div class="form-group">
				  <label for="usr">C:</label>
				  <input type="text" class="form-control" name="c" id="c">
				</div>
			</div>

			<div class="col-md-3">
				<div class="form-group">
				  <label for="usr">D:</label>
				  <input type="text" class="form-control" name="d" id="d">
				</div>
			</div>


		</div>

	</div>


		The following div will output the sum of a + b + c + d:<br />
		<div id="result"> </div>
		<input type="submit" name="submit" value="Calculate">

</form>



	</body>

<script>	

/* Get from elements values */

$("#calc").submit(function(event) {
console.log("SUBMITTED") ;
	 var values = $(this).serialize();
    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div */
    /* I am not aborting previous request because It's an asynchronous request, meaning 
       Once it's sent it's out there. but in case you want to abort it  you can do it by  
       abort(). jQuery Ajax methods return an XMLHttpRequest object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "calculate.php",
            type: "post",
            data: values
        });

      /*  request cab be abort by ajaxRequest.abort() */

     ajaxRequest.done(function (response, textStatus, jqXHR){
          // show successfully for submit message
          console.log("SUCCESS") ;
          $("#result").html(response);
     });

     /* On failure of request this function will be called  */
     ajaxRequest.fail(function (){

       // show error
       console.log("ERROR") ;
       $("#result").html('There is error while submit');
     });

});



</script>
	
</html>




calculate.php:

<?php

$a = $_POST['a'] ;
$b = $_POST['b'] ;
$c = $_POST['c'] ;
$d = $_POST['d'] ;

$z = $a + $b + $c + $d ;

// this is the output that will be shown in div id="result"
echo 'Result: ' . $z;