jQuery Ajax+PHP Tutorial

Posted on

What About jQuery and AJAX?

The combination of jQuery and ajax provide powerfull functionality. With jquery ajax you can make request for text or html from your remote server. If data is large you can use json to receive them. After receiving Ajax response we can use them in our html page.
jQuery provides some powerful set of jQuery AJAX API's to handle AJAX requests. In good way of making AJAX calls using JavaScript is a little bit odd as you have to first create an XMLHttpRequest Object that depends on the browser and then make an AJAX call. Also sending a form data using AJAX is also bit difficult if we use normal JavaScript approach of calling AJAX.

jQuery provides simple yet powerfull functions which have extended the JavaScript AJAX methods and provide more flexible way. Let us see way of doing AJAX things in jQuery.

In this tutorial of PHP Code for beginners we will show you how to use jQuery Ajax in your PHP form. Lets start... To use Jquery Ajax we need to create two files, In first file our html php code present from where we do ajax request. In second file we process the Ajax request and return the result to first page.

Step 1: Create a University.php file

<html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> <script> function getdetails(){ var name = $('#name').val(); var rno = $('#rno').val(); $.ajax({ type: "POST", url: "details.php", data: {fname:name, id:rno} }).done(function( result ) { $("#msg").html("Address of Roll no " +rno +" is "+result ); }); } </script> </head> <body> <table> <tr> <td>Your Name, Surname:</td><td><input type="text" name="name" id="name" /><td> </tr> <tr> <td>Roll Number:</td><td><input type="text" name="rno" id="rno" /><td> </tr> <tr> <td></td> <td><input type="button" name="submit" id="submit" value="submit" onClick = "getdetails()" /></td> </tr> </table> <div id="msg"></div> </body> </html>
In above code we are taking name and roll no of student and pass this to details.php using jquery ajax.

Step 2: Create details.php

<?php $name = $_POST['fname']; $rno = $_POST['id']; $con = mysql_connect("localhost","root",""); $db= mysql_select_db("university", $con); $sql = "SELECT address from students where name='".$name."' AND rno=".$rno; $result = mysql_query($sql,$con); $row=mysql_fetch_array($result); echo $row['address']; ?>
Free Hit Counters