how to get filename from php to ajax xhttp js - javascript

Here is js and html
I want to get filename in p tag. How to do this?
I tried with above code but still not working.
<div>
<p id="filename"></p>
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
<hr><br><br>
<script>
function uploadFile() {
var files = document.getElementById("file").files;
if(files.length > 0 ){
var formData = new FormData();
formData.append("file", files[0]);
var xhttp = new XMLHttpRequest();
// Set POST method and ajax file path
xhttp.open("POST", "includes/upload.php", true);
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
var filenamenew = this.filenamenewText;
document.getElementById("filename").innerHTML = filenamenew;
var input = document.getElementById("btn_uploadfile");
var a = document.getElementById("links");
if(response == 1){
alert("Upload successfully.");
input.value = "Uploaded";
input.disabled = 'true';
var input = document.getElementById("file");
input.disabled = 'true';
}else{
alert("File not uploaded.");
}
}
};
// Send request with data
xhttp.send(formData);
}else{
alert("Please select a file");
}
}
</script>
Php code here
<?php
if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES["file"]["name"];
$newfilename = round(microtime(true)) . '_original_' . $filename ;
// Location
$location = '../uploads/'.$newfilename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid extensions
$valid_ext = array("apk","aab","ipa");
$response = 0;
$filenamenew = 0;
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
$filenamenew = $filenamenew;
}
}
echo $response;
exit;
echo "<p>$filenamenew<p>";
exit;
}
?>
In this code it says in p tag is undefined

Related

XMLHttpRequest stream crashing when uploading large files (~1 GB)

I'm trying to make an online file manager for another project with friends, and when uploading files bigger than 1GB, the process either crashes (firefox), or succeeds but the received file weighs 0 bytes (chromium).
JS:
function uploadFile(fileInputId, fileIndex) {
//send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
//take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onloadend = function(event) {
ajax = new XMLHttpRequest();
//send data
ajax.open("POST", 'uploader.php', true);
//all browser supported sendAsBinary
XMLHttpRequest.prototype.mySendAsBinary = function(text) {
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0)
for (var i = 0; i < text.length; i++) ui8a[i] = (text.charCodeAt(i) & 0xff);
if (typeof window.Blob == "function") {
var blob = new Blob([data]);
}else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}
this.send(blob);
}
//track progress
var eventSource = ajax.upload || ajax;
eventSource.addEventListener('progress', function(e) {
//percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.mySendAsBinary(event.target.result);
}
}
PHP:
//mysql login
$conn = new PDO([Redacted]);
//file info
$fileName = $_COOKIE['fname'];
$targetDir = "uploads/";
$targetFile = $targetDir.$fileName;
$fileNameRaw = explode('.', $fileName)[0]; //file name with no extension
$tempFilePath = $targetDir.$fileNameRaw.'.tmp';
if (file_exists($targetFile)) {
echo '<font color="red">Un fichier du même nom existe déjà.</font>';
exit();
}
//read from stream
$inputHandler = fopen('php://input', 'r');
//create temp file to store data from stream
$fileHandler = fopen($tempFilePath, 'w+');
//store data from stream
while (true) {
$buffer = fgets($inputHandler, 4096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
break;
}
fwrite($fileHandler, $buffer);
}
//when finished
rename($tempFilePath, $targetFile);
chmod($targetFile, 0777);
echo 'Fichier envoyé avec succès !';
$bddInsert = $conn->prepare('INSERT INTO files(nom, chemin) VALUES(?,?)');
$bddInsert->execute(array($fileName, $targetFile));
in my php.ini,
max_execution_time is set to 0
max_input_time to -1
and my post max and upload max sizes are at 4G
I'm using apache2
You should not be reading the file with the fileReader if you don't need it.
Just send the file (blob) directly to your ajax request and avoid the FileReader
function uploadFile (fileInputId, fileIndex) {
// Send file name
try {
var fileName = document.getElementById('fileUploader').files[0].name;
}
catch {
document.getElementById('uploadStatus').innerHTML = `<font color="red">Mettre un fichier serait une bonne idée.</font>`;
return false;
}
document.cookie = 'fname=' + fileName;
// Take file from input
const file = document.getElementById(fileInputId).files[fileIndex];
const ajax = new XMLHttpRequest();
// send data
ajax.open("POST", 'uploader.php', true);
// track progress
ajax.upload.addEventListener('progress', function(e) {
// percentage
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
document.getElementById('uploadStatus').innerHTML = `${percentage}%`;
});
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
document.getElementById('uploadStatus').innerHTML = this.responseText;
}
}
ajax.send(file)
}

How do I send a value from Javascript to PHP that will not be changed?

I have function that is running multiple times and executing a PHP file. I do, however, want to make sure the functions does not interfere with each other.
for(int i = 0; i<5; i++){
functionName(i)
}
function functionName(number){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
var PageToSendTo = "phpFile.php?";
var MyVariable = number;
var VariablePlaceholder = "name=";
var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;
xhttp.open("GET", UrlToSend, true);
xhttp.send();
}
This is how my code looks so far, how do I change it so that the next iteration of the function does not effect the previous one?
phpFile.php
<?php
require '../notWebsite/dbh.php';
session_start();
$variable = $_GET['name'];
$sqlInsertClass = "INSERT INTO class (className) VALUES (?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sqlInsertClass)) {
header("Location: ../Website.php?error=InsertError");
exit();
} else {
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
exit();
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>

how to force the browser to run the javascript every time it called

Dears
I called a javascript function on onload body
<body onload="loadLeads()">
This function loads a leads information from database and display it in a table.
The problem is when the user press on delete button to delete a lead from the table. the function runs correctly and delete the lead from the database. BUT although the deletelead function relaoad the page which calls loadLeads() on load the page which should display the new leads without the deleted one. BUT the deleted one display again! although it deleted from the database!!
how can I run it correctly??
I should delete the cache of the browser each time to force the code runs correctly!!
how can I do it please?
this is the javascript code for delete
function deleteLead(id)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
location.reload();
}
}
xmlhttp.open("GET", "deletelead.php?id="+id, true);
xmlhttp.send();
}
This is the script calling in the HTML
<script src="https://example.net/js/loadLeads.js?version=' + Math.floor(Math.random() * 100) + '"\><\/script>'"></script>
This is the loadleads function javascript
function loadLeads()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
LeadsInfo = JSON.parse(this.responseText);
LeadsInfoCount = LeadsInfo.length;
DrawLeadsTable();
}
}
xmlhttp.open("GET", "LoadLeads.php", true);
xmlhttp.send();
}
This is the LoadLeads.php
<?php
require "conn.php";
$SelectSQL = "SELECT * FROM leads";
$result = $conn->query($SelectSQL);
$ECount = $result->num_rows;
if ($ECount != 0 )
{
$FinalArr = array();
$count =0;
while($row1 = $result->fetch_assoc())
{
$id = $row1["id"];
$name = $row1["name"];
$email = $row1["email"];
$mob = $row1["mob"];
$country = $row1["country"];
$comefrom = $row1["comefrom"];
$time = $row1["time"];
$qulified = $row1["qulified"];
$landingpage = $row1["landingpage"];
$myArr = array($id,$name,$email, $mob,$country,$comefrom,$time,$qulified,$landingpage);
$FinalArr[$count] = array();
$FinalArr[$count] = $myArr;
$count++;
$UserData = json_encode($FinalArr,JSON_UNESCAPED_UNICODE);
}
}
mysqli_close($conn);
echo $UserData;
?>
Add this before the xmlhttp.send();
xmlhttp.setRequestHeader("Cache-Control", "no-cache, no-store, must-revalidate");

How to send String from text area to php via js

I am trying to get the string value from a textarea in js and send it to my php file. but when i check the value of the variable that receives the string it returns "". however every other value is received.
js file
$(document).ready(function () {
$("#newTestApprove").on("click", function(e) {
$testimonial = escape(document.getElementById("testimonialArea").value);
$client = document.getElementById("client").value;
$event = document.getElementById("event").value;
$status = "submitted";
if ($testimonial.length === 0)
{
alert("Testimonial Field is left empty");
}else
if ($client.length === 0)
{
alert("Client Field is left empty");
}
else if ($event.length === 0)
{
alert("Event Field is left empty");
} else{
obj = {"status":$status, "client":$client, "event":$event, "testimonial":$testimonial};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "Successful"){
$('#newTestimonialModal .modal-body').html("Your Testimonial has been Submitted");
$("#newTestApprove").remove();
}
}
};
}
xmlhttp.open("POST", "../php/postTestimonial.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
xmlhttp.send("x=" + dbParam);
});
});
php file
<?php
$obj = json_decode($_POST["x"], false);
$testimonial = $obj->testimonial;
echo $testimonial;
?>
When i echo $testimonial it returns ""
please assign variable in javascript as
var testimonial=document.getElementById("testimonialArea").value;
instead of
`$testimonial=escape(document.getElementById("testimonialArea").value);
please try below `eg:
<html>
<body>
Address:<br>
<textarea id="myTextarea"></textarea>
<p>Click the button to alert the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var testimonial = document.getElementById("myTextarea").value;
document.getElementById("demo").innerHTML = testimonial;
var obj = {"testimonial":testimonial};
var dbParam = JSON.stringify(obj);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ajax_info.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname="+dbParam);
}
</script>
</body>
</html>
Php file ->ajax_info.php
<?php
$obj = json_decode($_POST["fname"], false);
$testimonial = $obj->testimonial;
echo $testimonial;
?>

New variable ajaxObj does not work

For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.

Categories