Insert javascript Array into database by clicking a button php - javascript

I have the following code:
- the javascript helps me select a text file and it chooses only the id from the text file. example of text file is below:
ID,Name,Surname
re-002,ram,kelu
rf-897,rem,juke
When i added the button 'loader', the javascript readText no longer displays the id that it took from the text file.
What i want to do is to allow user to select a text file, read only the ids, and then place the ids in my database.
My html page:
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}
}
$("#loader").on("click", function(){
var upload = $.ajax({
type: "POST",
url: "loader.php",
data: {array:output},
cache: false,
beforeSend: function() {
}
});
</script>
</head>
<body>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick='btn()'> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
</h3>
</body>
</html>
My php page 'loader.php':
<?php
define ( 'DB_HOST', 'localhost' );
define ( 'DB_USER', 'root' );
define ( 'DB_PASSWORD', '' );
define ( 'DB_NAME', 'dbapp' );
$array = json_decode($_POST['output']);
$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASSWORD','DB_NAME');
$arr_id = $mysqli->real_escape_string($array[0]);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO `user` (id) VALUES($arr_id)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br
/>';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
// close connection
$mysqli->close();
?>

Your code is brittle. But moving output declaration outside readText might help actually send some data
var output; // move the output declaration here
var reader = new FileReader();
function readText(that) {
if (that.files && that.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
output = e.target.result;
//process text to show only lines with "-":
output = output.split("\n").filter((line, i) => i != 0).map(line => line.split(",")[0]).join("<br/>\n");
document.getElementById('main').innerHTML = output;
}; //end onload()
reader.readAsText(that.files[0]);
}
}
function btn() {
var upload = new XMLHttpRequest();
upload.open("POST", "loader.php");
upload.send(JSON.stringify({ array: output }))
upload.onreadystatechange = function () {
if (upload.readyState === XMLHttpRequest.DONE) {
if (upload.status === 200) {
alert(upload.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
}
<main id="main"></main>
<h1> Utilisateur Nommé </h1>
<h3> Import : <button id="loader" onclick="btn()"> Import</button>
<h3> Choose file : <input type="file" onchange='readText(this)' />
Bonus: done without jQuery.
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started

Related

Probleme with ajax

I need help with my project, i have to do an 'drag n drop' zone, and, when the image is droped, it must be saved on the server (via PHP, which I succeeded), but also appear on the HTML thanks to the response from AJAX via PHP. I don't know what to do anymore, here is some code bugs. Each time I see the JS alert announces: 'An exception is produced: undefined'. I don't use Jquery or anyting else, it's just vanilla PHP and Javascript, Thanks for your help
Sorry for my bad English, I'm french :)
my code :
<body onload="init()" >
<div id="drop_file_zone" ondrop="upload_file(event)" ondragover="return false">
<div id="drag_upload_file">
<p>Drop file here</p>
<p>or</p>
<p><input type="button" value="Select File" onclick="file_explorer();"></p>
<input type="file" id="selectfile">
</div>
</div> <br>
<img id = "imageSource" src="uploads/"/>
<script type="text/javascript">
var fileobj;
var url = "ajax.php";
function upload_file(event) {
event.preventDefault();
var target = document.getElementById ("drop_file_zone");
for (var i = 0; i < 1; i++) {
var fileobj = event.dataTransfer.files[i];
ajax_file_upload(fileobj);
}}
function file_explorer() {
document.getElementById('selectfile').click();
document.getElementById('selectfile').onchange = function() {
fileobj = document.getElementById('selectfile').files[0];
ajax_file_upload(fileobj);
};
}
function init() {
request = new XMLHttpRequest();
var x = document.getElementById("imageSource");
}
function prepareData() {
let url = "ajax.php";
makeRequest( url, fileobj );
}
function ajax_file_upload(file_obj) {
request.onreadystatechange = alertContents;
var formData = new FormData();
formData.append('file', file_obj);
request.open('POST', url)
request.send(formData)
}
function alertContents() {
try {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
var reponse = JSON.parse( request.reponseText);
x.setAttribute("src", 'uploads' + reponse.text);
//document.getElementById("imageSource").src = reponse.text;
} else {
alert("Un problème est survenu au cours de la requête.");
}
}
}
catch( e ) {
alert("Une exception s’est produite : " + event.description);
}
}
</script>
</body>
</html>
And my PHP
<?php
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'. $_FILES['file']['name']);
$test = '{ "text":"uploads/'.$_FILES['file']['name'].'"}';
echo $_FILES['file']['name'] ;

ASP.NET how to push text from texbox using ajax into another page

I have this code where I want to post text to search.aspx from default.aspx using ajax, is this possible?
default.aspx
<div id="container">
<div id="search-container">
<input id="search" type="search" placeholder="look for Musics"/>
<ul></ul>
</div>
</div>
AJAX.js
$(document).ready(function() {
$('#search').bind('keyup', function() {
var searchTerm = jQuery.trim($(this).val());
if(searchTerm == '') {
$('#search-container ul').html('');
}
else {
//send the data to the database
$.ajax({
url: 'search.aspx',
type: 'GET',
data: { search:searchTerm },
beforeSend: function() {
$('#search-container ul').html('<li>Loading...</li>');
},
success: function(data) {
$('#search-container ul').html(data);
}
});
}
});
});
search.aspx
string term = //this is the part i want to store text from default.aspx
string connString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|mydb.mdb";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(connString))
{
OleDbCommand cmd = new OleDbCommand("SELECT title FROM news WHERE title LIKE '%'"+term+"'% ' ",conn);
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
if (results.Rows.Count != 0)
{
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
terms = reader[0].ToString();
searchbox.InnerText = terms;
}
}
}
}
So this is the code I have
I am unable to get text from default.aspx page to search.aspx
Try string term = Request["search"]

HTML5 input type="file" doesn't trigger handleFileSelect()

I have this JS code for uploading a .jpg file to firebase:
function handleFileSelect(evt) {
var f = evt.target.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var filePayload = e.target.result;
// Generate a location that can't be guessed using the file's contents and a random number
var hash = CryptoJS.SHA256(Math.random() + CryptoJS.SHA256(filePayload));
var f = new Firebase(firebaseRef + 'pano/' + hash + '/filePayload');
spinner.spin(document.getElementById('spin'));
// Set the file payload to Firebase and register an onComplete handler to stop the spinner and show the preview
f.set(filePayload, function() {
spinner.stop();
document.getElementById("pano").src = e.target.result;
$('#file-upload').hide();
// Update the location bar so the URL can be shared with others
window.location.hash = hash;
});
};
})(f);
reader.readAsDataURL(f);
}
$(function() {
$('#spin').append(spinner);
var idx = window.location.href.indexOf('#');
var hash = (idx > 0) ? window.location.href.slice(idx + 1) : '';
if (hash === '') {
// No hash found, so render the file upload button.
$('#file-upload').show();
document.getElementById("file-upload").addEventListener('change', handleFileSelect, false);
} else {
// A hash was passed in, so let's retrieve and render it.
spinner.spin(document.getElementById('spin'));
var f = new Firebase(firebaseRef + '/pano/' + hash + '/filePayload');
f.once('value', function(snap) {
var payload = snap.val();
if (payload != null) {
document.getElementById("pano").src = payload;
} else {
$('#body').append("Not found");
}
spinner.stop();
});
}
});
My js imports:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//cdn.firebase.com/v0/firebase.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/spin.js/1.2.7/spin.min.js"></script>
<script src="sha256.js"></script>
<script src="firepano.js"></script>
My html looks something like this:
<input type="file" accept="image/*" capture="camera" id="file-upload">
Of course this is just a piece, but somehow the js function isn't triggered when I select a file, only if I put the HTML code outside of my file in a separate file and leave only this input tag. Is there some other piece of code that can interfier in the selectfile function trigger?
Try this:
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="Upload">
</form>

Adding a loading text while an AJAX function is executing

I've been trying to add a loading text that would display while an AJAX function is being executed for a long while now, and all of my attempts (which includes using the ajaxStart and ajaxStop, among other things) haven't been working at all. Any help is appreciated!
Here is the webpage that the script in question is located on, if you want to see it in action. The way it works is that you enter in a url and the function will grab the meta tags of that URL.
Meanwhile, here is the relevant HTML, Javascript, and PHP:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Keywords Grabber</title>
<script src="ajax.js"></script>
<script>
function display(content) {
document.getElementById("displaydiv").innerHTML = content;
}
window.onload = function () {
document.getElementById("btn1").onclick = function () {
var url = document.getElementById("txt1").value;
doAjax("metatags.php", "url=" + url, "display", "post", 0);
}
}
</script>
</head>
<body>
http://<input type="text" id="txt1" value="" />
<input type="button" id="btn1" value="Get Keywords" />
<h3>Keywords Received:</h3>
<div id="displaydiv"></div>
</body>
</html>
JavaScript
function getXMLHttpRequest() {
try {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
return new ActiveXObject("Msml2.XMLHTTP");
}
}
catch(e) {
return new XMLHttpRequest();
}
}
function doAjax(url, query, callback, reqtype, getxml) {
var myreq = getXMLHttpRequest();
myreq.onreadystatechange = function () {
if (myreq.readyState == 4) {
if (myreq.status == 200) {
var item = myreq.responseText;
if (getxml == 1) item = myreq.responseXML;
eval(callback + '(item)');
}
}
}
if (reqtype.toUpperCase() == "POST") {
requestPOST(url, query, myreq);
} else {
requestGET(url, query, myreq);
}
}
function requestGET(url, query, req) {
var myRandom = parseInt(Math.random()*99999999);
if (query == '') {
var callUrl = url + '?rand=' + myRandom;
} else {
var callUrl = url + '?' + query + '&rand=' + myRandom;
}
req.open("GET", callUrl, true);
req.send(null);
}
function requestPOST(url, query, req) {
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(query);
}
PHP
<?php
$tags = #get_meta_tags('http://'.$_REQUEST['url']);
$result = $tags['keywords'];
if(strlen($result) > 0) {
echo $result;
} else {
echo "No keywords metatag is available.";
}
?>
something like this
<div id="loading" style="display:none;">loading</div>
Javascript
$('#loading').css('display', 'block');
$.post(url, {}, function(data){
$('#loading').css('display', 'none');
});

Reading a text file using Javascript

The following code should read the content of a text file which is in the current directory upon load, and display it on the html page. I tried modifying by my self. But it does not give an output. Is there an easier way to get this result using another method? or please help figure out what is wrong with this code?
<html>
<head>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
<script>
function startRead()
{
// obtain input element through DOM
var file = document.getElementById("\\file.txt").files[0]
if(file)
{
getAsText(file);
}
}
function getAsText(readFile)
{
var reader;
try
{
reader = new FileReader();
}catch(e)
{
document.getElementById('output').innerHTML =
"Error: seems File API is not supported on your browser";
return;
}
// Read file into memory as UTF-8
reader.readAsText(readFile, "UTF-8");
// Handle progress, success, and errors
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
function errorHandler(evt)
{
if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
{
// The file could not be read
document.getElementById('output').innerHTML = "Error reading file..."
}
}
//Start reading file on load
window.addEventListener("load", startRead() { }, false);
</script>
</head>
<body>
<pre>
<code id="output">
</code>
</pre>
</body>
</html>
Given below is the code which I modified to get the above code. My intention was. As I open the html file it would read the text file which is in the current directory and display the content.
<html>
<head>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8' >
<script>
function startRead()
{
// obtain input element through DOM
var file = document.getElementById("file").files[0];
if(file)
{
getAsText(file);
}
}
function getAsText(readFile)
{
var reader;
try
{
reader = new FileReader();
}catch(e)
{
document.getElementById('output').innerHTML =
"Error: seems File API is not supported on your browser";
return;
}
// Read file into memory as UTF-8
reader.readAsText(readFile, "UTF-8");
// Handle progress, success, and errors
reader.onload = loaded;
reader.onerror = errorHandler;
}
function loaded(evt)
{
// Obtain the read file data
var fileString = evt.target.result;
document.getElementById('output').innerHTML = fileString;
}
function errorHandler(evt)
{
if(evt.target.error.code == evt.target.error.NOT_READABLE_ERR)
{
// The file could not be read
document.getElementById('output').innerHTML = "Error reading file..."
}
}
</script>
</head>
<body>
<input id="file" type="file" multiple onchange="startRead()">
<pre>
<code id="output">
</code>
</pre>
</body>
</html>
Try this snippet, I just tried and it works :)!
Live Demo (With Input File)
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
var content = reader.result;
//Here the content has been read successfuly
alert(content);
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
<input type="file" id="fileInput">
Without Input File
Function
function readTextFile(file){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
And to test it
Test
Notice: I tried it, but it works only in firefox
<html>
<head></head>
<body>
<input type="file" id="openfile" />
<br>
<pre id="filecontents"></pre>
<script type="text/javascript">
document.getElementById("openfile").addEventListener('change', function() {
var fr = new FileReader();
fr.onload = function() {
document.getElementById("filecontents").textContent = this.result;
}
fr.readAsText(this.files[0]);
})
</script>
</body>
</html>
this code works
<script type="text/javascript">
document.getElementById("openfile").addEventListener('change', function(){
var fr= new FileReader();
fr.onload= function(){
document.getElementById("readfile").textContent=this.result;
}
fr.readAsText(this.files[0]);
})
</script>
<html>
<head>
<title>reading file</title>
</head>
<body>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
<input type="file" id="myFile">
<hr>
<textarea style="width:500px;height: 400px" id="output"></textarea>
<input type="file" id="myFile">
<hr>
<!--<div style="width: 300px;height: 0px" id="output"></div>-->
<textarea style="width:500px;height: 400px" id="output"></textarea>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener('load', function (e) {
output.textContent = e.target.result;
});
reader.readAsBinaryString(myFile);
}
});
</script>
</body>
</html>

Categories