4

I know how to upload images by ajax but I want to upload images via jQuery steps. I've tried multiple ways but its not not working. If anyone has ever done that please help me. Thanks.

HTML

<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">

jQuery

if(currentIndex == 0)
{ 
    var upload_doc = $("#upload_doc").val();
    event.preventDefault();
    $.ajax({
        async: false,
        url: myUrl,
        dataType: 'json',
        type: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data : {  upload_doc : upload_doc, step1 : step1},
        success: function(response) {
            console.log(response);
        }
    });
}
bharat parmar
  • 302
  • 3
  • 14
nerdyDev
  • 376
  • 3
  • 15
  • Hi! Please don't delete and re-ask your question, instead edit your question to improve it. – Epodax Oct 31 '16 at 08:19
  • means : you dont need to save it `server` just get from client and display in div ?? if client side only means its posssible but while refreshed img will be gone. – Karthi Oct 31 '16 at 08:23
  • U have done this previously but the thing is that , i use php + ajax do u need an answer having php too ? If yes i will upload my answer – akash raigade Oct 31 '16 at 08:25
  • yes i am using php also. after all i am sending data to php @akashraigade – nerdyDev Oct 31 '16 at 08:54
  • can u help me @akashraigade – nerdyDev Oct 31 '16 at 10:01
  • Are other given solutions worked for you ? I didnt answered bcas they given answers for your question ..are thier answer working dor you ? – akash raigade Oct 31 '16 at 16:41
  • umm no. its not working. if i mention contentType and processData the data doesn't go to url and don't submit the data i enter and i have set a check on the response that if the response doesn't come true it should stay on the same page. but the response can come true only if the data reaches the url. now it stays on same page cuz data doesn't go to the url cuz of contentType and processType parameters. – nerdyDev Oct 31 '16 at 17:42

4 Answers4

1

Follow this way for upload an image, In this way you don't want HTML form.

Add this code to your mainpage.php

<input type="file" name="upload_doc" id="upload_doc" title="Search for a file to add"/>
<input id="uploadImage" type="button" value="Upload Image" name="upload"/>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
 <script type="text/javascript">
    jQuery.noConflict();
    jQuery('#uploadImage').on("click", function (e) {
        var uploadedFile = new FormData();
        uploadedFile.append('upload_doc', upload_doc.files[0]);
        jQuery.ajax({
          url: 'lab1.php',
          type: 'POST',
          processData: false, // important
          contentType: false, // important
          dataType : 'json',
          data: uploadedFile
        });
    });
</script>

Then add this for upload.php

<?php
    // check record array
    print_r($_FILES);
    move_uploaded_file($_FILES['upload_doc']['tmp_name'], $_FILES['upload_doc']['name']);
?>
Gayan
  • 2,845
  • 7
  • 33
  • 60
  • uploadedFile.append('#upload_doc', upload_doc.files[0]); i have to mention hash right? – nerdyDev Oct 31 '16 at 09:10
  • @NerdyDev no need hash(#) upload_doc.files[0] for this part – Gayan Oct 31 '16 at 09:14
  • ok i sed this same thing and in php file i did print_r( json_encode($_FILES));exit; in php file still my console comes empty. – nerdyDev Oct 31 '16 at 09:17
  • @NerdyDev Remove json_encode and print, print_r($_FILES); – Gayan Oct 31 '16 at 09:20
  • still no response :( – nerdyDev Oct 31 '16 at 09:25
  • @NerdyDev If your file contain more jQuery scripts (other than this), it may cause to jQuery conflict, so you better try this without other script and content(just create two page and try). If it works then you can fix jQuery conflict. – Gayan Oct 31 '16 at 09:30
  • @NerdyDev And I guess you get 200 OK message on console after you press the button – Gayan Oct 31 '16 at 09:32
  • the thing is that i am sending many data from this form. and image is one of those parameters. – nerdyDev Oct 31 '16 at 09:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127034/discussion-between-user3099298-and-nerdydev). – Gayan Oct 31 '16 at 09:34
1

first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.

<form action="" name="imageUploadForm" id="imageUploadForm" method="post" enctype="multipart/form-data">
<input type="file" style="background-color: #2184b3; color: #fff;" class="btn btn-default" name="upload_doc" id="upload_doc" title="Search for a file to add">
</form>
<script type="text/javascript">
    $(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);
                }
            });
        }));

        $("#upload_doc").on("change", function() {
            $("#imageUploadForm").submit();
        });
    });
</script>
Samir Lakhani
  • 685
  • 10
  • 19
0

From your comment,

actually the thing is that I'm submitting many values also when uploading the image. so one click of next i sends so many data including image. rest data goes well except image only.

If you're uploading file, along with other input values, through AJAX, use FormData object. But keep in mind that old browsers don't support FormData object, FormData support starts from the following desktop browsers versions: IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+.

So your jQuery should be like this:

if(currentIndex == 0){
    event.preventDefault();
    var formData = new FormData($('form')[0]);
    $.ajax({
        async: false,
        url: myUrl,
        dataType: 'json',
        type: 'POST',
        cache: false,
        contentType: false,
        processData: false,
        data : formData,
        success: function(response) {
            console.log(response);
        }
    });
}
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • what if i want to get only image from the form not the whole form.This formData will get only image?? – nerdyDev Oct 31 '16 at 08:45
  • @NerdyDev Yes, it will capture only image. However, you should validate the input values on the server side. – Rajdeep Paul Oct 31 '16 at 08:47
  • i have used it before but i haven't used it in jquery steps. and in my success i have "console.log()response" and in php file i have "echo json_encode($_FILES);exit;" but console log shows nothing – nerdyDev Oct 31 '16 at 08:52
  • @NerdyDev It should be `console.log(response);`. Do you have other forms apart from this one? If so, then change this statement, the index, accordingly, `var formData = new FormData($('form')[0]);`. Also, check whether the AJAX is being fired correctly or not. – Rajdeep Paul Oct 31 '16 at 08:59
  • no only this form and yeah i meant that console.log(response); – nerdyDev Oct 31 '16 at 09:01
  • i have used alert(JSON.stringify(formData)); to check whether my formData has data or not and it shows empty – nerdyDev Oct 31 '16 at 10:07
  • @NerdyDev Post your complete code(HTML and jQuery) on [pastebin.com](http://pastebin.com/index.php) and give me it's link here. – Rajdeep Paul Oct 31 '16 at 10:49
0

first in your ajax call include success & error function and then check if it gives you error or what?You can use jquery.form.js plugin to upload image via ajax to the server.

$(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();
    });
});
Samir Lakhani
  • 685
  • 10
  • 19