0

I'm new to Phonegap development and got stuck on submitting a form and image. I've searched other articles and it seems no article covers submitting form data and an image.

What I've got so far is a page in HTML where you can take a picture (camera) or select one from you library. Underneath is a form. After touching the "Send" button in the form I want to send the data of the form and image to a PHP-server. The form is working perfectly and the content is brought to the server, when I try to include the Base64 image data as variable the information sent to the server is [object HTMLCollection] instead of the data itself.

The code:

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

// Wait for Cordova to connect with the device
//
document.addEventListener("deviceready",onDeviceReady,false);

// Cordova is ready to be used!
//
function onDeviceReady() {
    pictureSource=navigator.camera.PictureSourceType;
    destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
  // Uncomment to view the base64 encoded image data
  // console.log(imageData);

  // Get image handle
  //
  var smallImage = document.getElementById('smallImage');

  // Unhide image elements
  //
  smallImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  smallImage.src = "data:image/jpeg;base64," + imageData;
}

// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
  // Uncomment to view the image file URI 
  // console.log(imageURI);

  // Get image handle
  //
  var largeImage = document.getElementById('largeImage');

  // Unhide image elements
  //
  largeImage.style.display = 'block';

  // Show the captured photo
  // The inline CSS rules are used to resize the image
  //
  largeImage.src = imageURI;
}

// A button will call this function
//
function capturePhoto() {
  // Take picture using device camera and retrieve image as base64-encoded string
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
    destinationType: destinationType.DATA_URL });
}

// A button will call this function
//
function capturePhotoEdit() {
  // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
  navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
    destinationType: destinationType.DATA_URL });
}

// 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 });
}

// Called if something bad happens.
// 
function onFail(message) {
  alert('Mislukt: ' + message);
}

The HTML:

<div class="container">
      <div class="contactForm" id="contactForm">
        <form id="contact">
            <fieldset>
                <label for="contactName" id="name_label">Naam (vereist)</label>
                <input type="text" name="contactName" id="contactName" size="30" value="" class="text-input" />
                <span class="error" id="nameError">Geef uw naam op!</span>
                <label for="contactEmail" id="email_label">Email (vereist)</label>
                <input type="text" name="contactEmail" id="contactEmail" size="30" value="" class="text-input" />
                <span class="error" id="emailError">Geef uw e-mailadres op!</span> <span class="error" id="emailError2">Please enter a valid email address !</span>
                <label for="contactMessage" id="message_label">Locatie (vereist)</label>
                <textarea  name="contactMessage" id="contactMessage" class="text-input">    </textarea>
                <span class="error" id="messageError">Geef de locatie op!</span>
                <label for="contactProbleem" id="probleem_label">Probleem (vereist)</label>
                <textarea  name="contactProbleem" id="contactProbleem" class="text-input"></textarea>
                <span class="error" id="messageError">Geef het probleem in!</span>
                <input type="hidden" id="largeImage" name="largeImage" />
                <p class="contact-button-house">
                    <input type="submit" name="submitMessage" class="full-screen-button contactButton button grey" id="contactSubmitBtn" value="Send"/>
                </p>
            </fieldset>
        </form>

The JS-file:

jQuery(function() {
    jQuery('.error').hide();
    jQuery(".contactButton").click(function() {
    // validate and process form
    // first hide any error messages
        jQuery('.error').hide();

    var name = jQuery("input#contactName").val();
    if (name == "") {
        jQuery("span#nameError").show();
        jQuery("input#contactName").focus();
        return false;
    }
    var email = jQuery("input#contactEmail").val();
    if (email == "") {
        jQuery("span#emailError").show();
        jQuery("input#contactEmail").focus();
        return false;
    }

    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    if(!emailReg.test(email)) {
        jQuery("span#emailError2").show();
        jQuery("input#contactEmail").focus();
        return false;
    }

    var msg = jQuery("textarea#contactMessage").val();
    if (msg == "") {
        jQuery("span#messageError").show();
        jQuery("textarea#contactMessage").focus();
        return false;
    }

    var prob = jQuery("textarea#contactProbleem").val();
    if (prob == "") {
        jQuery("span#messageError").show();
        jQuery("textarea#contactProbleem").focus();
        return false;
    }

    var dataString = 'name='+ name + '&email=' + email + '&msg=' + msg + '&prob=' + prob + '&largeImage=' + largeImage;
//alert (dataString);return false;

    jQuery.ajax({
        type: "POST",
        url: "http://serverurl/script.php",
        data: dataString,
        success: function() {
            jQuery('#contactForm').html("<div id='successMessage' style='margin-top:47px;'></div>");
            jQuery('#successMessage').html("<img src='images/ok.png' alt='' style='float:left; margin-top:4px; margin-right:10px;'/><strong style='float:left;'>Thank you for contacting us!</strong>")
                .append("<p style='float:left;'>We will be in touch soon.</p>")
                .hide()
                .fadeIn(1500, function() {
                    jQuery('#successMessage');
                });
            }
        });
        return false;
    });
});

Any ideas what I'm doing wrong? Help is greatly appreciated! Thanks.

Shimon Rachlenko
  • 5,469
  • 40
  • 51
Erik
  • 26
  • 1
  • 5

1 Answers1

0

In your dataString you send a largeImage variable, which is obtained by

var largeImage = document.getElementById('largeImage');

thus it is a JS object and not what you need.

I also see that you assign image data to the src property of largeImage in onPhotoURISuccess method. According to your HTML, the largeImage is of type input, so i suggest you also change it to <img /> tag and then use the src property when you compose the `dataString.

var dataString = 'name='+ name + '&email=' + email + '&msg=' + msg + '&prob=' + prob + '&largeImage=' + largeImage.src;
Shimon Rachlenko
  • 5,469
  • 40
  • 51
  • Thanks for your reply and suggestion Shimon! I'm testing it out. – Erik Feb 27 '13 at 13:28
  • Your tips took me to the next level, thanks so much! The contents of largeImage now contains the URL of the actual file stored on my device. Now I need to think of a way to submit the actuel file and not the URL to a server. Any thoughts on how to do that? ..thanks for the help! – Erik Feb 27 '13 at 13:42
  • If the URL points to your server, you don't need to submit it, the image is already there(on your server). – Shimon Rachlenko Feb 27 '13 at 13:44
  • True but in this scenario the image is took by a mobile devices and thus stores it in it's local filesystem. The URL points to the local system, like: file:///var/mobile/Applications/6898FF-74B7-4331-A76D-7A37094E1C84/tmp/cdv_photo_037.jpg. The JS-file uses the POST-method to submit the data in the variables to a PHP-server, which results in de URL being sent instead of the file. Any thoughts? – Erik Feb 27 '13 at 13:50
  • [This SO answer](http://stackoverflow.com/questions/934012/get-image-data-in-javascript) shows the way to obtain image data from `img` tag – Shimon Rachlenko Feb 27 '13 at 13:57