Sending Data to Ajax Using PHP

Introduction

In this article I explain how to send data to Ajax using PHP. In the sample in this article I have two buttons on the browser page, labeled "Developers" and "Technologies". When either button is pressed, an Ajax request is sent to a PHP script with the query parameter ? type=developer or ?type=technologies. When the PHP script receives the request it uses the query value to select and return an appropriate developer's entry encoded as JSON.

Example

This is a PHP script file. Save it with the name "dev_tech.php".

<?php

error_reporting(E_ALL);

$developers = array(

"Nitin", "Sharad", "Manish", "Rahul",

"Aman", "Anubhav", "Sandip", "Prabhakar"

);

$technologies = array(

".Net", "PHP", "Jsp", "IPhone",

"C++", "JavaScript", "C", "Java"

);

if (isset($_GET['type'])) {

switch ($_GET['type']) {

case "developers":

print json_encode($developers[array_rand($developers)]);

break;

case "technologies":

print json_encode($technologies[array_rand($technologies)]);

break;

default:

print json_encode("n/a");

break;

}

}

?>

This is a HTML file that loads the response from an Ajax request. I handled the .click event of either of our two buttons by sending an Ajax .load request. The "deve_tech.php" file receives this request, along with a type parameter, and sends back a string response, that is loaded into our document. I have used the "array_rand" function to generate a random index of our chosen array and then I used "json_encode" to output it in JSON format data.

<html>

<head>

<title>Developers and Technologies Example</title>

</head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">

</script>

<script type="text/javascript">

 $(document).ready(function ()
{

  $("#developers").click(function ()
{

  $("#response").load("dev_tech.php?type=developers");

});

  $("#technologies").click(function ()
{

 $("#response").load("dev_tech.php?type=technologies");

    });

 });

</script>

<body bgcolor="#E0FED6">

<button id="developers">Developers</button>

<button id="technologies">Technologies</button>

<p><strong>Ajax response from PHP:</strong></p>

<div id="response">&nbsp;</div>

</body>

</html>

Output

When you click on the developer's button then your developers name is randomly shown from the array.

cal2.jpg

And the same thing when you click on technologies, your technology name is shown randomly.

dynamic check.jpg


Similar Articles