If I create a dynamic bitmap on the clientside via javascript, how can I submit this via POST or GET ( and then parse out values from the bitmap on the serverside? NodeJS, PHP etc )
From Making Images Byte-by-Byte in Javascript
var src = 'data:image/bmp;base64,' + myBase64EncodedData;
Just upload the base 64 data. Parse it on the server side form there any way you like.
HTML:
<form id="uploadImage" method="POST">
<input type="hidden" name="imageData64" id="imageData64"/>
<input type="submit" value="upload"/>
<form>
JS:
document.getElementById('uploadImage').onsubmit = function() {
document.getElementById('imageData64').value = myBase64EncodedData;
};
Or you could do the same with an ajax request.
You probably don't want to use GET though. Partly because it's not appropriate, you aren't retrieving anything form the server. But more because GET puts some limits on URL length, so your image data may not fit. POST has no such limit since the request can have a body, unlike GET.
You can use post like this..
HTML
<img src="whatever.jpg" id="myimage" />
<div id="button" data-role="button">Click on button</div>
JS
$(function() {
$("#button").click(function() {
postImageData();
});
});
function postImageData(){
var img = document.getElementById('myimage')
var myBase64EncodedData = getBase64Image(img);
$.ajax({
type: 'POST',
url: 'http://same_domain_url.com/',
data: {
'imagedata': myBase64EncodedData
},
success: function(msg){
console.log('posted' + msg);
}
});
}
php
$imagedata=$_POST['imagedata'];
For getBase64Image function refer to this SO question
Get image data in JavaScript?
Related
I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}
i have a simple browse which accepts only images. But after onclick button i can not get the full path in javascript so that i can send them to server by jquery post. i am only getting the filename.
javascript
<script type="text/javascript">
function post_ad() {
var img = document.getElementById('img1'),
tempimg= img.value;
alert(tempimg);
jQuery.ajax({
type: 'POST',
url: 'process.php',
data: {
tempimg: tempimg
},
success: function (html) {
}
});
}
</script>
HTML
<input id="img1" name="img1" accept="image/*" type='file'>
<input type="button" onclick="post_ad()" value="click">
For security reasons its forbidden. Here its a more complete answer:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
I am trying to use jQuery to trigger a form submission and then use AJAX to call a PHP script that will handle the file and return a response. The issue, though, is that the file is not being uploaded upon submitting the form.
HTML:
<div id="browseButton" class="step1Button" onclick="browseFile()">Browse</div>
<form method="post" id="fileForm" style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<input id="submitForm" type="submit" style="display: none"/>
</form>
<div id="previewButton" class="step1Button pull-right" onclick="uploadFile()" style="background-color: #57a957">
Preview
</div>
jQuery:
function uploadFile() {
submitForm();
parseExcel();
}
var submitForm = function() {
$('#previewButton').click(function(){
$('#submitForm').click();
});
};
var parseExcel = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",'default/ParseExcel',true);
xmlhttp.send();
console.log("made it past excel parse");
};
The PHP that's called:
public function actionParseExcel() {
print "made it to parse".PHP_EOL;
print "File:";
if($_FILES['FileInput']['tmp_name']) {
print_r($_FILES['FileInput']['tmp_name']);
}
else {
print "Not found";
}
print "Done.";
}
I know the issue is that my form isn't submitting the chosen file because that's typically why the "Undefined index" error is thrown. But I can't understand why.
First, if you don't want your page to refresh, you better use <input type="button">
or else call your JavaScript via <form onSubmit="uploadFile()"> and return false at the end of your function uploadFile().
Second, you'll need to put enctype="multipart/form-data" in your <form>.
I see you're using JQuery, you should use it to send your AJAX request too :
// This code supports multiple type="file" inputs
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Create a formdata object and add the file
var data = new FormData();
// In case you want to upload more than one file
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'your.php?FileInput',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Prevent the file from beeing converted to string
contentType: false, // Set the content file to false prevent JQuery from using 'application/x-www-form-urlencoded; charset=UTF-8' as default type
...
});
I hope this will lead you to the solution...
Edited : var files declaration + files processing
To send forms with files you need to use enctype="multipart/form-data".
BUT, as far as I know, you can't send files using ajax.
So, the solution for that is to use a hidden iFrame:
Create a hidden iFrame (outside of your form) and assing it an ID
Create the form pointing to yout PHP file, and using the attribute enctype="multipart/form-data" and target="ID_OF_THE_IFRAME" (so the form, when submitted, will be sent to that iframe)
When the PHP finish procesing the file, you could output a javascript that calls parent.YOURFUNCTION(), so you can do whatever you want when the process is done.
Good luck!
I have looked through all the similar posts out there but nothing seems to help. This is what I have
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
Send Message
Clear Form
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submit is pressed. I tried return false; I tried preventDefault() and every combination including return false; inside the onClick. I also tried using input type="button" and type="submit" instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
Modify the function like this:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
onclick = sendForm(event);
Update 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
function sendForm(){
// all your code
return false;
}
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
Have you tried using
function sendForm(event){
event.preventDefault();
}
Simple and Complete working code
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loading could be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
I expect anyone to understand my idea very well as it's a very simple idea.
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:
// element refers to the form DOM after you got it in a variable called element for example:
element.addEventListener('submit', (e) => {
e.preventDefault();
// rest of your code goes here
});
The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
Of course it will work only with forms.
The way I approached this: I removed the entire form tag and placed all the form elements such as input, textarea tags inside a div and used one button to call a javascript function. Like this:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a form when we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
Note:
The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.
I have an HTML form which i populate from a database. On submit we load a page called "viewgame.php". Now what i want is here to run some scripts to populate some tables with data but how exactly can i pass the variable which i got from the form ex. $_POST['gameNo'] to the other php file though JavaScript?
Below is some of my code
JS function
function refreshGameinfo() {
var load = $.get('gameinfo_sc.php');
$(".gameinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
// do something here if request failed
});
load.success(function(res) {
console.log("Success");
$(".gameinfo").html(res);
});
load.done(function() {
console.log("Completed");
});
}
How can i pass the $POST_['gameNo'] to the gameinfo_sc.php file so that i can get the correct results?
Try this
var load = $.get('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_GET['gameNo']
For post method use
var load = $.post('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_POST['gameNo']
You are trying to post $POST_['gameNo'] to gameinfo_sc.php but $.get isn't the right method for post, its actually for http get. you can also do this by using $.post http://api.jquery.com/jquery.post/
function refreshGameinfo() {
$.ajax({
type: "POST",
url: "gameinfo_sc.php",
data: {gameNo: data},
cache: false,
success: function(html){
console.log( "Success" );
$(".gameinfo").html(res);
},
error:function(html){
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
}
});
}
try this
You can do it like this:
(in html layout):
<input type="hidden" id="gameNo" value="<?=$_POST['gameNo']?>" />
(in js file):
var gameNo = $('#gameNo').val();
var load = $.get('gameinfo_sc.php', {gameNo: gameNo});
....
UPDATE:
If your server doesn't support short open tags, you can write:
<input type="hidden" id="gameNo" value="<?php echo $_POST['gameNo'] ?>" />