Jquery
Using JSON, PHP, JQUERY a practical example
Apr 29th
I am quite newbie in Jquery/Json area, so I was trying to make a simple practical exercise where my objective was to send 2 values from input fields to be calculated at server side using PHP. To send the value to server side I used Jquery and Json (AJAX) and the return value should be printed at user browser without refreshing the page. I know that there are many ways to do it, but I succeed with the example below that I want to share in this article. Any suggestions or comments are very welcome.
Basicaly we have to create 2 files in a PHP server, the first file I called index.php where we have the input fields, the button calc and where the result of calculation should be shown. Also you have to point the jquery.js script. In my case it was located at the same directory. Jquery will listen the Calc button and when it is pressed the values from input fields will be sent to calculator.php by means of JSON. The result will be printed at div id=result.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submitbutton").click(function(){
$.ajax({
url: "calculator.php", //URL where number will be calculated
dataType: "json", //Return type
data: "number1="+$('#number1').val()+"&number2="+$('#number2').val(), // input values to be sent by GET method
success: function(json){ //Return actions
$("#result").html("Result Sum of Number1="+json.number1+" Number2="+json.number2+" from PHP/Json: "+json.result); // result will be printed at id=result
}
});
});
});
</script>
</head>
<body>Number 1:
<input name="number1" id="number1" size="10" type="text" />
<br />Number 2:
<input name="number2" id="number2" size="10" type="text" />
<br />
<input type="submit" value="Calc" id="submitbutton" name="submitbutton"/>
<br />
<div id="result">
</div>
</body>
</html>
Now the calculator.php where values from input fields are handled and result is returned using json_encode.
<?php $number1 = $_GET['number1']; $number2 = $_GET['number2']; $sum = $number1 + $number2; $arr = array(); //array declaration that will be used to return the values //fill up array with the values you want to return $arr['result'] = $sum; $arr['number1'] = $number1; $arr['number2'] = $number2; //The function json_encode() converts the array format to Json format echo json_encode($arr); ?>
