Pass Data with Ajax to PHP

Using the method below you can retrieve data from a database and run PHP scripts using the values of the forms and fields to pass the data from Ajax to PHP code. We will be using Ajax to collect and send the data from the forms to an PHP file, where we process it, and then return the results with Ajax again.

CREATING HTML PAGE

[html]
<input id="text1" type="text" /> +
<input id="text2" type="text" />
<button id="button"> = </button>
<div id="result"></div>
[/html]

PASSING DATA WITH AJAX

[html]
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
[/html]

Once we have the form and jQuery included in our document we need to store there values in 2 different variables that would be ( val1 and val2 ) so we can pass them to the PHP file to process further.

[php]
$(‘#button’).click(function() {
var val1 = $(‘#text1’).val();
var val2 = $(‘#text2’).val();
$.ajax({
type: ‘POST’,
url: ‘process.php’,
data: { text1: val1, text2: val2 },
success: function(response) {
$(‘#result’).html(response);
}
});
});
[/php]

We have created a “.click event” when the button with ID of #button is clicked, the it will call out function. after that we will get the value of each text field and assign it in val1 and val2.
Once we have the values we can now create an “$.ajax method”.

This method has 4 parameters.

  • type
  • url
  • data
  • success

If we use POST then in the PHP file, we use $_POST[”] to get the value. If we use GET then we use $_GET[]

PHP FILE

[php]
$text1 = $_POST[‘text1’];
$text2 = $_POST[‘text2’];
echo $text1 + $text2;
[/php]