Jump to content

php, ajax and phpmailer


sayedsohail

Recommended Posts

Hi everyone,

 

I am using php ajax succesfully, now i wish to add ajax functiionality to attachments, here is my php code mail attachment function which works fine.

 

but i am wondering how to incorporate this with ajax. Usually i am calling myajaxrequest("FILENAME.PHP="ID=$id). how do i pass $_FILES['images']['name'] in my ajax function.

 

function uploadFile() {
global $attachments;
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $value;
array_push($attachments, $filename);
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES['images']['tmp_name'][$key], $dir);
}
                                
}
                                            
if ($success) {
echo "<p align='center'>Files Uploaded Successfully</p><BR>";
SendIt();
}
else {
echo "<br></br><hr></hr><br></br><table width='100%' align='center' color='Blue'><tr><td>Sorry the server was unable to upload the files</td></tr>";
echo "<tr align='center'><td>Mailer Error:  . $mail->ErrorInfo</td></tr>";
echo "<tr aling='center'><td><a href='editservice.php'>Back to Email Form</a></td></tr></table>";
exit();}
}  

Link to comment
Share on other sites

Very good question. When passing files via HTTP Requests, there's a whole new animal that crops up. I would highly recommend you use a JS library such as the YUI lib to do this sort of transaction. Take a look at this example to see how easily you can come up with something that uploads files.

 

Hope this helps!

Link to comment
Share on other sites

Erm.. i didn't think AJAX could do $_FILE requests, but only POST & GET!

but i'll have a read as well!

 

That's exactly what AJAX is: it allows you to send an HTTP request via POST or GET (either one, mind you) to a script behind the scenes and return the result to your page. That in mind, anything you can do with a standard form via POST or GET can be done via an AJAX call if your script is handled properly.

Link to comment
Share on other sites

Even i thought it can be done using frames, however, i wish to send the filename to ajax and on backend the receiving file phpupload.php file should upload, i can't see any possibility using ajax.  You know what i mean doing same like googlemail attachments.

 

obsidian seems to know the way for this functionality, we wish if he could direct us using simple ajax request rather than yahoo tools.

Link to comment
Share on other sites

This is what i got but its freezez up.  If this works, than i have to incorporate this in my email.php form.

Hope this could help someone like me and would be able to

 

<?php
$upload_dir = "C:/Program Files/Apache2/mail/uploads"; 
$web_upload_dir = "/mail/uploads"; 
$tf = $upload_dir.'/'.md5(rand()).".test";
$f = @fopen($tf, "w");
if ($f == false) 
    die("Fatal error! {$upload_dir} is not writable. Set 'chmod 777 {$upload_dir}'
        or something like this");
fclose($f);
unlink($tf);
if (isset($_POST['fileframe'])) 
{
    $result = 'ERROR';
    $result_msg = 'No FILE field found';

    if (isset($_FILES['file']))  // file was send from browser
    {
        if ($_FILES['file']['error'] == UPLOAD_ERR_OK)  // no error
        {
            $filename = $_FILES['file']['name']; // file name 
            move_uploaded_file($_FILES['file']['tmp_name'], $upload_dir.'/'.$filename);
            // main action -- move uploaded file to $upload_dir 
            $result = 'OK';
        }
        elseif ($_FILES['file']['error'] == UPLOAD_ERR_INI_SIZE)
            $result_msg = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        else 
            $result_msg = 'Unknown error';

    }
    echo '<html><head><title>-</title></head><body>';
    echo '<script language="JavaScript" type="text/javascript">'."\n";
    echo 'var parDoc = window.parent.document;';
    if ($result == 'OK')
    {
        echo 'parDoc.getElementById("upload_status").value = "file successfully uploaded";';
        echo 'parDoc.getElementById("filename").value = "'.$filename.'";';
        echo 'parDoc.getElementById("filenamei").value = "'.$filename.'";';
        echo 'parDoc.getElementById("upload_button").disabled = false;';
    }
    else
    {
        echo 'parDoc.getElementById("upload_status").value = "ERROR: '.$result_msg.'";';
    }

    echo "\n".'</script></body></html>';

    exit(); // do not go futher 
}
// FILEFRAME section END

function safehtml($s)
{
    $s=str_replace("&", "&", $s);
    $s=str_replace("<", "<", $s);
    $s=str_replace(">", ">", $s);
    $s=str_replace("'", "'", $s);
    $s=str_replace("\"", """, $s);
    return $s;
}

if (isset($_POST['description']))
{
    $filename = $_POST['filename'];
    $size = filesize($upload_dir.'/'.$filename);
    $date = date('r', filemtime($upload_dir.'/'.$filename));
    $description = safehtml($_POST['description']);

    // Let's generate file information page
$html =<<<END
<html><head><title>{$filename} [uploaded by IFRAME Async file uploader]</title></head>
<body>
<h1>{$filename}</h1>
<p>This is a file information page for your uploaded file. Bookmark it, or send to anyone...</p>
<p>Date: {$date}</p>
<p>Size: {$size} bytes</p>
<p>Description: 
<pre>{$description}</pre>
</p>
<p><a href="{$web_upload_dir}/{$filename}" style="font-size: large;">download file</a><br>
<a href="{$PHP_SELF}" style="font-size: small;">back to file uploading</a><br>
<a href="{$web_upload_dir}/upload-log.html" style="font-size: small;">upload-log</a></p>
<br><br>Example by <a href="http://www.anyexample.com/">AnyExample</a>
</body></html>
END;
    // save HTML 
    $f = fopen($upload_dir.'/'.$filename.'-desc.html', "w");
    fwrite($f, $html);
    fclose($f);
    $msg = "File {$filename} uploaded, 
           <a href='{$web_upload_dir}/{$filename}-desc.html'>see file information page</a>";

    // Save to file upload-log 
    $f = fopen($upload_dir."/upload-log.html", "a");
    fwrite($f, "<p>$msg</p>\n");
    fclose($f);

    // setting result message to cookie  
    setcookie('msg', $msg); 
    // redirecting to the script main page 
    // we're doing so, to avoid POST form reposting  
    // this method of outputting messages is called 'flash' in Ruby on Rails  
    header("Location: http://".$_SERVER['HTTP_HOST'].$PHP_SELF); 
    exit(); 
    // redirect was send, so we're exiting now
} 

// retrieving message from cookie 
if (isset($_COOKIE['msg']) && $_COOKIE['msg'] != '')  
{  
    if (get_magic_quotes_gpc()) 
        $msg = stripslashes($_COOKIE['msg']); 
    else
        $msg = $_COOKIE['msg'];
    setcookie('msg', ''); 
} 
?>
<!-- Beginning of main page -->
<html><head>
<title>IFRAME Async file uploader example</title>
</head>
<body>
<?php 
if (isset($msg)) // this is special section for outputing message 
    echo '<p style="font-weight: bold;">'.$msg.'</p>';
?> 
<h1>Upload file:</h1>
<p>File will begin to upload just after selection. </p>
<p>You may write file description, while you file is being uploaded.</p>

<form action="<?=$PHP_SELF?>" target="upload_iframe" method="post" enctype="multipart/form-data">
<input type="hidden" name="fileframe" value="true">
<label for="file">text file uploader:</label><br>
<!-- JavaScript is called by OnChange attribute -->
<input type="file" name="file" id="file" onChange="jsUpload(this)">
</form>
<script type="text/javascript">
/* This function is called when user selects file in file dialog */
function jsUpload(upload_field)
{
    var re_text = /\.txt|\.pdf|\.gif/i;
    var filename = upload_field.value;
    if (filename.search(re_text) == -1)
    {
        alert("File does not have text(txt, pdf, gif) extension");
        upload_field.form.reset();
        return false;
    }

    upload_field.form.submit();
    document.getElementById('upload_status').value = "uploading file...";
    upload_field.disabled = true;
    return true;
}
</script>
<iframe name="upload_iframe" style="width: 400px; height: 100px; display: none;">
</iframe>
<!-- For debugging purposes, it's often useful to remove
     "display: none" from style="" attribute -->

<br>
Upload status:<br>
<input type="text" name="upload_status" id="upload_status" 
       value="not uploaded" size="64" disabled>
<br><br>

File name:<br>
<input type="text" name="filenamei" id="filenamei" value="none" disabled>

<form action="<?=$PHP_SELF?>" method="POST">
<!-- one field is "disabled" for displaying-only. Other, hidden one is for 
    sending data -->
<input type="hidden" name="filename" id="filename">
<br><br>

<label for="photo">File description:</label><br>
<textarea rows="5" cols="50" name="description"></textarea>

<br><br>
<input type="submit" id="upload_button" value="save file" disabled>
</form>
<br><br>
<a href="<?=$web_upload_dir?>/upload-log.html">upload-log</a>
<br><br><br>

Example by <a href="http://www.anyexample.com/">AnyExample</a>
</body>
</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.