Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Passing Data to the server with POST using AJAX

Like using the GET query, data can also be send to the server using POST query.

Here's how.

choose_msg.php

<?php
if($_REQUEST["data"]=="1")
{
  echo "You sent the server a value of 1";
}
if($_REQUEST["data"]=="2")
{
  echo "You sent the server a value of 2";
}
?>

AJAX Code :

<html>
<head>
<title>An AJAX Demo</title>
<script language="javaScript">
var XMLHttpRequestObject=false;
if(window.XMLHttpRequest)
{
   XMLHttpRequestObject=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
   XMLHttpRequestObject=new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource,divID,data)
{
   if(XMLHttpRequestObject)
     {
        var obj=document.getElementById(divID);
            XMLHttpRequestObject.open("POST",dataSource);
            XMLHttpRequestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
            XMLHttpRequestObject.onreadystatechange=function()
            {
              if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)
                {
                  obj.innerHTML=XMLHttpRequestObject.responseText;
              }
            }
            XMLHttpRequestObject.send("data="+data);
        }
}
</script>
</head>
<body>
<h2>Sending AJAX data with POST</h2>
<form>
<input type="button" value="Retrieve Message 1" onclick="getData('choose_msg.php','targetDiv',1)">
<input type="button" value="Retrieve Message 2" onclick="getData('choose_msg.php','targetDiv',2)">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>

Before executing the program :


Clicking on "Retrieve Message 1"


Clicking on "Retrieve Message 2"
 

Passing Data to the Server with GET using AJAX

When using the GET method of fetching data from the server, data is sent from Web pages back to the server using URL encoding, which means data is appended to the URL that is read back from the server.

choose_msg.php

<?php
if($_REQUEST{"data"}=="1")          // If a value '1' is sent to the server
{
  echo "You sent the server a value of 1";
}
if($_REQUEST{"data"}=="2")        // If a value '2' is sent to the server
{
  echo "You sent the server a value of 2";
}
?>

AJAX Code :

<html>
<head>
<title>An AJAX DEMO</title>
<script language="javaScript">
var XMLHttpRequestObject=false;
if(window.XMLHttpRequest)
{
   XMLHttpRequestObject=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
   XMLHttpRequestObject=new ActiveXObject("Micosoft.XMLHTTP");
}
function getData(dataSource,divID)
{
   if(XMLHttpRequestObject)
     {
        var obj=document.getElementById(divID);
        XMLHttpRequestObject.open("GET",dataSource);
            XMLHttpRequestObject.onreadystatechange=function()
            {
               if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)
                 {
                    obj.innerHTML=XMLHttpRequestObject.responseText;
         }
            }
        XMLHttpRequestObject.send(null);
  }
}
</script>
</head>
<body>
<h3>Sending AJAX data with GET</h3>
<form>
<input type="button" value="Retrieve Message 1" onclick="getData('choose_msg.php?data=1','targetDiv')">
<input type="button" value="Retrieve Message 2" onclick="getData('choose_msg.php?data=2','targetDiv')">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>

Before executing the program :

 Clicking on "Retrieve Message 1"


Clicking on "Retrieve Message 2"


The 1st button sends value '1' to the server and according the php file prints "You sent the server a value of 1".
Similarly, the 2nd button sends value '2' to the server and accordingly the php file prints the conditional output.

Using AJAX to retrieve message from a php file

This simple program just fetches the contents of a php file, data.php , from the server when you click the button. The difference between this application and a normal web page is that when you click the button the page doesn't blink and redisplay - all that happens is the default text is replaced by a text from a text file which is already stored in the server.

Here is the php code.

<?php
echo "Hello World !!! ";
echo " Welcome to programming in AJAX using PHP ";
?>


The AJAX code :

<html>
<head>
<title>An AJAX DEMO</title>
<script language="javaScript">
var XMLHttpRequestObject=false;
if(window.XMLHttpRequest)
{
   XMLHttpRequestObject=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
   XMLHttpRequestObject=new ActiveXObject("Micosoft.XMLHTTP");
}
function getData(dataSource,divID)
{
   if(XMLHttpRequestObject)
     {
        var obj=document.getElementById(divID);
        XMLHttpRequestObject.open("GET",dataSource);
            XMLHttpRequestObject.onreadystatechange=function()
            {
               if(XMLHttpRequestObject.readyState==4 && XMLHttpRequestObject.status==200)
                 {
                    obj.innerHTML=XMLHttpRequestObject.responseText;
         }
            }
        XMLHttpRequestObject.send(null);
  }
}
</script>
</head>
<body>
<h3>An Ajax Demo</h3>
<form>
<input type="button" value="Retrieve message from txt file" onclick="getData('data.php','targetDiv')">
</form>
<div id="targetDiv">
<p>The retrieved message will appear here</p>
</div>
</body>
</html>


Before clicking the button : 

After clicking the button :

The button is connected to a Javascript function, getData and passes two arguments to that function - "data.php", the name of the file on the server to fetch, and "targetDiv", which is the name of the <div> element to display the downloaded text in.

Delete a record from mysql database using php

This post is about how to delete a record from mysql database using php.

The php code :

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("DELETE FROM fruit WHERE name='CD'");
$result=mysql_query("SELECT * FROM fruit"); 
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"

            </td><td>",$row['quantity'],"</td>";
    echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>  


Before running the program :
NameNumberQuantity
DVD110
PENDRIVE250
CD325
KEYBOARD415

After running the program :
NameNumberQuantity
DVD110
PENDRIVE250
KEYBOARD415
                                     

Sort data in the mysql database using php

This post is about sorting data in the mysql database using php.

The php code :

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("SELECT * FROM fruit ORDER BY name"); 
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"  

    </td><td>",$row['quantity'],"</td>";
    echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>   


Before executing the program :
NameNumberQuantity
DVD110
PENDRIVE250
CD325
KEYBOARD415
          
After executing the program :
NameNumberQuantity
CD325
DVD110
KEYBOARD415
PENDRIVE250
        

Update a record in the mysql database using php

This program is about how to update a record already present in the mysql database using php.

Check out my previous two posts for convenience.

Displaying table of data from mysql database using php
Inserting data into mysql database using php

In SQL, the update command is usually written like this

UPDATE table_name SET col1='new_data' WHERE col2='present data'

Here is the php code for the update process.

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("UPDATE fruit SET quantity='30kg' WHERE name='PINEAPPLE'");
$result=mysql_query("SELECT * FROM fruit"); 
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"

            </td><td>",$row['quantity'],"</td>";
     echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?> 


Output before running the program :
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE420KG
    
Output after running the program :
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE430KG
 

Inserting data into MySql database using php

In my last post, I have discussed about displaying a table from mysql database using php. Click here to read my previous post.

This program is about inserting a new record into the database using php. To insert a new rcord into the databse, the program is kind of similar to the displaying the table but one extra piece of code is needed.

For SQL, we use the "Insert" query to enter a new record into the database. If you don't know the format of the "Insert" query then here it is.

INSERT INTO table_name VALUES("col1","col2",......);

Now, here is the php code.

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("INSERT INTO fruit VALUES('PINEAPPLE','04','20KG')");
$result=mysql_query("SELECT * FROM fruit"); 
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"  
     </td><td>",$row['quantity'],"</td>";
      echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>


Output before running the php file.
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg

Output after running the php file
NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE420KG
   


NOTE : If you keep on refreshing the page it will keep on adding the same row like this .

NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
PINEAPPLE420KG
                

Displaying table from MySql database using php

To display a table using php first we need to create a database using mysql and then we need to create a table inside the database. For this, I have used WAMP server because it is relatively easy to create a database.

If you don't have WAMP Server, you can download it from here.

Now, here are the steps to create a database.

1) Go to your phpMyAdmin page.


2) Click on "Databases". This page will give you the option of creating a new database and it will also show you the existing database in your server.

3) After creating your database, you will be asked to create a table. Create your table with the no. of columns you desire giving them your desired data type which depends on the type of data you are willing to store in the columns fo eg: text,integer and so on.

4) After creating your table, you will need to insert data into the table by using the following sql queries.

INSERT INTO TABLE_NAME VALUES("COL1","COL2",....);



Note : No need to give " " for integer fields. Replace your own table name with "TABLE_NAME".

5) Go on inserting data into table as much as you like.

6) Now you need to write the php file to make a connection with the database and display the table on your web browser.

For this I have used a database name "produce" and table name "fruit" with fields name(text), number(integer) and quantity(text).

Here is the php file for the program.

<?php
$connection=mysql_connect("localhost","root","")
   or die("Couldn't connect to the server");
$db=mysql_select_db("produce",$connection)
   or die ("Couldn't select database");
$result=mysql_query("SELECT * FROM fruit");
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th><th>Number</th><th>Quantity</th>";
echo "</tr>";
while($row=mysql_fetch_array($result))
{
     echo "<tr>";
     echo "<td>",$row['name'],"</td><td>",$row['number'],"
             </td><td>",$row['quantity'],"</td>";
     echo "</tr>";
}
echo "</table>";
mysql_close($connection);
?>   

Note : The default username for WAMP Server is "root" and no default password is given so I have used " " as password while making connection with the database.       
    
Here is the output of the php file.

NameNumberQuantity
APPLE15KG
MANGO210KG
Orange315kg
     

Using imagesetbrush in php

<?php
$pic = imagecreatetruecolor(400,400);
$redcol = 0;
for ($i = -20;$i<450; $i=$i+90) 
{
    for ($j=-20; $j<450;$j=$j+80) 
    {
        $brush = imagecreate(100,100);
        $brushtrans = imagecolorallocate($brush, 0, 0, 0);
        imagecolortransparent($brush, $brushtrans);
        for ($k = 1;$k<18;++$k)
        {
            $color = imagecolorallocate($brush,255,$k * 15,$redcol);
            imagefilledellipse($brush,$k*2,$k*2,1,1,$color);
        }

        imagesetbrush($pic,$brush);
        imageellipse($pic,$i,$j,50,50,IMG_COLOR_BRUSHED);
        imagedestroy($brush);
    }
    $redcol=$redcol+40;
}
imagepng($pic);
imagedestroy($pic);
?>

Output :



Image merge in php

<?php
$php=imagecreatefrompng("php.png");
$php2=imagecreatefrompng("php2.png");
imagecopymerge($php,$php2,0,0,0,0,256,256,60);
header('Content-type:image/png');
imagepng($php);
imagedestroy($php);
imagedestroy($php2);
?>

Image 1:


Image 2 :


Output :



Text Output using PHP

<?php

$image = imagecreate(400, 30);
$white = imagecolorallocate($image, 255, 255, 255);
$grey = imagecolorallocate($image, 128, 128, 128);
$black = imagecolorallocate($image,50,50,50);
imagefilledrectangle($image, 0, 0, 399, 29, $white);
$text = 'Welcome to my blog ';
$font = 'verdana.ttf';
imagettftext($image, 20, 0, 10, 20, $black, $font, $text);
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);

?> 

Output : Welcome to my blog 

Note : Include the 'verdana' font file in the same directory as that of the PHP script otherwise the script will not run.

HTML Form using PHP

To create a HTML form using php create a file with name "form.php" and paste the following code in it :

<html>
<body>
<form action="print.php" method="get">
Name:<input type="text" name="Name" value"Jim"/><br />
Password:<input type="password" name="Password" maxlength="10"/><br />
Age: <select name="Age">
<option value="15-25">15-25</option>
<option value="25-30">25-30</option>
<option value="30-40">30-40</option>
<option value="40-55">40-55</option>
</select><br /><br />
Favourite Activities :<br />
<textarea name="Story" rows="15" cols=50">
Enter your favourite activities here...</textarea><br /><br />
What is your favorite sport ?<br />
<input type="radio" name="Favesport" value="Cricket"/>Cricket
<input type="radio" name="Favesport" value="Football"/>Football
<input type="radio" name="Favesport" value="Tennis"/>Tennis
<input type="radio" name="Favesport" value="Baseball"/>Baseball
<input type="radio" name="Favesport" value="Basketball"/>Basketball
<br /><br />
What is your favourite programming language ?<br />
<input type="radio" name="Languages" value="Java"/>Java
<input type="radio" name="Languages" value="PHP"/>PHP
<input type="radio" name="Languages" value="HTML"/>HTML
<input type="radio" name="Languages" value="Python"/>Python
<input type="radio" name="Languages" value="C++"/>C++
<br /><br />
Enter your profession :<br />
<textarea name="Profession" rows="2" cols=30">
Enter your profession..</textarea><br /><br />
Enter your mail-id :<br />
<textarea name="mail" rows="2" cols=30">
</textarea><br /><br />
<br /><br />
<input type="submit" />
</form>
</body>
</html>




Create a file "print.php" and paste the following code in it :

<?php
print "Name : {$_GET['Name']}<br /><br />";
print "Password : {$_GET['Password']}<br /><br />";
print "Age : {$_GET['Age']}<br /><br />";
print "Activities : {$_GET['Story']}<br /><br />";
print "Favorite Sport : {$_GET['Favesport']}<br /><br />";
print "Favorite Programming Language : {$_GET['Languages']}<br /><br />";
print "Profession : {$_GET['Profession']}<br /><br />";
print "E-mail ID  : {$_GET['mail']}<br /><br />";
?>  

The data entered in the form will be printed through "print.php" where the data inputs are generated using "$_GET".


Top