PDA

Click to See Complete Forum and Search --> : Upload using AJAX


bharanidharanit
Apr 20th, 2010, 09:32 PM
Hi,
I want my image to be uploaded using AJAX,
When the page loads, my imageupload form(initially it is hidden) is shown on button click,
When i upload the image it invokes AJAX.
I used <input type="button"> and the imageupload form is visible after invoking AJAX.
But i want to upload image using $_FILES array. So i need to use this <input type="submit">
But after when i submit the form the page is again reloading and so imageupload form is again hided.
This is my coding
AJAX
var http = getHTTPObject(); // We create the HTTP Object
var url = "friends_classes/upload_avatar_class.php?id=";

function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}

function update_avatar() {
if (http.readyState == 4){
if(http.status==200) {
var results=http.responseText;
document.getElementById('upload_avatar_result').innerHTML = results;
}
}
}

function change_avatar() {
var sId = document.getElementById("friends_user_avatar").value;
http.open("POST", url + escape(sId), true);
http.onreadystatechange = update_avatar;
http.send(null);
}
PHP
<?PHP
$image=$_FILES['friends_user_avatar']['name'];
$upload_avatar=new Upload_avatar($_GET['id'],$image);
class Upload_avatar{
function Upload_avatar($id,$image){
echo $id;
echo $image;
}
}
?>

squared
Sep 14th, 2010, 05:59 PM
Apparently jQuery might be able to do it (from here (http://solutoire.com/2007/09/10/submitting-forms-asynchronously-using-mootools/)):
$('submit').addEvent( 'click', function(evt){
// Stops the submission of the form.
new Event(evt).stop();

// Sends the form to the action path,
// which is 'script.php'
$('myForm').send();
} );
I'll take a look at the jQuery code.