I have created simple html form that contains text inputs, text area , files such as uploading images ..
how could I submit this form data when turning it into phone gap application that contains user registration to his data and photo and cv document?
when submitting data it should be sent to php page where mysql insert will held?
I have tried the serialize method face problems in getting data in th php page
also couldn't find the way to upload file and images??
any help???
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("Hello ");
$("#button").click(function(evt){
var name = $("#name").val();
var message = $("#message").val();
var sendData = { "name": name, "message": message };
$.ajax({
type: "POST",
url: "http://localhost/webs/main/ajax/process.php",
data: sendData,
success: function(data) {
log.console(data);
$("#info").html(data);
}
});
alert("Hello ");
alert($("#test").val());
alert($("#name").val());
alert($("#message").val());
return false;
});
}
Upload image using phonegap
============================
function uploadImage(){
//Using Camera
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: Camera.DestinationType.FILE_URI });
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
console.log("Message = " + message);
}
function uploadPhoto(imageURI) {
var imagefile = imageURI;
$('#vImage').attr('src', imagefile);
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
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, win, fail, options);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert($.parseJSON(r.response))
}
function fail(error) {
console.log("Response = " + error.code);
}
On your php file
=================
file_put_contents("file.txt", print_r($_FILES, true));
Post Form data and Image together
================================
// Here first submit your form input data after successfully submit upload image call
$('#submit').on('click', function(event){
if(event.handled !== true)
{
var ajax_call = serviceURL;
var str = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: str,
dataType: "json",
success: function(response){
$.each(response, function(key, value) {
// after success submit data
if(response){
var imagefile = $('#vImage').attr('src');
/* Image Upload Start */
var ft = new FileTransfer();
var options = new FileUploadOptions();
options.fileKey="vImage1";
options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
options.mimeType="image/jpeg";
options.mimeType="image/png";
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
options.chunkedMode = false;
ft.upload(imagefile, your_service_url, win, fail, options);
}
});
}
});
event.handled = true;
}
return false;
})
Related
I'm trying to save the generated PDF file with JSPDF plugin into the server instead of being saved on the client side, the javascript part that handles the JsPDF is this:
<script type="text/javascript">
(function(){
var
form = $('.form'),
cache_width = form.width(),
//cache_height = form.height(),
a4 =[ 595.28, 841.89]; // for a4 size paper width and height
$('#create_pdf').on('click',function(){
$('body').scrollTop(0);
createPDF();
});
//create pdf
function createPDF(){
getCanvas().then(function(canvas){
var
img = canvas.toDataURL("image/png"),
doc = new jsPDF({
unit:'px',
format:'a4'
});
var imgWidth = 220;
var pageHeight = 295;
var imgHeight = canvas.height * imgWidth / canvas.width;
var heightLeft = imgHeight;
var doc = new jsPDF('p', 'mm');
var position = 0;
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
doc.addPage();
doc.addImage(img, 'PNG', 0, position, imgWidth, imgHeight);
heightLeft -= pageHeight;
}
var blob = doc.output('blob');
var formData = new FormData();
formData.append('pdf', blob);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
dataType: 'text',
cache: false,
processData: false,
contentType: false,
success: function(response){
alert(response);
console.log(response)
},
error: function(err){
alert(err);
console.log(err)
}
});
});
}
// create canvas object
function getCanvas(){
form.width((a4[0]*1.33333) -80).css('max-width','none');
return html2canvas(form,{
imageTimeout:2000,
removeContainer:true
});
}
}());
</script>
the upload.php file should move the generated pdf file or its content to the Uploads folder but it seems that the $_FILES['data'] is empty
<?php
if(!empty($_FILES['data'])) {
// PDF is located at $_FILES['data']['tmp_name']
$content = file_get_contents($_FILES['data']['tmp_name']);
//echo $content;
$location = "uploads/";
move_uploaded_file($_FILES['data']['tmp_name'], $location.'random-name.pdf');
} else {
throw new Exception("no data");
}
the response I get back from Ajax is "Notice: Undefined index: data ".
Thanks in advance for any help.
I finally got it to work using this code:
var pdf = btoa(doc.output());
var file_name = $('#id').val();
//var file_name = 'hello world';
$.ajax({
method: "POST",
url: "upload.php",
data: {data: pdf, filename: file_name},
}).done(function(data){
// alert(data);
console.log(data);
});
and on the server side upload.php like this:
if(!empty($_POST['data'])){
$data = base64_decode($_POST['data']);
$fileName = $_POST['filename'];
file_put_contents( "uploads/".$fileName.".pdf", $data );
} else {
echo "No Data Sent";
}
exit();
I have this function to get values from a form
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();
$.ajax({
url:"fetch_import.php",
method:"POST",
data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
and a php code like this:
enter code here$bcid = $_POST['batchid'];
$yrs = $_POST['yrstart'];
$yrg = $_POST['yrend'];
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);
passing the file doesn't work. I've searched for this but still not working for me, i think i'll understand how it will work. Any idea? Tyia
You should append your fields to fd and simply use that as data-parameter in $.ajax:
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
fd.append('batchid', $("input[name='batchid']").val());
fd.append('yrstart', $("input[name='yrstart']").val());
fd.append('yrend', $("input[name='yrend']").val());
$.ajax({
url:"fetch_import.php",
method:"POST",
data: fd,
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
I am trying to send an image via JavaScript after displaying the preview on the screen, I refuse to use Dropzone, Plupload or any JavaScript library, because I just want a simple functionality.
var finput;
var fileReader;
var fd; //formdata...
$(function(){
fileReader = new FileReader;
fileReader.onload = function(e) {
var img = document.createElement("img");
img.src = fileReader.result; //display the image on the screen...
img.height = 200;
$('#pimgbox').html(img);
//enable the image button... // $('#pimagebox').html(img);
$('#pimgbtn').removeAttr('disabled', 'disabled').removeClass('btn-alert').addClass('btn-primary');
}
});
and when you click on the submit button
$('#pimgbtn').bind('click', function(e){
//initialize the formdata...
fd = new FormData(); //initialize the formdata..
fd.append('pimgupl', finput.files[0]); //s
//alert(fd);
$('#pimgldr').css('display','block');
$(this).attr('disabled', 'disabled').removeClass('btn-primary').addClass('btn-alert')
if(fileReader.result != null){
////////////// beginning of ajax call...
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
}; //end of setting..
$.ajax(settings)
.done(function (response) {
alert(response);
resetPUplButtons();
//close modal...
$('#profimgwin').modal('hide');
})
.fail(function (jqXHR, textStatus, error) {
alert('error sending file...' + error);
resetPUplButtons();
});
/////////////////////////end of ajax calls..
}else{
alert('you havent selected an image yet..');
resetPUplButtons();
}
});
and on my Laravel usercontroller I have this method that tries to upload the image but it's refusing to work.
public function setProfilePix(Request $request){
$file = $request->file('pimgupl');
$code = Auth::user()->profile->usrcode;
$targetDir = public_path() . DS . 'userdata'.DS.'ppix';
$newname = $targetDir.DS.strtolower($code).md5($code).'_'.time() .'.jpg';
// echo $newname;
//exit;
$file->move($targetDir, $newname);
echo 'saved';
}
I keep getting this error in my output panel:
Line 418 is the ajax operation, I have tried everything but nothing seems to be working. I have also added an exception to the route in my verifyCsrfToken.php - middleware, but still it isn't working.
In your jQuery try changing settings from
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd
};
to
var settings = {
type: "POST",
url: "/user/setprofilepix",
data: fd,
processData: false,
contentType: false,
};
I used thickbox components in Joomla. I am submitting form using jQuery ajax but jQuery not getting values after click on submit buttons. I used
and created script.js file containing :
jQuery(document).ready(function(){
jQuery('.wp_btn').click(function() {
var id = $j(this).attr('id');
var url = $j(this).attr('value');
if (document.cookie.indexOf('visited=true') == -1) {
var fifteenDays = 1000*60*60*24*15;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
jQuery("#dwnlnk").val(url);
TB_show('', '/#TB_inline?KeepThis=true&id=9876asdvfrty54321&height=250&width=350&inlineId=mypopup&caption=Subscription', '');
}else{
window.location = url;
}
});
//
jQuery(document).on('submit', '#subscription',function(){
return false;
});
jQuery(document).on('click', '#btnSubmit',function(){
var url = jQuery('#dwnlnk').val();
var txtname = $j('input[name=txtname]').val();
var txtemail = $j('input[name=txtemail]').val();
jQuery.ajax({
type: 'POST',
url: 'whitepapers/',
data: jQuery('#frmsubscription').serialize(),
success: function(data) {
alert(data);
//if(data == 'true') {
window.location = url;
//}
}
});
});//end click
});
I already tried document.getElementById('txtname').value but its not getting value of textbox. When I entered static value then its getting value.
You have to use jQuery or $ to select an element.
Try this
var txtname = jQuery('input[name="txtname"]').val();
var txtemail = jQuery('input[name="txtemail"]').val();
OR
var txtname = $('input[name="txtname"]').val();
var txtemail = $('input[name="txtemail"]').val();
I am currently trying to upload a file through a form I made, using jQuery. This is what I am attempting to do:
function ajax_upload(){
var formData = new FormData($('form#userform'));
$.ajax({
url: location.protocol + "//" + location.host + "/profile/uploadPicture",
dataType: 'json',
data: formData,
type: 'post',
success: function(data, status){
if (data.status == 'error') {
$('#error').html(data.msg);
}
else {
var filename = location.protocol + "//" + location.host + "/data/profiles/" + data.msg;
$('input#filename').val(filename);
close_upload_form();
pop_profilechanger(filename);
}
}
});
return false;
}
the form appears to post to the backend, but while trying to return the filename from the uploaded file in a JSON object like:
echo json_encode(array('status' => $status, 'msg' => $msg));
Is there something wrong?
Please tell me
This is how I do it. If you want more information, rather than just my pasted code, check out this http://www.html5rocks.com/en/tutorials/file/dndfiles/ because my code was made for drag and drop files
handleFiles : function(files, evt, target)
{
console.log(target);
$.each(files, function(index, value)
{
var file = value;
reader = new FileReader();
reader.onload = function(evt)
{
var li = $("<li class='uploading'><img data-image-id='0' src='" + evt.target.result + "' /></li>");
target.find('.imagesList').append(li);
var request = new XMLHttpRequest();
var formData = new FormData();
formData.append('image', file);
request.open("Post", settings.uploadImageUrl);
request.addEventListener("load", function(evt)
{
var id = evt.target.responseText;
li.removeClass('uploading');
li.find('img').attr('data-image-id', id);
}, false);
request.send(formData);
};
reader.readAsDataURL(value);
});
},