Displaying each data line by line during AJAX CSV File Upload - javascript

I am using papaparse, Jquery AJAX, PHP and have successfully finished the parsing of csv, However, I would like to display data while my CSV file is being uploaded.
Here is a bit of my code;
var xhr_file = null;
$('#fileVariants').change(function(e){
var file = e.target.files[0];
splitFileName = file['name'].split(".");
fileType = splitFileName.slice(-1)[0];
if(fileType != 'csv')
{
$('.error-message').html('<br /><div class="notification is-warning">Only CSV file extension is allowed!</div><br />');
}
else
{
Papa.parse(file, {
header: false,
dynamicTyping: true,
skipEmptyLines: true,
complete: function(results, file) {
file_arr = results.data;
file_chunk = results.data;
$('#uploadVariantsBtn').attr('disabled', false);
}// End complete: function(results, file)
});
}
});
$(function(){
$('#uploadVariants').submit(function(e){
if($('#fileVariants').val() == '')
{
$('.error-message').html('<div class="alert alert-danger" role="alert">File is required!</div><br />');
return false;
}
var method = $(this).attr('method');
var url = $(this).attr('action');
var parameters = 'row=' + JSON.stringify(file_chunk);
xhr_file = $.ajax({
type : method,
url : url,
data : parameters,
cache : false,
async: false,
dataType : "script",
beforeSend: function(xhr){
$('#uploadVariantsBtn').attr('disabled', true);
$('.error-message').html('<br /><div class="notification is-info has-text-centered"><img width="110" src="{{ asset("img/loading.gif") }}" title="Uploading" /></div>');
$('.error-message').show();
if (xhr_file != null)
{
xhr_file.abort();
}
}
}).complete(function(data){
$('#uploadVariantsBtn').attr('disabled', false);
$('.error-message').html('<div class="alert alert-success" role="alert">Product Variants has been updated!</div><br />');
// $('.show-results').html('<h3>Product Variants have been updated!</h3>');
}).fail(function(jqXHR, textStatus){
console.log('Request failed: ' + textStatus);
});
return false;
e.preventDefault();
});
});
So instead of showing a progress bar in the upload, I would like to display each data line by line to show the progress.
For Example :
Product Data 1 has been successfully updated!
Product Data 2 has been successfully updated!
Product Data 3 already exist!
Product Data 4 has been successfully updated!
Product Data 5 has been successfully updated!
Is there any way to do that using PHP, Javascript, AJAX?

You uploaded all of your data at once, then the server process your data, in completion it returns the result. You actually want the long running process's status of every single row process data.
For that, you actually need a seperate php file and ajax call. Your original php file should update the status in session or db, like below,
session_start();
$_SESSION['status'] = $status;
session_write_close();
Note that, this piece of code should be inside the loop of processing data. You should start() and close() this particular session because same session cannot be opened in other process, as we need to access this session from 2nd php file which looks like below,
ob_start();
session_start();
session_write_close();
$output = array();
$output['status'] = $_SESSION['status'];
echo json_encode($output);
Now the server side code is okay, you need to query the 2nd php with regular interval to get the processing status,
var timeout = setInterval('showUpdate()', 1000);
function showUpdate(){
$.get( "2ndPhp.php", function( data ) {
var returnData = data.status;
if (returnData.length>0){
// This is server returned update data, you can show this or convert it to
//progressbar
}
}, "json");
}
When you main process ends, you can close this loop by closing this interval.
.complete(function(data){
clearInterval(timeout);
$('#uploadVariantsBtn').attr('disabled', false);
$('.error-message').html('<div class="alert alert-success" role="alert">Product
Variants has been updated!</div><br />');
// $('.show-results').html('<h3>Product Variants have been updated!</h3>');
}).fail(function(jqXHR, textStatus){
console.log('Request failed: ' + textStatus);
});

Related

How to run a php file with javascript in html

I have a html with some javascript in in, now I want to run another php-file (test.php) without showing or opening this file. It's part of a loop and I tried:
for(i = 1; i < length; i++){
var bname = table.rows[i].cells.item(0).innerHTML;
var bvalue = table.rows[i].cells.item(1).innerHTML;
location.href = "test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
}
But this will redirect the current location and runs only once...
I also tried to use:
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","test.php?account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue);
xmlhttp.send();
But that seems not to work.
I also found the hint to use ajax, but I never used it and don't know how to pass my variables to test.php.
Thanks for your help!
You can do using ajax,
$.post("test.php",
{
account: account,
key: key,
memo:memo,
bname:bname,
bvalue:bvalue
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
use ajax to send data from javascript to a php file
vars="account="+account+"&key="+key+"&memo="+memo+"&bname="+bname+"&bvalue="+bvalue;
var ajaxhr = new XMLHttpRequest();
var url = "test.php";
ajaxhr.open("POST", url, true);
ajaxhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxhr.onreadystatechange = function() {
if(ajaxhr.readyState == 4 && ajaxhr.status == 200) {
var return_data = ajaxhr.responseText;
}
}
ajaxhr.send(vars);
I am posting this for a detailed answer to help PHP and Javascript side.
I would use jQuery + AJAX. Reference: http://api.jquery.com/jquery.ajax/
Ajax is great for sending data to php, reading data from php etc..
Please take time to look at my reference to read up on how it all works for future knowledge!
Lets get into the code!
Ajax (Javascript - Client Side):
var memoData = "Today is beautiful"; //Varible passed for ajax data
$.ajax({
url : '/LocationToTestPHP/test.php', //Location to PHP File
cache: false,
type: 'POST', //Type of method - Remove this line for GET if required
data: {account: "Welcome", key: "ValueHere", memo: memoData, bname: "ValueHere", bvalue: "ValueHere"} //Data to send to PHP
}).done(function(data)
{
//We check if PHP sent us back the correct data required here.
if(data == "Success")
{
alert("Success! Data returned is: " + data);
}
else
{
alert("Error! We didnt get correct data back. Data: " + data);
}
});
Please note, i provided a variable into ajax data for memo, this is
also possible.
PHP (Server Side) - test.php:
<?PHP
//Check for our value and return data
if($_POST['account'] == "Welcome") //Check if account has Welcome passed in..
{
echo "Success";
}
else //Welcome is not provided
{
echo "Account did not equal to Welcome :(";
}
?>
I quickly typed this up so hopefully you get the correct idea! Any help required, comment below :)

how can I trigger javascript css action?

I have a memory game code, using javascript, php and css.
I would like to register somehow the event when the game is finished by php so that I can save the results in database.
In other words I would like to place php code inside <div id="player_won"> </div> and trigger that winning event properly.
css
#player_won{
display: none;
}
javascript
$(document).ready(function(){
$(document).bind("game_won", gameWon);
}
function gameWon(){
$.getJSON(document.location.href, {won: 1}, notifiedServerWin);
var $game_board = $("#game_board");
var $player_won = $("#player_won");
$game_board.hide();
$player_won.show();
$game_board = $player_won = null;
};
You'll want to create an ajax call that sends some information from the page and tells the php file below if the player has won or lost. After which you can deal with the logic needed for the player inside foo.php and send back Json to the success function inside the ajax call and update your page accordingly.
index
$(document).ready(function () {
//look for some kind of click below
$(document).on('click', '#SomeId', function () {
//Get the information you wish to send here
var foo = "test";
$.ajax({
url: "/foo.php",
type: 'POST',
cache: false,
data: {Info: foo},
dataType: 'json',
success: function (output, text, error)
{
//here is where you'll receive the son if successfully sent
if(ouput.answer === "yes"){
$("#player_won").show();
} else {
// Do something else
}
},
error: function (jqXHR, textStatus, errorThrown)
{
//Error handling for potential issues.
alert(textStatus + errorThrown + jqXHR);
}
})
})
});
foo.php
<?php
if(isset($_POST['Info'])){
//figure out if what was sent is correct here.
if($_POST['Info'] === "test"){
$data['answer'] = "yes";
echo json_encode($data);
exit;
} else {
// do something else
}
}
?>

Exchange data php javascript

I have to select a file locally and use it in a python script.
I can't get the filename in order to have it in my ajax script that i use to call a php function.
This is my javascript, called onclick over Ok button:
function myAjax () {
$.ajax( { type : 'POST',
data : {},
url : 'action.php',
success: function ( data ) {
alert( data );
},
error: function (xhr, status, error) {
// executed if something went wrong during call
if (xhr.status > 0) alert('got error: ' + status); // status 0 - when load is interrupted
},
complete: function (data) {
setImg();
}
});
}
This is the php script used to call python script:
<?
function bb(){
$out = shell_exec( 'python heatmap.py');
echo "ok";
$fp = fopen('log.txt', 'w');
fwrite
($fp, $out);
fclose($fp);
}
bb();
?>
I have to take filename from Browse button and send it to ok button, where the python is called.
What is the correct way to exchange data from input="file" html, javascript and php?
I'm making a lot of assumptions here as the question is not entirely clear...
But presumably you're wanting the name of a file that has been selected from the OS. In JS you can do this using the following.
var fileName, oForm = document.getElementById('my-file');
oForm.onchange = function(){
fileName = this.files[0].name;
}
Then in your AJAX call, add the fileName variable to your data property.
data : {"filename":fileName},
And then in your PHP access it via the $_POST variable. So...
echo $_POST['filename'];

Upload Avatar To Server Using AJAX

I have looked into the best way to do this and keep getting conflicting information and advice on the various demonstrations.
My code is as follows...
html
<img src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="avatar-uploader" id="avatar-uploader" style="display: none;" />
javascript
$('input[type=file]').on('change', function(){
$.ajax({
url: "/ajax/upload-new-avatar.ajax.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert("Success");
}
});
});
PHP: /ajax/upload-new-avatar.ajax.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$sourcePath = $_FILES['avatar-uploader']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "".$_FILES['avatar-uploader']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
I'm sure there is something simple that I am missing here and i'm going to feel pretty stupid afterwards but could someone explain to me why the image isn't being uploaded to the server and saved in the AJAX directory for further processing.
What I need it to do is when the user clicks on the "change" hyperlink below the image it opens a file upload dialog (working), once an image has been selected it automatically uploads to the server over an AJAX connection (possibly working, logging shows the PHP file is being triggered), and then the image file needs to be saved in the AJAX directory to be further processed later in the code for it to be uploaded to the avatar service.
Thanks in advance.
Have managed to get it working...
Here is my amended code...
Javascript
$('input[type=file]').on('change', function(event){
files = event.target.files;
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
$("#avatar-status").text("Loading new avatar...");
$("#avatar").css("opacity", "0.4");
$("#avatar").css("filter", "alpha(opacity=40);");
//Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value) {
data.append(key, value);
});
$.ajax({
url: '/ajax/upload-new-avatar.ajax.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
if(typeof data.error === 'undefined') {
//Success so call function to process the form
//submitForm(event, data);
$("#avatar-status").text("Powered by Gravatar");
$("#avatar").css("opacity", "");
$("#avatar").css("filter", "");
} else {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
});
});
PHP
session_start();
require_once("../libraries/logging.lib.php");
new LogEntry("AJAX Upload Started - UploadNewAvatar", Log::DEBUG, "AvatarUpload");
sleep(3);
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = '../tmp/';
foreach($_FILES as $file) {
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) {
$files[] = $uploaddir .$file['name'];
new LogEntry("UploadNewAvatar - Upload Successful", Log::DEBUG, "AvatarUpload");
} else {
$error = true;
new LogEntry("UploadNewAvatar - Errors Occured", Log::ERROR, "AvatarUpload");
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
new LogEntry("UploadNewAvatar - Form was submitted successfully", Log::DEBUG, "AvatarUpload");
}
echo json_encode($data);
HTML
<img id="avatar" src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span id="avatar-status" class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="upfile" id="upfile" style="display: none;" />

From a running PHP Code, how to update status in DIV tag

I have a web Page, in which i an downloading data one after another in a loop. After each data download is finished i want to update the status to a DIV tag in the Web Page. How can i do this. Connecting to server and downloading data via php code and the div tag is within the .phtml page.
i have tried
echo "
<script type=\"text/javascript\">
$('#tstData').show();
</script>
";
But the echo statement update will happen at the end only. Refreshing of DIV tag need to happen at the end of each download.
Use jQuery load()
$('#testData').load('http://URL to script that is downloading and formatting data to display');
$("#save_card").submit(function(event) {
event.preventDefault();
var url = "card_save.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#save_card").serialize(), // serializes the form's elements.
success: function(data)
{
console.log(data);
if(data.msg=="success")
{
$("#submit_msg").html("Thank You !!!");
console.log("Record has been Inserted Successfully!!!");
}
else
{
$("#submit_msg").html(data.er);
console.log("There Is Some Error");
}
$("#submit_msg").show();
setTimeout(function() { $("#submit_msg").hide(); }, 5000);
$("#save_card").get(0).reset();
}
});
return false; // avoid to execute the actual submit of the form.class_master
});
Use This Ajax function to call PHP function to get data. Here
#save_card = Id of the form that you want to submit.
url = action for the form or the location to the php file from where your data is coming.
data: $("#save_card").serialize() = it is sending all the data of the form in serialize form. Data can be created manually to do this repalce this line with data: {'name':name,'year':year}
function(data) = here data is returned from the php code in json formate.
data.msg = It is a way to access different field from data.
$user_email = $_REQUEST['user_email'];
$cat_id = $_REQUEST['category'];
$title = $_REQUEST['title'];
$country = $_REQUEST['country'];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO project(title, user_email, cat_id, country, start_date) VALUES ('$title','$user_email','$cat_id','$country', '$date')";
if (mysql_query($sql)) {
$project_id = mysql_insert_id();
echo json_encode(array('project_id' => $project_id, 'msg' => 'Successfully Added', 'status' => 'true'));
} else {
echo json_encode(array('msg' => 'Not Added', 'status' => 'false'));
}
PHP code to send data in json format

Categories