0

I have an HTML form that takes input and then it is sent as JSON using a ajax script. Within this form is another form to upload images to the webserver using PHP and another JS script. The problem I am having is when I hit the 'Upload File' button it uses the function for the JSON post, but doesn't use the PHP/JS to upload the image to the webserver.

I tried to combine the two form enctypes into one, but that didn't seem to work. It hits the first form and doesn't continue to the next it seems. Is there a way to combine this? or is it as simple as syntax errors.

HTML forms:

                <div id="createModal" class="modal fade" role ="dialog">
                    <div class="modal-dialog modal-lg">
                        <!--Modal content-->
                        <div class="modal-content">
                            <div class="modal-header" style="text-align: center">
                                <button type="button" class="close" data-dismiss="modal">&times;</button>
                                <h4 class="modal-title">Create New Listing</h4>
                            </div>
                            <div class="modal-body">
                                <div style="text-align: left">

                                    <form enctype='application/json' style="text-align: center" method="post" name="form" id="form" onsubmit="submitForms()">
                                        <input name="seller" value="" type="text" class="form-control" placeholder="First and Last Name"> &nbsp
                                        <input name="email" value="" type="text" class="form-control" placeholder="Email"> &nbsp
                                        <select name="category" value="" class="form-control">
                                            <option selected disabled value="choose">--Category--</option>
                                            <option value="furniture">Furniture</option>
                                            <option value="books">Books</option>
                                            <option value="music">Music</option>
                                        </select> &nbsp
                                        <input name="item" value="" type="text" class="form-control" placeholder="Item Name"> &nbsp
                                        <input name="itemdesc" value="" type="text" class="form-control" placeholder="Item Description"> &nbsp
                                        <input name="model" value="" type="text" class="form-control" placeholder="Model"> &nbsp
                                        <input name="price" value="" type="text" class="form-control" placeholder="Price ($00.00)"> &nbsp
                                    </form>


                                    <h2> Image Upload </h2>
                                    <form enctype='multipart/form-data' action='' method='POST' name="uploadForm" id="uploadForm" onsubmit="submitForms()">
                                        Only JPEG, PNG, JPG types allowed. Image size should be less than 100KB.
                                        <br/><br/>
                                        <div id="filediv"><input name="file[]" type="file" id="file"/></div>
                                        <br/><br/>
                                        <input type="button" id="add_more" class="upload" value="Add More Files"/>
                                        <!--<input type="submit" value="Upload File" name="upload_submit" id="upload_submit" class="upload"/>-->

                                        <!--- Including PHP Script -->
                                        <?php include 'upload.php'; ?>


                                        <div class="modal-footer">
                                            <input type="submit" class="btn btn-default" value='Submit'/>
                                        </div>
                                    </form>

                                    <script>

                                    var success = ("The forms were submitted");

                                    function submitForms()
                                    {

                                        document.getElementById("form").submit();
                                        document.getElementById("uploadForm").submit();

                                        console.log(success);
                                        alert(success);
                                    }

                                    </script>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <script src="js/script.js"></script>
                <script src="js/json.js"></script>

JSON Ajax:

var form = document.forms['form'];

form.onsubmit = function (e) {
    //stop regular form submission
    e.preventDefault();

    //collect the form data 
    var data = {};
    for (var i = 0, ii = form.length; i <ii; ++i) {
        var input = form[i];
        if (input.name) {
            data[input.name] = input.value;
        }
    }

    //console.log(JSON.stringify(data));
    //construct an HTTP request
    var url = [removed]

        $.ajax({
                url: url,
                type: 'POST',
                crossDomain: true,
                data: JSON.stringify(data),
                dataType: 'json',
                contentType: "application/json",
                success: function (response) {
                    var resp = JSON.parse(response)
                    alert(resp.status);
                },
                error: function (xhr, status) {
                    alert("error");
                }
        });
        //console.log(JSON.stringify(data))
        //console.log(url);

};

Upload PHP:

<?php
if (isset($_POST['upload_submit'])) {
    $j = 0;         // Variable for indexing uploaded image
    $target_path = "/tmp/uploads";  // Declaring path for uploaded images.
    for ( $i = 0; $i < count($_FILES['file']['name']); $i++) {
        // Loop to get individual element from the array
        $validextensions = array("jpeg","jpg","png");  // Extensions that are allowed
        $ext = explode('.', basename($_FILES['file']['name'][$i]))  // Explode file name from dot (.)
        $file_extension = end($ext); // Store extentions in the variable
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; //Set the target path with the name of the image
        $j = $j + 1; // Increment the number of uploaded images according to the files in the array
        if (($_FILES["file"]["size"][$i] < 100000) // Approx. 100kb files can be uploaded
        && in_array($file_ectensions, $validextensions)) {

            if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {

                // If file moved to uploads folder
                echo $j. ').<span id="noerror">Image uploaded successfully!. </span><br/><br/>';
            } else {    // If File was not moved.
                echo $j. '). <span id="error">Please try again!.<span><br/><br/>';
            }
        } else {        // If file size and File type incorrect.
            echo $j. ').<span id="error"> Invalid file Size or Type</span>       <br/><br/>';
        }
    }
}
?>

Thanks for any help with this.

Kevin B
  • 92,700
  • 15
  • 158
  • 170
  • It's hard to tell with your partial JavaScript and strange formatting, but it looks as though you never close one of `for (var i = 0, ii = form.length; i – Obsidian Age Feb 08 '17 at 22:28
  • form within form is not a good idea. for click on one button outside both forms you can trigger both form submit. – bawa g Feb 08 '17 at 22:28
  • You have 2 forms open tags and only one form close tag. Fix your HTML and you will find things work better – RiggsFolly Feb 08 '17 at 23:00
  • You shouldn't nest HTML form tags: http://stackoverflow.com/questions/379610/can-you-nest-html-forms – ChrisW Feb 08 '17 at 23:03
  • I've updated the HTML to show the entire modal I am using. I am getting a success in my console but not seeing results in the API or the server where the images should be. I assume this has something to do with the conflicting forms or the function I wrote is bad. – Tyler Brittin Feb 13 '17 at 19:12
  • `var resp = JSON.parse(response)` why? is that not throwing an error? – Kevin B Feb 13 '17 at 19:20
  • Well I want to submit both forms at the same time since they are in one modal. I get this from the console '
    index.html:318:45 uncaught exception: unknown (can't convert to string)' when doing `console.log(form)`
    – Tyler Brittin Feb 13 '17 at 19:21
  • after reading better your question... could it be better if using jQuery `when()` ? –  Feb 13 '17 at 19:24
  • Instead of the `function submitForms()` ? – Tyler Brittin Feb 13 '17 at 19:26
  • yes something like `$.when( document.getElementById("form").submit();).then(function() { document.getElementById("uploadForm").submit(); });` or vice versa on the forms. –  Feb 13 '17 at 19:28
  • @KevinB it isn't giving me an error on that, but i also don't get any type of response anyway – Tyler Brittin Feb 13 '17 at 19:29
  • @PeterDarmis you... can't use $.when like that, unless i'm missing your point.. – Kevin B Feb 13 '17 at 19:33
  • @TylerBrittin i don't see anything glaringly wrong with your code other than trying to parse an object as if it were json, but that wouldn't stop the other form from functioning. What exactly is wrong? that bit is unclear at this point. – Kevin B Feb 13 '17 at 19:35
  • @PeterDarmis I'm getting `SyntaxError: missing ) after argument list` I looked in the arguments of this but I don't work with JQuery much to recognize whats missing to use the `when()` statement you provided. – Tyler Brittin Feb 13 '17 at 19:35
  • ok one thing you can do is move this `document.getElementById("uploadForm").submit();` inside ajax success –  Feb 13 '17 at 19:36
  • Oh, i see, yeah... you can't submit two forms at once. The one uploading the image is going to abort the one performing ajax. you'll have to perform the ajax one, then the other after one is complete. – Kevin B Feb 13 '17 at 19:36
  • i wasn't meaning exactly write that :) my answer is the above :) –  Feb 13 '17 at 19:37
  • @KevinB I can't seem to debug it because I'm not getting any type of response from the upload.php code. Which leads me to believe that its not even being hit at all. Also, after adding the upload form, the submit button to submit the json to the API is no longer working. – Tyler Brittin Feb 13 '17 at 19:37
  • 1
    you have to submit in a sequential way. First submit your ajax json and inside the success palce your upload submit –  Feb 13 '17 at 19:38
  • In my success, would I need to change `function(reponse)` to like `function(e)` `success: function (response) { //var resp = JSON.parse(response) //alert(resp.status); document.getElementById("uploadForm").submit(); }, error: function (xhr, status) { alert("error"); }` – Tyler Brittin Feb 13 '17 at 19:50

0 Answers0