Sending Data to Ajax Using PHP


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.


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



$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)]);


case "technologies":

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



print json_encode("n/a");





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.



<title>Developers and Technologies Example</title>


<script type="text/javascript" src="">


<script type="text/javascript">

 $(document).ready(function ()

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



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





<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>




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


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

dynamic check.jpg

Up Next
    Ebook Download
    View all
    View all