I have a form which has a Date From and To Date selector then a generate button, upon clicking generate button, an excel file will be the output. Question how and where do I put the loading script in my code given I'm not using ajax but rather:
$("#btnReport1").click(function() {
var page = 'export-report1?from='+$("#fromDateAll").val()+'&to='+$("#toDateAll").val();
return window.location = page;
});
And my route
Route::get('export-report1', 'ReportController#exportReport1');
function
public function exportReport1()
{
$from = Input::get('from');
$to = Input::get('to');
$query = "SELECT id, phone FROM qcv.forms WHERE calldatetime >= '$from' AND calldatetime <= '$to' ORDER BY id ASC ;";
// $query = "SELECT a.id as form_id, a.phone, b.metrics_id, b.response, c.metrics_name, c.description, c.question
// FROM forms a
// INNER JOIN forms_responses b ON a.id = b.form_id
// INNER JOIN metrics c ON c.id = b.metrics_id LIMIT 10";
$phone = DB::connection('mysql')->select($query);
if(!empty($phone))
{
Excel::create('Laravel Excel', function($excel) use ($phone) {
return $excel->sheet('Excel sheet', function($sheet) use ($phone) {
$sheet->setOrientation('landscape');
$sheet->cell('A9', 'KEY QUALITY METRICS');
$sheet->cell('B9', 'DESCRIPTIONS');
$sheet->cell('C9', 'ASSESSMENT QUESTION');
$sheet->cells('A9:C9', function($cells) {
$cells->setFontWeight('bold');
$cells->setFontColor('#DF013A');
});
$metrics = Metric::all();
$metric_start = 10;
$start = "D";
$count = 10;
foreach ($phone as $key => $value2) // Populate Phone Numbers Horizontally
{
$sheet->cell($start.'9', $value2->phone);
// This will fill the responses for each number
foreach ($metrics as $key => $value)
{
$responses = FormResponses::where('form_id', '=', $value2->id)->where('metrics_id', '=', $value->id)->get();
$sheet->cell($start.$count, $responses[0]->response);
$sheet->cell('C'.$count, $value->question);
$sheet->cell('B'.$count, $value->description);
$sheet->cell('A'.$count, $value->metrics_name);
$count++;
}
$start++;
$count = 10;
}
});
})->export('xls');
}
else
{
return "No records found.";
}
}
Related
If you want to see the part where I tried AJAX, go look down below. It completely messed up the page and I'm stuck on how to do this. I've got some code here:
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id='$id'";
$INFO=mysqli_query($conn, $sql);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
};
Bets.prototype.doubleDown = function() {
this.pot -= this.bet;
this.bet += this.bet;
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.disableDeal = function () {
$('#button-deal').addClass('disabled');
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#button-deal').removeClass('disabled');
} else {
notEnoughChips();
}
};
First part is php second part js. I have an int value in my database called riskcoin. this.pot contains that riskcoin value (//Bets object) and shows itin another php file in a paragraph with id="pot".
When an image is clicked another function ads an amount to the bet depending on the picture (for example 5).
Now my question: after the line this.updateAmounts(); it executes
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
Now my question would be if I could update the riskcoin value in my database with an update query after this function with the current this.pot value? It should show live updates without page refreshes. I've read about AJAX so I tried something like this:
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
window.history.pushState('page2', 'Title', '?coins=' + this.pot);
$(document).ready(function(){
var url = window.location.href;
var params = url.split('?coins=');
var id = (params[1]);
$("#button-deal").click(function(){ $.ajax({
type:"POST",
url:"blackjackgame.php",
data:{id:id},
success:function(result){
$("#pot").html(result);
}
});
});
});
};
But it for some reason when I click on the deal button (#button-deal) it shows up my login page in the middle of the page under all the other stuff, console gives me: GET http://riskybusiness.nglyceum.eu/games/login.css net::ERR_ABORTED 404 (Not Found)jquery-3.1.1.js:5921
PHP and Javascript execute in different contexts. PHP on the server, Javascript on the client (browser). Keep your PHP code and Javascript separate. Since PHP executes first on the server, you can embed PHP output into your HTML/Javascript/CSS—BEFORE—it is sent to the browser.
One problem you have with your code is intermingling PHP and Javascript, such as:
<?php
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
The PHP (only) gets processed on the server, and this text is sent to the client:
riskcoin: 100<br>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = 100;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
Also, this $("#button-deal").click(function(){ in your code adds a click event handler to your button. The problem is, you're not adding this event handler until addBet() is executed, which then executes updateAmount(). Not only don't wait, but the handler is added each time addBet() is executed. Instead add the event handler on page load.
I've separated the various code components into server-side execution and client-side execution contexts, and properly connected them to each other:
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = 100; // <?=$riskcoin?>;
this.bet = 0;
$('#bet span').text('$' + 0);
$('#pot span').text('$' + this.pot);
$('#deal button').addClass('disabled');
}
// Bets methods
Bets.prototype.updateAmounts = function() {
$('#bet span').text('$' + this.bet);
$('#pot span').text('$' + this.pot);
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#deal button').removeClass('disabled');
} else {
notEnoughChips();
}
};
// add the click event handler on page load
document.querySelector("#deal button").addEventListener("click", evt => {
$.ajax({
type: "POST",
url: "deal.php", // <-- post data to separate PHP file, see PHP file below
data: {bet: bets.betAmount()},
success: function(result) {
const win = (result > bets.pot)? " (won)": " (lost)";
bets.pot = result;
bets.bet = 0;
$("#pot span").text('$' + bets.pot + win);
$('#bet span').text('$' + bets.bet);
$('#deal button').addClass('disabled');
}
});
});
document.querySelectorAll("#bet button").forEach(btn => {
btn.addEventListener("click", evt => {
bets.addBet(parseInt(evt.target.textContent));
});
});
function notEnoughChips() {
alert("Not enough chips.");
}
// mock ajax, remove in real world
$.ajax = (function () {
return function (params) {
if (Math.random() < 0.5) {
params.success(bets.pot + (params.data.bet * 2));
} else {
params.success(bets.pot);
}
};
}());
.disabled {
cursor: not-allowed;
pointer-events: none;
color: #c0c0c0;
background-color: #ffffff;
}
<!-- uncomment in the real world
<?php
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id=?"; // <-- use prepared statements
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
?>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="pot">Pot: <span><?=$riskcoin?></span></div>
<div id="bet">Bet: <span>0</span> <button>+5</button><button>+10</button><button>+15</button><button>+20</button></div>
<div id="deal"><button>Deal</button></div>
deal.php (The JQuery ajax function POSTs to this file.)
<?php
// this file called in JQuery ajax function found in "#deal button" "click" handler
$id = $_SESSION["id"];
$bet = $_POST["bet"];
$sql = "SELECT riskcoin FROM klanten WHERE id= ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
// random win or lose
$riskcoin += ((bool)random_int(0, 1))? ($bet * 2): (-1 * abs($bet));
$sql = "UPDATE klanten SET riskcoin = ? WHERE id = ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ii", $riskcoin, $id);
mysqli_stmt_execute($stmt);
echo $riskcoin;
?>
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
You cannot put php code inside of javascript as PHP is server side so it runs before javascript.
I believe your best option would be to use php for all of it.
When I search null or space values, all the results from database come to my html table.
I wanted to prevent users to search null values or space values.
I tried this post, but now helped me, How to prevent a database search from running on an empty string?
Here is the backend script-
<?php
//fetch.php
$connect = new PDO("mysql:host=localhost;dbname=searchv3", "root", "");
$output = '';
$query = '';
$data = [];
if(isset($_POST["query"]))
{
$search = str_replace(",", "|", $_POST["query"]);
$query = "
SELECT * FROM number_list
WHERE IMSI REGEXP '".$search."'
OR Mobile_no REGEXP '".$search."'
OR Backup_date REGEXP '".$search."'
OR Sr REGEXP '".$search."'
";
}
else
{
$query = "
SELECT * FROM number_list order by Sr DESC LIMIT 50;
";
}
$statement = $connect->prepare($query);
$statement->execute();
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
$connect = null;
?>
I will share front-end jav script as well-
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch_numberlist.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
$('#total_records').text(data.length);
var html = '';
if(data.length > 0)
{
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td>'+data[count].Sr+'</td>';
html += '<td>'+data[count].IMSI+'</td>';
html += '<td>'+data[count].Mobile_no+'</td>';
html += '<td>'+data[count].Backup_date+'</td>';
}
}
else
{
html = '<tr><td colspan="4">No Data Found</td></tr>';
}
$('tbody').html(html);
}
})
}
$('#search').click(function(){
var query = $('#tags').val();
load_data(query);
});
})
</script>
...
$data = [];
// `??` operator returns value if isset needed post element, else use empty string
// trim - remove start and ending spaces from string.
// So it return empty string if user input only space
$post_query = trim($_POST["query"] ?? '');
if($post_query)
{
$search = str_replace(",", "|", $post_query);
...
I am having to solve a problem involving code in both JS and PHP. For some reason, whenever this code executes, it puts the first entry in all the rows of the table instead of iterating through each entry and putting all of them in the rows. I would appreciate someone's help in giving me insights into how to fix this issue. Can this be fixed with just a "for in" loop? Thanks in advance.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$sql = "SELECT COUNT(`LID`) AS `x` FROM `snipe`.`plobby` WHERE LID = '".$_POST['id']."';";
$result = $db->query($query);
$rst = $db->query($sql);
$cnt = 0;
if($rst->num_rows > 0)
while($row = $rst->fetch_assoc())
$cnt = $row["x"];
if ($result->num_rows > 0)
for($i = 1;$i<= $cnt;$i++)
echo json_encode($result->fetch_assoc());
else
echo json_encode([]);
?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Here is the object to which the above loop is referring:
<script type="text/javascript">
var state = {};
for($i = 1;$i <= <?php echo getLobbytPlayers($_GET['id']);?>;$i++ ){
var reloadTable = function (data) {
if ($.data(state) == $.data(data)) {
return;
}
$('#js-lobby-table').empty();
$.each(data, function (rowNumber, rowData) {
var row = $('<tr>');
console.log(data);
// Player
row.append($('<td>', {
'html': data.eName
}));
// Status
row.append($('<td>', {
'html': data.gameID == "000" ? 'waiting' : 'ingame'
}));
// Win %
row.append($('<td>', {
'html': 'TODO'
}));
// Games
row.append($('<td>', {
'html': 'TODO'
}));
// K/D
row.append($('<td>', {
'html': 'TODO'
}));
$('#js-lobby-table').append(row);
});
// Set the current table state.
state = data;
};
}
setInterval(function () {
$.ajax({
type: 'POST',
url: '/lobby/api/table.php',
data: {
id: '<?= $_GET['id'] ?>'
},
success: reloadTable,
dataType: 'json'
});
}, 10);
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You shouldn't call json_encode() multiple times. The response has to contain a single JSON object, not multiple objects. You need to put all the results in an array, and call json_encode() on that array at the end.
There's also no need to get the count first. Just call fetch_assoc() until you get all the results.
<?php include('../../functions.php');
$query = "
SELECT
*
FROM
plobby
LEFT JOIN users ON users.UID = plobby.UID
WHERE
`LID` = '". preg_replace("/[^A-Za-z0-9 ]/", '', $_POST['id']) ."';
";
$result = $db->query($query);
$rows = [];
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
echo json_encode($rows);
?>
I'm making a stock table, where the user can input a number of stock to issue out, and this function is to verify, for each member of the table, whether or not the quantity of stock in the database is sufficient to make the issue.
When I breakpoint through the code on Chrome, it seems to never hit the inside code of the $.post until after its finished looping through the table. And by then the data that is supposed to be passed to AddIssue just becomes 1 and 10 and nothing else.
It's starting to drive me mad, so I'd appreciate a pointer on what I'm doing wrong here
var issueArray =[];
function VerifyIssue()
{
var numRows = document.getElementById("searchTable").rows.length - 2;
var running = true;
var str1 = "issue_";
while(running == true)
{
if (numRows < 0 && running == true)
{
running = false;
//insert code for success
break;
}
else if (running == false)
{
break;
}
var str2 = numRows;
var comb = str1.concat(str2);
var issue_element = document.getElementById(comb);
var q = issue_element.value;
var i = issue_element.name;
var idd = i.replace("issue_", "");
var trimId = idd.trim();
$.post
(
'includes/issueCheck.php',
{
id: trimId,
issueQuantity: q
},
function(result)
{
alert(result);
if (result < 0)
{
alert("One of more quantities inputted are greater than held in stock");
running = false;
}
if (result > 0)
{
addIssue(trimId, q);
}
}
);
numRows = numRows - 1;
}
alert(issueArray);
}
function addIssue(issueID, quant)
{
var item = {};
item.label = issueID;
item.value = quant;
issueArray.push(item);
}
This is the PHP that is called by the $.post
<?php
$server = 'SQL2008';
$connectionInfo = array( "Database"=>"rde_470585");
$conn = sqlsrv_connect($server,$connectionInfo);
$false = -1;
$true = 1;
$id = $_POST['id'];
$quantity = $_POST['issueQuantity'];
$query = "Select Quantity FROM Stock WHERE StockID = ?";
$param = array($id);
$res = sqlsrv_query($conn, $query, $param);
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC);
$dbQuantity = $row['Quantity'];
if ($dbQuantity < $quantity)
{
echo $false;
}
else if($dbQuantity >= $quantity)
{
echo $true;
}
Do you realise that your function(result){ ... } will only be called when the server response for your POST request is received? You have to build the code to take that delay into account.
I'm still working on this, reading up on Promises based on what #jojo said, but not sure if it's going to work for me.
How else can I make the javascript wait for a server response before resuming?
I'm trying to get two distinct results from AJAX calls. I pass in _functionToRun to the PHP file, which uses a switch statement to determine which function to run.
In the PHP file, I echo out two different arrays of words... newQuestWords() should only return some of the words. parseHoveredText() should return all vocab in the database.
Yet it seems when I echo out both, just all of the vocab is returned...
For example, in the JavaScript, log(hoveredWords[i]); should show all of the vocab available in the database, as returned from `parseHoveredText() function, but it doesn't show anything.
Why is that?
JavaScript:
$(document).ready(function() {
//initially append words to word bank
$.getJSON("php/Quests.php", { "_questNum" : questNum, "_functionToRun" : 1},
function(returned_data) {
wordsArray = returned_data;
$.each(wordsArray, function(key, value) {
$(".wordBank_Words").append("<span class='bankword' data-display-word='" + key + "' ><b>" + key + "</b>: " + value + "</span><br/>");
}
);
});
//get all chinese/english words for hover over translation
$.getJSON("php/Quests.php", {"_functionToRun" : 2},
function(returned_data) {
hoveredWords = returned_data;
for (var i = 0; i < hoveredWords.length; i++) {
log(hoveredWords[i]);
}
});
PHP:
<?php
//if user's input is correct, increment task number, get next vocabulary
$functionToRun = (isset($_GET['_functionToRun'])) ? $_GET['_functionToRun'] : 1;
parseHoveredText();
switch ($functionToRun)
{
case 1:
newQuestWords();
break;
case 2:
parseHoveredText();
break;
default:
echo "defaulted...";
}
function newQuestWords () {
include 'DbConnect.php';
$questNumber = (isset($_GET['_questNum'])) ? $_GET['_questNum'] : 1;
$qry =
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = " . $questNumber;
$sql = $mysqli->query($qry);
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
echo json_encode($wordsArray);
}
function parseHoveredText () {
include 'DbConnect.php';
$qry =
"SELECT v.*
FROM vocab v";
$sql = $mysqli->query($qry);
$hoveredWords = array();
while ($row = $sql->fetch_assoc()) {
$hoveredWords[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
//return Chinese and English Words
echo json_encode($hoveredWords);
}
?>
Dump return_data, it is json object not an array you can iterate. You can iterate through it this way
...
function(returned_data) {
for (word in returned_data) {
console.log(word);
}
}
...
Or with $.each
...
$.each(returned_data, function(key, value) {
console.log(value);
}
...