Asked  7 Months ago    Answers:  5   Viewed   43 times

Q.1 I would like to convert this form to ajax but it seems like my ajax code lacks something. On submit doesn't do anything at all.

Q2. I also want the function to fire on change when the file has been selected not to wait for a submit.

Here is JS.

$('#imageUploadForm').on('submit',(function(e) {
    e.preventDefault()
    $.ajax({
        type:'POST',
        url: $(this).attr('action'),
        data:$(this).serialize(),
        cache:false
    });
}));

and the HTMl with php.

<form name="photo" id="imageUploadForm" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
    <input type="file" style="widows:0; height:0" id="ImageBrowse" hidden="hidden" name="image" size="30"/>
    <input type="submit" name="upload" value="Upload" />
    <img width="100" style="border:#000; z-index:1;position: relative; border-width:2px; float:left" height="100px" src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" id="thumbnail"/>
</form>

 Answers

81

first in your ajax call include success & error function and then check if it gives you error or what?

your code should be like this

$(document).ready(function (e) {
    $('#imageUploadForm').on('submit',(function(e) {
        e.preventDefault();
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                console.log("success");
                console.log(data);
            },
            error: function(data){
                console.log("error");
                console.log(data);
            }
        });
    }));

    $("#ImageBrowse").on("change", function() {
        $("#imageUploadForm").submit();
    });
});
Wednesday, March 31, 2021
 
macha
answered 7 Months ago
90

Try this. Edited to the final answer.

button:

<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
    <button class="reserve-button">Reserve Book</button>
</div>

script:

<script>
$('.reserve-button').click(function(){

    var book_id = $(this).parent().data('id');

    $.ajax
    ({ 
        url: 'reservebook.php',
        data: {"bookID": book_id},
        type: 'post',
        success: function(result)
        {
            $('.modal-box').text(result).fadeIn(700, function() 
            {
                setTimeout(function() 
                {
                    $('.modal-box').fadeOut();
                }, 2000);
            });
        }
    });
});
</script>

reservebook.php:

<?php
session_start();

$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);

if(isset($_POST['bookID']))
{
    $bookID = $_POST['bookID'];

    $result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);

    if ($result)
        echo "Book #" + $bookId + " has been reserved.";
    else
        echo "An error message!";
}
?>

PS#1: The change to mysqli is minimal to your code, but strongly recommended.

PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.

Wednesday, March 31, 2021
 
muffe
answered 7 Months ago
81

Try utilizing json to upload , process file object

html

<div id="drop" class="drop-area ui-widget-header">
  <div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
  <input type="file" name="file" id="file" multiple="true" accepts="image/*" />
  <ul class="gallery-image-list" id="uploads">
    <!-- The file uploads will be shown here -->
  </ul>
</form>
<div id="listTable"></div>

css

  #uploads {
      display:block;
      position:relative;
  } 

  #uploads li {
      list-style:none;
  }

  #drop {
      width: 90%;
      height: 100px;
      padding: 0.5em;
      float: left;
      margin: 10px;
      border: 8px dotted grey;
  }

  #drop.hover {
      border: 8px dotted green;
  }

  #drop.err {
      border: 8px dotted orangered;
  }

js

var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
    context: display,
    contentType: "application/json",
    dataType: "json",
    beforeSend: function (jqxhr, settings) {
        // pre-process `file`
        var file = JSON.parse(
                   decodeURIComponent(settings.data.split(/=/)[1])
                   );
        // add `progress` element for each `file`
        var progress = $("<progress />", {
                "class": "file-" + (!!$("progress").length 
                         ? $("progress").length 
                         : "0"),
                "min": 0,
                "max": 0,
                "value": 0,
                "data-name": file.name
        });
        this.append(progress, file.name + "<br />");
        jqxhr.name = progress.attr("class"); 
    }
});

var processFiles = function processFiles(event) {
    event.preventDefault();
    // process `input[type=file]`, `droppable` `file`
    var files = event.target.files || event.dataTransfer.files;
    var images = $.map(files, function (file, i) {
        var reader = new FileReader();
        var dfd = new $.Deferred();
        reader.onload = function (e) {
            dfd.resolveWith(file, [e.target.result])
        };
        reader.readAsDataURL(new Blob([file], {
            "type": file.type
        }));
        return dfd.then(function (data) {
            return $.ajax({
                type: "POST",
                url: "/echo/json/",
                data: {
                    "file": JSON.stringify({
                            "file": data,
                            "name": this.name,
                            "size": this.size,
                            "type": this.type
                    })
                },
                xhr: function () {
                    // do `progress` event stuff
                    var uploads = this.context;
                    var progress = this.context.find("progress:last");
                    var xhrUpload = $.ajaxSettings.xhr();
                    if (xhrUpload.upload) {
                        xhrUpload.upload.onprogress = function (evt) {
                            progress.attr({
                                    "max": evt.total,
                                    "value": evt.loaded
                            })
                        };
                        xhrUpload.upload.onloadend = function (evt) {
                            var progressData = progress.eq(-1);
                            console.log(progressData.data("name")
                                    + " upload complete...");
                            var img = new Image;
                            $(img).addClass(progressData.eq(-1)
                            .attr("class"));
                            img.onload = function () {
                                if (this.complete) {
                                  console.log(
                                      progressData.data("name")
                                      + " preview loading..."
                                  );
                                };

                            };
                        uploads.append("<br /><li>", img, "</li><br />");
                        };
                    }
                    return xhrUpload;
                }
            })
            .then(function (data, textStatus, jqxhr) {
                console.log(data)
                this.find("img[class=" + jqxhr.name + "]")
                .attr("src", data.file)
                .before("<span>" + data.name + "</span><br />");
                return data
            }, function (jqxhr, textStatus, errorThrown) {
                console.log(errorThrown);
                return errorThrown
            });
        })
    });
    $.when.apply(display, images).then(function () {
        var result = $.makeArray(arguments);
        console.log(result.length, "uploads complete");
    }, function err(jqxhr, textStatus, errorThrown) {
        console.log(jqxhr, textStatus, errorThrown)
    })
};

$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
    $(this).addClass("hover");
    return false;
};

droppable.ondragend = function () {
    $(this).removeClass("hover")
    return false;
};

droppable.ondrop = function (e) {
    $(this).removeClass("hover");
    var image = Array.prototype.slice.call(e.dataTransfer.files)
        .every(function (img, i) {
        return /^image/.test(img.type)
    });
    e.preventDefault();
    // if `file`, file type `image` , process `file`
    if (!!e.dataTransfer.files.length && image) {
            $(this).find(".drop-area-label")
            .css("color", "blue")
            .html(function (i, html) {
            $(this).delay(3000, "msg").queue("msg", function () {
                $(this).css("color", "initial").html(html)
            }).dequeue("msg");
            return "File dropped, processing file upload...";
        });
        processFiles(e);
    } else {
            // if dropped `file` _not_ `image`
            $(this)
            .removeClass("hover")
            .addClass("err")
            .find(".drop-area-label")
            .css("color", "darkred")
            .html(function (i, html) {
            $(this).delay(3000, "msg").queue("msg", function () {
                $(this).css("color", "initial").html(html)
                .parent("#drop").removeClass("err")
            }).dequeue("msg");
            return "Please drop image file...";
        });
    };
};

php

<?php
  if (isset($_POST["file"])) {
    // do php stuff
    // call `json_encode` on `file` object
    $file = json_encode($_POST["file"]);
    // return `file` as `json` string
    echo $file;
  };

jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

Tuesday, June 1, 2021
 
KingCrunch
answered 5 Months ago
42

Changing from serialize() to the following code works for me:

$('#imageUploadForm').submit(function(evt) {
                evt.preventDefault();

                var formData = new FormData(this);

                $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data:formData,
                cache:false,
                contentType: false,
                processData: false,
                success: function(data) {
                    $('#imagedisplay').html("<img src=" + data.url + "" + data.name + ">");
                },
                error: function(data) {
                    $('#imagedisplay').html("<h2>this file type is not supported</h2>");
                }
                });
            });
Sunday, October 10, 2021
 
Peyton
answered 2 Weeks ago
51

Both S├ębastien and Zain have valid points. It depends what kind of performance you're talking about.

If you want to reduce your server's bandwidth, then you should return JSON and create your display using client-side javascript.

However if your dataset is large, on most machines creating your display client-side could lag the browser and cause the UI to become unresponsive. If that is important to you then you might consider returning HTML from the server.

Tuesday, October 12, 2021
 
Kiran Dash
answered 2 Weeks ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :