Search code examples
jqueryimagepostbackavatar

how can pass an image location to a php function using jquery's call back function?


<div class="hideAfterSuccess">
                    <label for="avatar">Upload an Avatar :</label>
                    <input type="file" name="avatar" id="avatar" />
                </div>

and below is the jquery that has to pass image location to a php function in another file (parsePortal.php). am able to pass other kinds of data o the file but the image failed. i thought since it posts the location string of the image, i would be able to use $_FILES[$_POST['image']]['name'] and then upload the image. i have tried the web, surely, didn't find what i needed.

        $(function(){
           var imageLoc = $('avatar').val();
           var url = "parsePortal.php";
                $.post(url, {
                    status : "getimage",
                    image : "imageLoc"
                }, function(result){

                 });
            });

Solution

  • i successfully did it using the jquery forms plugin. this means it sent the whole path from which i got the the file name and printed it out. THANKS TO YOU VIC, there is no way i c'd have done this without this kind of help.

    here is the javascript.

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
    <script src="http://malsup.github.com/jquery.form.js"></script> 
    
    <script> 
            // prepare the form when the DOM is ready 
            $(document).ready(function() { 
                // bind form using ajaxForm 
                $('#htmlForm').ajaxForm({ 
                    // target identifies the element(s) to update with the server response 
                    target: '#htmlExampleTarget', 
    
                    // success identifies the function to invoke when the server response 
                    // has been received; here we apply a fade-in effect to the new content 
                    success: function() { 
                        $('#htmlExampleTarget').fadeIn('slow'); 
                    } 
                }); 
            });
    </script> 
    

    and here is the html

    <form id="htmlForm" action="file.php" method="post"> 
    Message: <input type="text" name="message" value="Hello HTML" /> <p></p>
    Image : <input type="file" name="image" id="image" /><p></p>
    <input type="submit" value="Echo as HTML" /> 
    

    and here is the php

    $image =  $_FILES['image']['tmp_name'];
    $name = $_FILES['image']['name'];
    move_uploaded_file($image, "uploads/".$name);
    echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] .  '</div>'; 
    echo '<img src="uploads/'.$name.'"/>';