0

I need to upload files via my form but I don't know how to incorporate a file upload into my form for posting blog entries. I don't know how to perform ajax with JQuery. I don't know how to send the image file/data via the ajax request, any help would be appreciated.

This is what've got atm:

CP.PHP

<?php
    include("../scripts/database_connx.php");
    include("../scripts/functions.php");
    start_secure_session();
    if(logged_in($sqli_con) === false) {
        header("Location: ../index.php");
        exit();
    }
    $cp = true;
?>
<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>TridantDesigns | Admin</title>
        <link rel="stylesheet" type="text/css" href="../style/reset.css" />
        <link rel="stylesheet" type="text/css" href="../style/main.css" />
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script>
            $(document).ready(function() {
                setInterval(function() {
                    if(window.XMLHttpRequest) {
                        get_entries = new XMLHttpRequest();
                    } else {
                        get_entries = new ActiveXObject("Microsoft.XMLHTTP");
                    }

                    get_entries.onreadystatechange = function() {
                        if(get_entries.readyState == 4 && get_entries.status == 200) {
                            document.getElementById("r_e").innerHTML = get_entries.responseText;
                        }
                    }

                    get_entries.open("GET", "get_entries.php", true);
                    get_entries.send();
                }, 50000);
            });
        </script>
    </head>
    <body>
        <?php include("../scripts/includes/header.inc.php"); ?>
        <div id="site_content">
            <div id="new_entry">
                <form>
                    <h1>Add A New Blog Entry</h1>
                    <input type="text" name="entry_title" maxlength="40" placeholder="Entry Title(40 Char)" /><br />
                    <textarea name="entry_contents" placeholder="Entry Content" /></textarea><br />
                    <label for="image">Choose Image File:</label>
                    &nbsp;<input type="file" name="image" /><br />
                    <input type="button" value="Post Entry" onclick="post_entry(this.form, this.form.entry_title, this.form.entry_contents, this.form.image);" />
                </form>
                <div id="post_error">

                </div>
            </div>

            <div id="remove_entry">
                <h1>Remove Entries(Click to remove)</h1>
                <div id="r_e">
                    <?php
                        get_entries($sqli_con);
                    ?>
                </div>
            </div>
        </div>

        <script>
            function post_entry(form, title, contents, image) {
                document.getElementById("post_error").style.display = "block";
                if(title.value.length < 1) {
                    document.getElementById("post_error").innerHTML = "Please enter an entry title!";
                    return;
                }
                if(title.value.length > 40) {
                    document.getElementById("post_error").innerHTML = "Title can not be longer than 40 characters!";
                    return;
                }
                if(contents.value.length < 1) {
                    document.getElementById("post_error").innerHTML = "Please enter some content!";
                    return;
                }

                if(window.XMLHttpRequest) {
                    post_entry_ = new XMLHttpRequest();
                } else {
                    post_entry_ = new ActiveXObject("Microsoft.XMLHTTP");
                }

                post_entry_.onreadystatechange = function() {
                    if(post_entry_.readyState == 4 && post_entry_.status == 200) {
                        document.getElementById("post_error").innerHTML = post_entry_.responseText;
                        if(post_entry_.responseText == "<response>Entry Added</response>") {
                            //get_entries();
                        }
                    }
                }

                post_entry_.open("POST", "add_entry.php", true);
                post_entry_.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                post_entry_.send("title="+title.value+"&contents="+contents.value+"&image="+image.value);

            }

            function remove_entry() {

            }
        </script>
        <?php include("../scripts/includes/footer.inc.php"); ?>
    </body>
</html>

Add_Entry.PHP

<?php
    include("../scripts/database_connx.php");
    include("../scripts/functions.php");
    start_secure_session();

    if(logged_in($sqli_con) === false) {
        header("Location: ../index.php");
        exit();
    }

    $title = mysqli_escape_string($sqli_con, strip_tags($_POST['title']));
    $contents = mysqli_escape_string($sqli_con, strip_tags($_POST['contents']));
    $image = mysqli_escape_string($sqli_con, strip_tags($_POST['image']));
    $poster = mysqli_escape_string($sqli_con, strip_tags($_SESSION['tridantblog_username']));

    echo var_dump($image);

    if($image == "") {
        if($stmt = $sqli_con->prepare("INSERT INTO entries (title, contents, poster) VALUES (?, ?, ?)")) {
            $stmt->bind_param("sss", $title, $contents, $poster);
            $stmt->execute();
            $stmt->store_result();
            $stmt->fetch();
            if($stmt->rows_affected > 0) {
                $stmt->close();
                echo "<response>Added to database!</response>";
            } else {
                $stmt->close();
                echo "<response>Could not add entry to the database!</response>";
            }
        }
    } else {

        #Check and upload images here!

        if($stmt = $sqli_con->prepare("INSERT INTO entries (title, contents, image, poster) VALUES (?, ?, ?, ?)")) {
            $stmt->bind_param("sss", $title, $contents, $poster);
            $stmt->execute();
            $stmt->store_result();
            if($stmt->rows_affected > 0) {
                $stmt->close();
                echo "<response>Added to database!</response>";
            } else {
                $stmt->close();
                echo "<response>Could not add entry to the database!</response>";
            }
        }
    }
?>
Musa
  • 96,336
  • 17
  • 118
  • 137
Liam Potter
  • 1,732
  • 8
  • 24
  • 47
  • You should take a look at this post:http://stackoverflow.com/questions/2320069/jquery-ajax-file-upload . It's not that recent, but most of it still applies, I believe. You'll probably need an external plugin which uses an iframe or a flash file. – Kippie Feb 05 '13 at 07:54
  • @MCL and how would the `jQuery.ajax()` method help in uploading files to the server asynchronously? – Darin Dimitrov Feb 05 '13 at 08:01
  • @DarinDimitrov I asked my question before the question was done being edited. Now that I see the code, it's a whole other story. – MCL Feb 05 '13 at 08:04
  • I wouldn't really say that it's a whole other story. The `jQuery.ajax` method doesn't support uploading files. The fact that the OP is not using jQuery doesn't change this fact at all. So even if he had used jQuery that wouldn't have helped him very much. – Darin Dimitrov Feb 05 '13 at 08:05
  • I wasn't suggesting that jQuery could provide a solution. I merely refered Liam Potter to the jQuery docs, since he didn't know "how to perform ajax with JQuery". Also I wasn't sure where the files' original location was, JSON-P data for example can be retrieved and posted back somewhere else very well. His code clarified that. – MCL Feb 05 '13 at 08:13

1 Answers1

2

Uploading files with AJAX is not supported using the old XmlHttpRequest object. Possible workarounds include using file upload controls such as Uploadify, Fine Uploader or the jQuery form plugin which supports uploading files. Also modern browsers that support the HTML 5 File API and the XmlHttpRequest2 object would allow you to achieve that natively. Take a look at the following article which illustrates how this could be achieved.

For example let's suppose that you have the following HTML form:

<form action="upload.cgi" method="post" enctype="multipart/form-data" onsubmit="return upload(this);">
    <input type="file" name="file" />
    <button type="submit">Upload file to the server</button>
</form>

you could have a script that will perform the upload using AJAX:

function upload(formElement) {
    var xhr = new XMLHttpRequest();
    xhr.open(formElement.method, formElement.action);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // Handle response.
            alert(xhr.responseText); // handle response.
        }
    };
    xhr.send(new FormData(formElement));
    return false;
}

You might also take a look at the following article about HTML5 forms.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • `Uploading files with AJAX is not supported` by what – Musa Feb 05 '13 at 07:59
  • @Musa, I have updated my answer to be more precise: `Uploading files with AJAX is not supported using the old XmlHttpRequest object`. I have also illustrated an example of how this could be achieved with the new XHR2 object that is built into modern browsers. – Darin Dimitrov Feb 05 '13 at 08:01