How to show file upload status in Laravel? - javascript

I have a controller that takes a lot of data by file and inserts it into the database. How can I show the user some status about how much code is run.
For example, I want to show statuses like, "file upload was done", "data is being validated", "data is inserted" etc. My initial approach was to use the session.
I inserted something like the following in appropriate places on controllers.
..
..code for file upload
..
session()->put('_order_upload_status','file upload done');
..
..code for validation
..
session()->put('_order_upload_status','data is being validated');
Then on the front end, I ran a bit of js code to get the status periodically.
function intervalAction()
{
var intervalID = window.setInterval(getStatus, 500);
}
function getStatus()
{
var request = new XMLHttpRequest();
var url = '{{ route('order.upload.getStatus') }}';
request.open('GET',url,true);
request.onload = function(){
document.getElementById('percentageModalTextBox').innerHTML = this.response
};
request.send();
}
The url {{ route('order.upload.getStatus') }} does nothing more than to get the session data.
However, this approach is not working. I can get the correct session only after the file upload controller runs completely. So I am getting nothing for a long time and only the last status after everything is over.
How can I show the status update to the user?

Related

How to receive a PHP response in Javascript

I've been stuck on this for the past day and it feels like I am missing something.
My assignment is:
Create a php file register.php which allows users to input their Name, Last name, Username and Email(via an HTML form) and then do some server-side verification on this data.
This file would also serve as an html form where users could input the data.
For the Username input field I have to, on each keystroke, check if a user with that username already exists in my database.
This has to be accomplished using Javascript by sending a request to register.php with Ajax.
I know how to run the necessary query to search my database based on a certain username. That part is not a problem.
What I can't get to work is
using Javascript/Ajax to send a request to register.php
getting register.php to run a query based on the inputed username, since I don't know how to recieve the request
getting register.php to "return" a response without writing it out in the DOM
What I've tried so far:
let username= document.getElementById('username');
username.addEventListener('input', validateUsername);
function validateUsername(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText);
}
};
xhttp.open("POST", "../obrasci/registracija.php", true);
xhttp.send("username="+username.value);
}
this part works and I'm getting the whole HTML document back. I know that because the whole structure is being printed into the console.
now this is the part that I can't get to work. In PHP I've got this so far and I can't get the script to do anything with the username.
if( isset($_POST['username']) ){
json_encode($_POST['username']);
}
Edit: I forgot to add that this site needs to process the data sent with ajax dynamically(if that username is taken, mark the input as not okay until the user chooses a username that's not taken).
That might be a problem in the way I'm using this since the if in PHP only gets tested on first load?
Any help is appreciated.
First, you can check whether or not the request was sent as a POST request (opening register.php in your browser will be a GET request).
You can wrap your form handling by something like this
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// check if username exists
if (isset($_POST['username'])) {
echo 'username: ' . $_POST['username'];
die;
} else {
echo 'no username';
die;
}
}
change the code accordingly, use echo json_encode($data) to return your data in JSON format.
In your request, you might need to add the right header to tell PHP how to interpret the body sent with the request.
function validateUsername(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText);
}
};
// add this line
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp.open("POST", "../obrasci/registracija.php", true);
xhttp.send("username="+username.value);
}
Also, make sure you have the right naming. In your code example, you refer to your input as the variable username, but you add the event listener to kor_ime, I don't know if you updated something to english and forgot other parts of it for this question or if that is your actual code
let username= document.getElementById('username');
username.addEventListener('input', validateUsername); // here change kor_ime to username and update the function name, you can omit the extra function wrapper

Upload data to the db without stopping the loading of the site

I have a small problem, I created a data analysis system on my site. Everything works, only that every time I run the post to be able to insert the data in the db, it slows down the loading of the site a lot. I was wondering if it was possible to load the data in the database without stopping the execution of the site. For example, if I load and click on an item in the menu I would like it not to let me wait for the data to be entered in the db but to continue with the click I made on the menu item.
My code works this way.
I take the data that interest me with javascript and I post to a php page for data entry
Thank
I don't know if you are using AJAX calls to pass the value from frontend to PHP.
If not, try to use AJAX calls calling the PHP page for data entry and passing the values you want to store. AJAX calls are asynchronous so JavaScript does not have to wait for the server response.
This is an example of AJAX call:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "data_entry.php?value1=exampleOfValueBeingStored1&value2=exampleOfValueBeingStored2", true);
xhttp.send();
}
in the REST paradigm if you need to update values you should use PUT or POST instead of GET. GET should be used only when you want retrieve values already inserted inside database for example.

JS counter write to database

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?
To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX
You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

How to compare the two OrderIds in Google Wallet?

I am implementing Google Wallet for Digital Goods in a website, using PHP and HTML/JavaScript. I have achieved a successful Wallet transaction in the sandbox setting. So far, so good.
Now, in order to ensure the purchase is a secure transaction, I want to check whether the orderId that comes back in the successHandler is equal to the orderId received via a POST from Google in my postback file on the server.
I know a reasonable bit about PHP, less so about Javascript. After having studied all Google Wallet entries in StackOverflow and after having read over and over again the Google Wallet Merchant Setup pages, I still cannot figure out the proper code to compare the orderId coming from the successHandler and the orderId from the postback file. It seems to me that the successHandler's orderId (which I am guessing can be written as result.response.orderId which I have seen in other StackOverflow answers) is defined in Javascript, while the one from the postback file (which I call here postback-orderId) is defined in PHP.
How can you compare the two? One is a Javascript variable, the other a PHP variable.
I guess the best place to compare these variables is in the successHandler function. But how do I get a PHP variable from the postback file (called $orderId in that file) into a Javascript function which is used in another file?
I show what I have so far as my PURCHASE file and what I have as my POSTBACK file.
PURCHASE FILE
<?php
include ('sessionstart.inc');
require_once 'generate_token.php';
echo "
<!DOCTYPE html>
<html>
<head><meta name='viewport' content='width=device-width, initial-scale=1,maximum-scale=1'>
<title>Digital Goods Application</title>
<script src='https://sandbox.google.com/checkout/inapp/lib/buy.js'></script>
<script type='text/javascript'>
//Success handler
var successHandler = function(result){
if (result.reponse.orderId == postback-orderId) {
if (window.console != undefined) {
console.log('Purchase completed successfully.');
}
}
}
//Failure handler
var failureHandler = function(result){
if (window.console != undefined) {
console.log('Purchase did not complete.');
}
}
function purchase(jwt_value) {
runDemoButton = document.getElementById('runDemoButton')
google.payments.inapp.buy({
'jwt': jwt_value,
'success': successHandler,
'failure': failureHandler
});
return false;
}
</script>
</head>
<body>
<div>
<p>Buy 5 Search Credits to continue searching The Clock Register.</p><br />
<button id='runDemoButton' value='buy' class='buttons' onclick='purchase(\"$jwtToken\");'><b>Buy</b></button>
</div>
</body>
</html>";
?>
POSTBACK FILE
<?php
include ('sessionstart.inc');
include_once ('JWT.php');
$encoded_jwt = $_POST['jwt'];
$decodedJWT = JWT::decode($encoded_jwt,"mySecretKey");
$orderId = $decodedJWT->response->orderId;
header("HTTP/1.0 200 OK");
echo $orderId;
?>
</body>
</html>
Any help much appreciated!
You have to remember that the rendering of your page (and the buy action) happen long before the postback is dispatched / received by your server, as such, you can not have the postback-orderID in your page. You will have to do the following:
Your postback url target file / script should log the data received on your server (in a file or database).
You will need to write another php file / script on your server that can retrieve data from the logs in 1 above and does the comparison to check whether the orderID in the successHandler has been logged.
The success handler will have to make a call to the script in 2 above with, at least, the orderID as a parameter. (do not worry about the ajax call, it is simply javascript)
This may seem convoluted and long but can be achieved in less than 20 lines of code (both php and javascript / ajax).
EDIT
1. Updated postback.php to include logging
<?php
require_once 'JWT.php';
$encoded_jwt = $_POST['jwt'];
$decodedJWT = JWT::decode($encoded_jwt, $sellerSecret);
$orderId = $decodedJWT->response->orderId;
header("HTTP/1.0 200 OK");
echo $orderId;
$logfile = "logfile.txt";
if (!file_exists($logfile)) {
touch($logfile);
chmod($logfile, 0777);
}
$orderIDS = file($logfile); //reads file into array
$orderIDS[] = $orderId; //append new orderID to array
file_put_contents($logfile, $orderIDS); //save the new array to file
?>
EDIT 2
second script IDSearch.php to search for orderIds
<?php
$orderSearch = $_GET['orderID'];
$logfile = "logfile.txt";
if (file_exists($logfile)) {
$orderIDS = file($logfile); //reads file into array
echo (in_array($orderSearch, $orderIDS)); // either true or false is returned
} else {
echo 'Error';
}
?>
EDIT 3
Finally, amending your successhandler to call the IDSearch.php script
var successHandler = function (result) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (window.console != undefined) {
console.log(xmlhttp.responseText);
}
}
}
xmlhttp.open("GET", "IDSearch.php?orderID=" + result.reponse.orderId, true);
xmlhttp.send();
}
PS. In the handler, make sure you have the absolute path to the web resource of IDSearch.php
Am not a PHP developer so this is more "conceptual" than specific -
The overall idea is that you would persist the data you received from the (server side) POST from Google (aka "the PHP variable" you received at your postback url) somehow - e.g. a database.
You then have options on what to do next (to compare) -
perhaps an ajax call in your success handler to your server (that obtains the persisted data to) verify/compare the "javascript variable/orderId" with the "Php variable/orderId", before doing x
perhaps redirect in your success handler and send the "javascript orderId" as some value (query string, POST data, etc.) to a target that does the verification/comparison same as above (from server/db), and then do x
So its about persisting the data for later verification.
Hth....
Update (above disclaimer applies) :)
I set $orderId in the POST-back file into a SESSION as follows: $_SESSION['orderid'] = $orderId; However, when I check on the value of $_SESSION['orderid'] it is empty.
If I understood correctly, you're setting a Session Variable from Google's server-side Postback which means the request/session isn't "tied" to the browser/client. It was a server side POST - the browser, where the payment process is happening has no knowledge of it - it wasn't involved in the postback at all (the "client" in that case was some Google machine).
In other words, the browser has no "knowledge" of that (separate/server-side) "session", it either has no "sessionID" (cookie) nor one that would match (remember it was "some Google machine" that made the request when you set a session variable)
Hth....

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources