Capture image and upload to server using PhoneGap


Client Side Script

PhoneGap Capture Image API: Capture Image PhoneGap API



//Camera Section
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is ready
function onDeviceReady() {}

// Called when capture operation is finished
//
function captureSuccess(mediaFiles) {    
    uploadFile(mediaFiles[0]);
}

// Called if something bad happens.
//
function captureError(error) {
    var msg = 'An error occurred during capture: ' + error.code;
    navigator.notification.alert(msg, null, 'Uh oh!');
}

// A button will call this function
//
function captureImage() {
    // Launch device camera application,
    // allowing user to capture only one image by {limit: 1}
    navigator.device.capture.captureImage(captureSuccess, captureError, { limit: 1 });
}

// Upload files to server
function uploadFile(mediaFile) {
    path = mediaFile.fullPath;
    name = mediaFile.name;
    
    var options = new FileUploadOptions();
    options.fileKey="file";
    options.fileName=mediaFile.name;
    options.mimeType="image/jpeg";

    var params = new Object();
    params.fullpath = path;
    params.name = name;

    options.params = params;
    options.chunkedMode = false;
    
    var ft = new FileTransfer();
    ft.upload( path, "http://www.serverurl.com/image_upload",
        function(result) {
			//upload successful            
        },
        function(error) {
            //upload unsuccessful, error occured while upload. 
        },
        options
        );
}

Server Side Code


    $new_image_name = $_FILES["file"]["name"];
    move_uploaded_file($_FILES["file"]["tmp_name"], WWW_ROOT . "/products/" . $new_image_name);

Cross-Domain Ajax call with JSNOP in PhoneGap


Client side script:


	var url = base_url;  // you'll want to change

	$.ajax({
		type: 'GET',
		url: url,
		contentType: "application/json",
		dataType: 'jsonp',
		crossDomain: true,
		data: {
			username: $('#username').val(),
			password: $('#password').val()
		},		
		beforeSend: function ( xhr ) {
			//show your image loader here
			$('.loader-image').fadeIn(100);
		},
		success: function ( res ) {
		    //hide your image loader
			$('.loader-image').fadeOut(100);
			if( res.value === 2 ) {
				//unsuccessful code goes here
				return false;
			}
			if( res.value === 1 ){
				//success code goes here
			}
		}
	});

Server side code:


$email = $_GET['username'];
$pass = $_GET['password'];

$user = DO user query using $email and $pass checking.

if (!empty($user)) {
	$value = 1;
} else {
	$value = 2;
}
$theName->value = $value;
echo $_GET['callback'] . '(' . json_encode($theName) . ')';