How to pass hidden values with ajax upload form - html

I'm busying with passing some values of hidden input with an ajax form. I've tried may ways but it looks like the values didn't go through.
HTML
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="hidden" name="sid" value="$rec_sStdi[std_sid]" />
<input type="hidden" name="stid" value="$rec_sStdi[stdi_sid]" />
<input type="text" name="title" class="form-control" size="50" maxlength="128" autocomplete="off" placeholder="ชื่อไฟล์ เช่น แบบประเมินครู เป็นต้น"/>
<progress id="progressBar" value="0" max="100" style="width:100%;"></progress>
<button class="btn btn-primary btn-xs pull-right" type="button" value="Upload File" onclick="uploadFile()"><i class="glyphicon glyphicon-upload"></i> อัพโหลด</button>
<input type="file" name="file1" id="file1" class="btn btn-danger btn-xs pull-right">
<b id="status"></b>
<p id="loaded_n_total"></p>
</form>
Javascript
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
//alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "inc/eval_file_upload.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
PHP (eval_file_upload.php)
<?
$sid=$_POST['sid'];
$stid=$_POST['stid'];
$title=$_POST['title'];
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "../files/$fileName")){
echo "\"$fileName\" upload is complete (sid:$sid , stid:$stid, title:$title)";
} else {
echo "move_uploaded_file function failed";
}
?>
I tried to test the passing by echoing the hidden values. But nothing shows up.
ref : http://www.developphp.com/view.php?tid=1351

Try to add the params in your ajax call:
sid = document.getElementById("sid").value;
stid = document.getElementById("stid").value;
formdata.append("sid", sid);
formdata.append("stid", stid);
And adds an id to your input type hidden.
<input type="hidden" id="sid" name="sid" value="$rec_sStdi[std_sid]" />
<input type="hidden" id="stid" name="stid" value="$rec_sStdi[stdi_sid]" />

Related

Saving information in google sheets from my form

I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>

HTML Get method

I have create a form with one text field and one select field and using GET method. Is it possible to make the parameter combine to one when submit the form? Example: test.html?domain=test.com
<form action = "test.html" method = "GET">
Name: <input type = "text" name = "domain" />
<select name="domain_ext" class="inputAuto">
<option value=".com">.com</option>
</select>
<input type = "submit" />
</form>
You can use XHR https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Here's a very basic example:
var getData = function () {
var xhr = new XMLHttpRequest();
var domain = document.querySelector('.domainInput').value;
var ext = document.querySelector('.extInput').value;
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE && xhr.status === 200) {
document.querySelector('.output').innerText = xhr.responseText;
}
};
xhr.open('GET', domain + ext, true);
xhr.send(null);
};
document.querySelector('.getButton').addEventListener('click', getData);
<form>
Name: <input type="text" value="https://output.jsbin.com/juwuy" class="domainInput" />
<select class="extInput">
<option value=".js" default>.js</option>
<option value=".com">.com</option>
</select>
<input type="button" value="Get" class="getButton"/>
</form>
<p class="output"></p>

HTML How to show an <iframe> when a button is pressed

Ive been using geolocation and HTML recently, i want to try to show an iframe when the submit button is pressed, i keep getting stuck on what to do.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" />
<input type="button" id="btn" value="Submit" onClick="javascript: window.open('https://api.ipdata.co/' + document.getElementById('text').value);" />
</body>
</html>
Oh and here’s my iframe
The IPadress is the ipadress of a device i am testing this out on. I want to put this in where the “javascript: window.open” is
I'm not sure why You'd want to show an iframe with a JSON response...
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
iframe = document.getElementById("iframe");
function text2iframe() {
iframe.src = "https://api.ipdata.co/" + text.value;
}
btn.addEventListener("click", text2iframe);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<iframe id="iframe"></iframe>
When you can go for the JSON directly!
var text = document.getElementById("text"),
btn = document.getElementById("btn"),
pre = document.getElementById("pre");
function ipdata() {
var request = new XMLHttpRequest();
request.open('GET', "https://api.ipdata.co/" + text.value, true);
request.addEventListener("load", function() {
if (request.status >= 200 && request.status < 400) {
pre.textContent = request.responseText
var responseObj = JSON.parse(request.responseText);
console.log( responseObj.country_name )
console.dir( responseObj );
} else {
// error
}
});
request.addEventListener("error", function() {
// connection error
});
request.send();
}
btn.addEventListener("click", ipdata);
<input type="text" id="text" value="47.91.202.22"><br>
<input type="button" id="btn" value="Submit"><br>
<pre id="pre"></pre>

form getting redirected to base_url when action is set to null in codeigniter view

I submit the below form its processing the code in the controller but after processing its redirecting to my base url. Also I haven't used any redirect in my controller function. why is it redirecting to my base_url when the action is null?
This is my form code
<form action="" class="form-horizontal contact-1" role="form" method="post" id="contactform">
<input type="hidden" name="operation" value="newquery">
<div class="form-group">
<div class="col-sm-6">
<input type="text" class="form-control" name="name" id="name" placeholder="Name">
</div>
<div class="col-sm-6">
<input type="text" class="form-control" name="email" id="email" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" id="subject" type="text" name="subject" placeholder="Subject">
<textarea name="message" type="text" id="msg" class="form-control textarea" cols="30" rows="5" placeholder="Message"></textarea>
<button type="submit" id="contsub" class="btn btn-primary btn-block contact-1-button" data-loading-text="Sending" ><i class="fa fa-send"></i> Send Message</button>
</div>
</div>
</form>
and this is my ajax call
<script>
$(document).ready(function() {
$("#contsub").click(function() {
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
I am not able to figure out what the problem is?
1.If you set form action empty, form will be submitted to its current url.so look at your browser current url and I think it is same as your base_url.
2.If you click on the contsub button your javascript $("#contsub").click(function() will not execute perfectly because when you click this button it will submit the form too and will redirect to the action url.change your <button type="submit" to <button type="button" so it will not submit the form and your javascript will work.
<script>
$(document).ready(function() {
$("#contsub").click(function(e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var subject = $("#subject").val();
var msg = $("#msg").val();
if (name == '' || email == '' || subject == '' || msg == '') {
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("contactform.php", {
name: name,
email: email,
subject: contact,
msg: msg
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
pressing the button causes the form to submit, redirecting you to your current location. adding the e.preventDefault(); will stop this from happening.

HTML form submitted to URL that depends on one of the fields

I have this form with one text field:
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
When the user enters a text, for instance "Hello" and clicks on Submit, I want to load the URL /search-results/hello. Any ideas?
Have a look at this and see if you could edit it to your specifications.
<form>
<div class="form-group">
<input type="text" id="var1" class="form-control" placeholder="Search">
</div>
<input type="button" id="URLGenerate" value="Generate" />
</form>
//assign the button event handler
document.getElementById( 'URLGenerate' ).addEventListener( 'click', onGenerate );
//given the name of a radio button group, it returns the value of the selected radio button or null if none of them are selected
function getRadioButtonValue ( name ) {
var allRadios = document.getElementsByName( name );
for ( var i = 0; i < allRadios.length; i++ ) {
if ( allRadios[i].checked ) {
return allRadios[ i ].value;
}
}
return null;//or any other value when nothing is selected
}
function onGenerate() {
//the base url
var url = 'http://domain.com/file.php';
//an array of all the parameters
var params = [];
//get the value from the edit box with id=var1
params.push( 'var1=' + document.getElementById( 'var1' ).value );
//get the value from the edit box with id=var2
// params.push( 'var2=' + document.getElementById( 'var2' ).value );
//get the value of the radio box
params.push( 'var3=' + getRadioButtonValue( 'var3' ) );
//join all the parameters together and add to the url
url += '?' + params.join( '&' );
alert( url );
}
Code:
http://jsbin.com/itovat/22/edit?html,js,output
Live:
http://jsbin.com/itovat/22/
Try this jQuery script
$("button[type=submit]").click(function(e){
e.preventDefault();
var searchItem = $("#form-control").val();
$("form").attr('action','search-results/'+searchItem);
$("form").submit();
});