PhoneGap upload Image to server on form submit

Create two functions you can call separately. One function for just getting the image, and another function to upload the image.

You can do something like below.

<!DOCTYPE html>
<html>
  <head>
    <title>Submit form</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // device APIs are available
    //
    function onDeviceReady() {
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
    }


    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {

        // Show the selected image
        var smallImage = document.getElementById('smallImage');
        smallImage.style.display = 'block';
        smallImage.src = imageURI;
    }


    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    function uploadPhoto() {

        //selected photo URI is in the src attribute (we set this on getPhoto)
        var imageURI = document.getElementById('smallImage').getAttribute("src");
        if (!imageURI) {
            alert('Please select an image first.');
            return;
        }

        //set upload options
        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType = "image/jpeg";

        options.params = {
            firstname: document.getElementById("firstname").value,
            lastname: document.getElementById("lastname").value,
            workplace: document.getElementById("workplace").value
        }

        var ft = new FileTransfer();
        ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
    }

    // Called if something bad happens.
    //
    function onFail(message) {
      console.log('Failed because: ' + message);
    }

    function win(r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        //alert("Response =" + r.response);
        console.log("Sent = " + r.bytesSent);
    }

    function fail(error) {
        alert("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
    }

    </script>
  </head>
  <body>
    <form id="regform">
        <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Select Photo:</button><br>
        <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />

        First Name: <input type="text" id="firstname" name="firstname"><br>
        Last Name: <input type="text" id="lastname" name="lastname"><br>
        Work Place: <input type="text" id="workplace" name="workPlace"><br>
        <input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
    </form>
  </body>
</html>

You're already sending custom fields in your example.

var params = new Object();
params.value1 = "test";
params.value2 = "param";

options.params = params;

Just populate params with your form fields.


I also faced same problem, but I have done using two server side calls on one click. In this, in first call submit data and get its id in callback using JSON then upload image using this id. On server side updated data and image using this id.

$('#btn_Submit').on('click',function(event) {
   event.preventDefault();
   if(event.handled !== true)
   {
      var ajax_call = serviceURL; 
      var str = $('#frm_id').serialize();                 
      $.ajax({
      type: "POST",
      url: ajax_call,
      data: str,
      dataType: "json",
      success: function(response){
              //console.log(JSON.stringify(response))
        $.each(response, function(key, value) { 
              if(value.Id){                               
                   if($('#vImage').attr('src')){
                         var imagefile = imageURI; 
                          $('#vImage').attr('src', imagefile);
                        /* Image Upload Start */
                          var ft = new FileTransfer();                     
                        var options = new FileUploadOptions();                      
                        options.fileKey="vImage";                      
                        options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
                        options.mimeType="image/jpeg";  
                        var params = new Object();
                        params.value1 = "test";
                        params.value2 = "param";                       
                        options.params = params;
                        options.chunkedMode = false;                       
                        ft.upload(imagefile, your_service_url+'&Id='+Id+'&mode=upload', win, fail, options); 
                      /* Image Upload End */
                   }      
               }

             }); 
          }
     }).done(function() {
          $.mobile.hidePageLoadingMsg();              
     })

   event.handled = true;
  }
  return false;
});

On server side using PHP

if($_GET['type'] != "upload"){
  // Add insert logic code
}else if($_GET['type'] == "upload"){
  // Add  logic for image 
  if(!empty($_FILES['vImage']) ){ 
    // Copy image code and update data  
  }
}