JavaTechie

Its all about Technology

Using POST method in XMLHTTPRequest(Ajax) December 12, 2007

Filed under: Uncategorized — javatechie @ 11:26 am
Tags:

Requirements

Create a XMLHTTPRequest Object that uses the POST method.

var http = new XMLHttpRequest();

Using GET method

Now we open a connection using the GET method.

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET“, url+”?”+params, true);
http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(null);

I really hope that this much is clear for you

POST method

We are going to make some modifications so POST method will be used when sending the request…

var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST“, url, true);

//Send the proper header information along with the request
http.setRequestHeader(”Content-type”, “application/x-www-form-urlencoded”);
http.setRequestHeader(”Content-length”, params.length);
http.setRequestHeader(”Connection”, “close”);

http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}
http.send(params);

The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument – in the GET method, we send the parameters along with the url separated by a ‘?’ character…

http.open("GET",url+”?”+params, true);

But in the POST method we will use just the url as the second argument. We will send the parameters later.

http.open("POST", url, true);

Some http headers must be set along with any POST request. So we set them in these lines…

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {
//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);}}

We set a handler for the ‘ready state’ change event. This is the same handler we used for the GET method. You can use the http.responseText here – insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

 

Count Number of lines using php December 12, 2007

Filed under: Uncategorized — javatechie @ 11:26 am
Tags:

$file = “somefile.txt”;

$lines = count(file($file));

echo “There are $lines lines in $file”;

?>

_uacct = “UA-2915044-4″;
urchinTracker();

 

Creating simple PHP contact form December 12, 2007

Filed under: Uncategorized — javatechie @ 11:25 am
Tags:

############### Code

<table width="400" border="0" align="center" cellpadding="3" cellspacing="1">
<tr>
<td><strong>Contact Form </strong></td>
</tr>
</table>

<table width="400" border="0" align="center" cellpadding="0" cellspacing="1">
<tr>
<td><form name="form1" method="post" action="send_contact.php">
<table width="100%" border="0" cellspacing="1" cellpadding="3">
<tr>
<td width="16%">Subject</td>
<td width="2%">:</td>
<td width="82%"><input name="subject" type="text" id="subject" size="50"></td>
</tr>
<tr>
<td>Detail</td>
<td>:</td>
<td><textarea name="detail" cols="50" rows="4" id="detail"></textarea></td>
</tr>
<tr>
<td>Name</td>
<td>:</td>
<td><input name="name" type="text" id="name" size="50"></td>
</tr>
<tr>
<td>Email</td>
<td>:</td>
<td><input name="customer_mail" type="text" id="customer_mail" size="50"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Submit"> <input type="reset" name="Submit2" value="Reset"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>

############### Code

<?php
// Contact subject
$subject =”$subject”;
// Details
$message=”$detail”;

// Mail of sender
$mail_from=”$customer_mail”;
// From
$header=”from: $name ”;

// Enter your email address
$to =’someone@somewhere.com’;

$send_contact=mail($to,$subject,$message,$header);

// Check, if message sent to your email
// display message “We’ve recived your information”

if($send_contact){
echo “We’ve recived your contact information”;
}
else {
echo “ERROR”;
}
?>

_uacct = “UA-2915044-4″;
urchinTracker();

 

Get the width and height of an image using a function in PHP December 12, 2007

Filed under: Uncategorized — javatechie @ 11:24 am
Tags:

############### Code
This is a sample code, change image_name to your image name and test it!

list($width, $height, $type, $attr) = getimagesize(”image_name.jpg“);

echo “Image width ” .$width;
echo “
”;
echo “Image height ” .$height;
echo “
”;
echo “Image type ” .$type;
echo “
”;
echo “Attribute ” .$attr;

?>

When you run this script you will see the result like this

Image width 379
Image height 344
Image type 2
Image attribute width=”379″ height=”344″

You will get the width, height, type of an image and also attribute of an image, I use this function in my image upload form.

 

File upload using Java December 12, 2007

Filed under: Uncategorized — javatechie @ 11:24 am
Tags:

Checking If an HTTP Request is Encoded in Multipart Format

Now that you have installed the Apache Jakarta Commons FileUpload library, you can start writing the code. First, we have to make sure the HTTP request is encoded in multipart format. This can be done using the static method isMultipartContent() of the ServletFileUpload class of the org.apache.commons.fileupload.servlet package:

if (ServletFileUpload.isMultipartContent(request)){
// Parse the HTTP request…
}

In the above Java code snippet, request is a javax.servlet.http.HttpServletRequest object that encapsulates the HTTP request. It should be very familiar to you if you know Java Servlet or JSP.

Parsing Form Data with Java Servlet / JSP

Second, we will parse the form data contained in the HTTP request. Parsing the form data is very straightforward with the Apache Jakarta Commons FileUpload library:

ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
List fileItemsList = servletFileUpload.parseRequest(request);

(In the above Java code snippet, DiskFileItemFactory is a class contained in the org.apache.commons.fileupload.disk package and List is an interface contained in the java.util package.)

If everything works fine, fileItemsList will contain a list of file items that are instances of FileItem of the org.apache.commons.fileupload package. A file item may contain an uploaded file or a simple name-value pair of a form field. (More details about FileItem will be provided later.)

By default, the ServletFileUpload instance created by the above Java code uses the following values when parsing the HTTP request:

  • Size threshold = 10,240 bytes. If the size of a file item is smaller than the size threshold, it will be stored in the memory. Otherwise it will be stored in a temporary file on disk.
  • Maximum HTTP request body size = -1, which means the server will accept HTTP request bodies of any size.
  • Repository = System default temp directory, whose value can be found by the Java code System.getProperty(”java.io.tmpdir”). Temporary files will be stored there.

If you do not like the default settings, you can change them using the methods setSizeThreshold() and setRespository() of the DiskFileItemFactory class and the setSizeMax() method of the ServletFileUpload class, like this:

DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setSizeThreshold(40960); /* the unit is bytes */

File repositoryPath = new File(”/temp”);
diskFileItemFactory.setRepository(repositoryPath);

ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(81920); /* the unit is bytes */

(In the above Java code snippet, File is a class of the java.io package.)

If the size of the HTTP request body exceeds the maximum you set, the SizeLimitExceededException exception (fully qualified name: org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException) will be thrown when you call the parseRequest() method:

try {
List fileItemsList = servletFileUpload.parseRequest(request);
/* Process file items… */
}
catch (SizeLimitExceededException ex) {
/* The size of the HTTP request body exceeds the limit */
}

Iterating through File Items

Third, we will iterate through the file items and process each of them. The isFormField() method of the FileItem interface is used to determine whether a file item contains a simple name-value pair of a form field or an uploaded file:

Iterator it = fileItemsList.iterator();
while (it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if (fileItem.isFormField()){
/* The file item contains a simple name-value pair of a form field */
}
else{
/* The file item contains an uploaded file */
}
}

(In the above Java code snippet, Iterator is an interface in the java.util package and FileItem is an interface in the org.apache.commons.fileupload package.)

Retrieving Values of Ordinary Form Fields with Java Servlet / JSP

If a file item contains a simple name-value pair of an ordinary form field, we can retrieve its name and value using the getFieldName() method and the getString() method respectively:

String name = fileItem.getFieldName();
String value = fileItem.getString();

For example, suppose there is a text field in an HTML/XHTML form:

Getting Information about the Uploaded File with Java Servlet / JSP

If a file item contains an uploaded file, we can use a number of methods to obtain some information about the uploaded file before we decide what to do with it:

/* Get the name attribute value of the element. */
String fieldName = fileItem.getFieldName();

/* Get the size of the uploaded file in bytes. */
long fileSize = fileItem.getSize();

String fileName = fileItem.getName();

String contentType = fileItem.getContentType();

Saving Uploaded Files in the File System with Java Servlet / JSP

In some situations, you just want to store the uploaded file in the file system without concerning what the uploaded file contains. The FileItem interface provides a method called write() that helps us perform this easily:

File saveTo = new File(”/upload_files/myFile.txt”);
fileItem.write(saveTo);

Processing Contents of Uploaded Files with Java Servlet / JSP

f you do not want to save the uploaded file directly but to process it, the get() and getInputStream() methods can help you. The get() method returns the uploaded file as an array of the byte data type:

byte[] fileData = fileItem.get();

However, if the uploaded file is large in size, you will not want to load the whole file into memory. The getInputStream() method can help you in this case. It returns the uploaded file as a stream:

InputStream fileStream = fileItem.getInputStream();

(InputStream is a class of the java.io package.)

 

Multiple File upload with PHP December 12, 2007

Filed under: Uncategorized — javatechie @ 11:23 am
Tags:

############### Code
<table width="500″ border="0″ align="center" cellpadding="0″ cellspacing="1″ bgcolor="#CCCCCC">
<tr>
<form action="multiple_upload_ac.php" method="post" enctype="multipart/form-data" name="form1″ id="form1″>
<td>
<table width="100%" border="0″ cellpadding="3″ cellspacing="1″ bgcolor="#FFFFFF">
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50″ /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50″ /></td>
</tr>
<tr>
<td>Select file
<input name="ufile[]" type="file" id="ufile[]" size="50″ /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

############### Code

<?php
//set where you want to store files
//in this example we keep file in folder upload
//$HTTP_POST_FILES[’ufile’][’name’]; = upload file name
//for example upload file name cartoon.gif . $path will be upload/cartoon.gif

$path1= “upload/”.$HTTP_POST_FILES[’ufile’][’name’][0];
$path2= “upload/”.$HTTP_POST_FILES[’ufile’][’name’][1];
$path3= “upload/”.$HTTP_POST_FILES[’ufile’][’name’][2];

//copy file to where you want to store file
copy($HTTP_POST_FILES[’ufile’][’tmp_name’][0], $path1);
copy($HTTP_POST_FILES[’ufile’][’tmp_name’][1], $path2);
copy($HTTP_POST_FILES[’ufile’][’tmp_name’][2], $path3);

//$HTTP_POST_FILES[’ufile’][’name’] = file name
//$HTTP_POST_FILES[’ufile’][’size’] = file size
//$HTTP_POST_FILES[’ufile’][’type’] = type of file

echo “File Name :”.$HTTP_POST_FILES[’ufile’][’name’][0].”
”;
echo “File Size :”.$HTTP_POST_FILES[’ufile’][’size’][0].”
”;
echo “File Type :”.$HTTP_POST_FILES[’ufile’][’type’][0].”
”;
echo “”;
echo “

”;

echo “File Name :”.$HTTP_POST_FILES[’ufile’][’name’][1].”
”;
echo “File Size :”.$HTTP_POST_FILES[’ufile’][’size’][1].”
”;
echo “File Type :”.$HTTP_POST_FILES[’ufile’][’type’][1].”
”;
echo “”;
echo “

”;

echo “File Name :”.$HTTP_POST_FILES[’ufile’][’name’][2].”
”;
echo “File Size :”.$HTTP_POST_FILES[’ufile’][’size’][2].”
”;
echo “File Type :”.$HTTP_POST_FILES[’ufile’][’type’][2].”
”;
echo “”;
?>

 

Image resizing with PHP December 12, 2007

Filed under: Uncategorized — javatechie @ 11:23 am
Tags:

function imageResize($width, $height, $target) {

//takes the larger size of the width and height and applies the
formula accordingly…this is so this script will work
dynamically with any size image

if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}

//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);

//returns the new sizes in html image tag format…this is so you
can plug this function inside an image tag and just get the

return “width=\”$width\” height=\”$height\””;

}

?>

The Function in Action

//get the image size of the picture and load it into an array
$mysock = getimagesize(”images/sock001.jpg”);

?>

<!—using a standard html image tag, where you would have the
width and height, insert your new imageResize() function with
the correct attributes –>

<img src=”images/sock001.jpg” >

 

Single file upload in php December 12, 2007

Filed under: Uncategorized — javatechie @ 11:22 am
Tags:

############### Code

<table width=”500″ border=”0″ align=”center” cellpadding=”0″ cellspacing=”1″ bgcolor=”#CCCCCC”>
<tr>
<form action=”upload.php” method=”post” enctype=”multipart/form-data” name=”form1″ id=”form1″>
<td>
<table width=”100%” border=”0″ cellpadding=”3″ cellspacing=”1″ bgcolor=”#FFFFFF”>
<tr>
<td><strong>Single File Upload </strong></td>
</tr>
<tr>
<td>Select file
<input name=”ufile” type=”file” id=”ufile” size=”50″ /></td>
</tr>
<tr>
<td align=”center”><input type=”submit” name=”Submit” value=”Upload” /></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

###############upload.php

”;

//$HTTP_POST_FILES[’ufile’][’name’] = file name
//$HTTP_POST_FILES[’ufile’][’size’] = file size
//$HTTP_POST_FILES[’ufile’][’type’] = type of file
echo “File Name :”.$HTTP_POST_FILES[’ufile’][’name’].”
”;
echo “File Size :”.$HTTP_POST_FILES[’ufile’][’size’].”
”;
echo “File Type :”.$HTTP_POST_FILES[’ufile’][’type’].”
”;
echo “”;
}
else
{
echo “Error”;
}
}
?>

 

Nickname validation javascript December 12, 2007

Filed under: Uncategorized — javatechie @ 11:21 am
Tags:

function Check(form)
{
value=form.nickname.value

var valid=/^[0-9a-zA-Z_]*$/;

if(value!=””&& !valid.test(value))
{
form.nickname.style.background = “#FFCCCC”;
alert(” field must contain only alphabets,numbers and underscore.\n”);
return false;
}
return true;
}

 

Limit Displayed Characters From Your Text December 12, 2007

Filed under: Uncategorized — javatechie @ 11:20 am
Tags:

############### Code

$position=14; // Define how many characters you want to display.

$message=”You are now joining over 2000 current”;
$post = substr($message,$position,1); // Find what is the last character displaying. We find it by getting only last one character from your display message.

if($post !=” “){ // In this step, if last character is not ” “(space) do this step .

// Find until we found that last character is ” “(space)
// by $position+1 (14+1=15, 15+1=16 until we found ” “(space) that mean character 20)
while($post !=” “){
$i=1;
$position=$position+$i;

$message=”You are now joining over 2000 current”;
$post = substr($message,$position,1);
}

}

$post = substr($message,0,$position); // Display your message
echo $post;
echo “…”;
?>