I have a button that when clicked is supposed to submit variables to an ajax call which then a csv is created and downloaded but for some reason the file just isnt downloading. Yet I get the correct output in Chrome Dev tools:
Here is what I have:
index.php
<form class="navbar-form navbar-left" method="post">
<input hidden id="ajaxquery" value="<?php echo $ajaxquery;?>">
<button type="button" class="btn btn-success btn-lg" id="downloadcsv">Download CSV</button>
</form>
script.js
$(document).ready(function() {
var csvquery = function(){
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
ajaxquery = $('#ajaxquery').val();
department = getUrlParameter('department');
startdate = getUrlParameter('startdate');
enddate = getUrlParameter('enddate');
staffsearch = getUrlParameter('staffsearch');
$.ajax({
type: 'POST', // type
url: '../report/csv.php', // request file the 'check_email.php'
data: {ajaxquery:ajaxquery, department: department, startdate:startdate, enddate: enddate, staffsearch: staffsearch},
success: function(responseText) {
}
}); // end success
}
$('#downloadcsv').click(csvquery);
});
csv.php
session_start();
require '../connect.php';
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('Name', 'Department','Hours Worked', 'On Holiday', 'Ill' , 'Date'));
$sql = "SELECT time.id as timeid, time.staff_id, time.timein, time.onholiday, time.dateadded, time.ill, time.notes, staff.id AS staffid, department.id AS departmentid, department.department_name, staff.staff_name, staff.department_id FROM time, staff, department WHERE staff.id = time.staff_id AND staff.department_id = department.id ORDER BY `time`.`dateadded` ASC ;";
$rows = mysqli_query($connect, $sql);
while ($rowcsv = mysqli_fetch_assoc($rows)){
fputcsv($output, array($rowcsv['staff_name'],$rowcsv['department_name'],$rowcsv['timein'],$rowcsv['onholiday'],$rowcsv['ill'],$rowcsv['dateadded']));
};
readfile("php://output");
Change aJax to fileDownload:
$.fileDownload('../report/csv.php', {
httpMethod: 'POST',
data: {
ajaxquery:ajaxquery, department: department, startdate:startdate, enddate: enddate, staffsearch: staffsearch
},
successCallback: function (url) {
//insert success code
},
failCallback: function (html, url) {
//insert fail code
}
});
You can use jQuery fileDownload method through this js file:
https://github.com/johnculviner/jquery.fileDownload/blob/master/src/Scripts/jquery.fileDownload.js
More information at:
http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/
Related
I have a slight problem with my code, lets say i have a json like this one :
[{"img":"john.png","name":"John","username":"#john"},
{"img":"mark.png","name":"mark","username":"#mark"}]
I wanna get data organized like :
John #john john.png
Mark #mark mark.png
But every time the data comes out like this:
John Mark #john #mark john.png mark.png
This is my Php Code:
<?php
class search{
public function gettingvalues($search_value){
require_once('conx.php');
$dir = "usersimage/";
$sql = "SELECT name,img,username FROM users WHERE username like '$search_value%' || name like '$search_value%'";
$query = mysqli_query($conx,$sql);
if ($query) {
if (mysqli_num_rows($query) > 0) {
while ($row = mysqli_fetch_array($query)) {
$img = $row['img'];
$name = $row['name'];
$username = $row['username'];
$json = array('img' => $img, 'name' => $name, 'username' => $username);
$results[] = $json;
}
echo json_encode($results);
}
}
}
}
?>
This the index code:
<?php
if (isset($_POST['data'])) {
require('search.php');
$search = new search;
$search->gettingvalues($_POST['data']);
header('Content-Type: application/json; charset=utf-8');
die();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input').keyup(function(){
var value= $('input').val();
$.ajax({
type: "POST",
url: "",
data: {data: value},
datatype: "json",
success: function(json_data) {
var img = [];
var username = [];
var name = [];
$.each(json_data, function(index, element) {
img.push(element.img);
username.push(element.username);
name.push(element.name);
})
$('#feedback').html('');
$('#feedback').html(name+username+img);
}
});
});
});
</script>
<input type="text" name="search" placeholder="looking for?">
<div id="feedback"></div>
Actually this is my first time with json, i don't know what is the problem or maybe i missed something, I hope getting some answers.
You need to build the HTML in the order that you want it displayed.
var html = '';
$.each(json_data, function(index, element) {
html += `${element.name} ${element.username} ${element.img}<br>`;
}
$("#feedback").html(html);
my script returns an array of JSON, and not individual results from the database. The script is designed to retrieve from the database records that match the text you typed. Below my codes, what could be wrong?
PHP:
//after connect to database (succesfull)
if($_GET['search_data'])
{
$search = ltrim($_GET['search']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
HTML
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#search").keyup(function(){
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: "text=" + text,
async: false,
success: function(text) {
if(text)
{
$('#display').append(JSON.stringify(text))
}
else
{
$('#display').append('No results!');
}
}
});
});
});</script>
<title>Live search</title>
</head>
<body>
<br />
search: <input type="textbox" value="" name="search" placeholder="Write here..." id="search" />
<br />
<div id="display"></div>
</html>
and results:
[{"id":"10","text":"Dropdowns"},{"id":"9","text":"Accordions"},{"id":"5","text":"Convert Weights"},{"id":"3","text":"Animated Buttons"},{"id":"8","text":"Side Navigation"},{"id":"6","text":"Parallax"},{"id":"2","text":"HTML Includes"},{"id":"7","text":"Progress Bars
"},{"id":"4","text":"Top Navigation"},{"id":"1","text":"Range Sliders"},{"id":"11","text":"Google Maps"}]
My problem is that it shows when you type some letters the whole array of JSON, and not only the record, which we expect. What can I do?
You're trying go get the search parameter with $_GET['search'] you need to use $_POST['text']. Try this :
if($_GET['search_data'])
{
$search = ltrim($_POST['text']);
$limit = 15;
header("Content-type: application/json; charset={$charset}");
if(!empty($search)
$res = $conn->query("SELECT aid, name FROM titles WHERE LIKE '%".$search."%'");
$data = array();
while($row = $res->fetch_accoss())
{
$row['name'] = htmlspecialchars_uni($row['name']);
$data[] = array('id' => $row['aid'], 'text' => $row['name']);
}
echo json_encode($data);
exit;
}
And it's a good practice to use object in your ajax data
$(document).ready(function () {
$("#search").keyup(function () {
var text = $(this).val();
$.ajax({
type: "POST",
url: "search.php?get=search_data",
dataType: 'JSON',
data: {
text: text
},
async: false,
success: function (text) {
if (text)
{
$('#display').append(JSON.stringify(text))
} else
{
$('#display').append('No results!');
}
}
});
});
});
I'm trying to upload an image to a folder using ajax, jquery and php but the problem is that I don't know how to send my file input value to my php file, when I run my code I get the following message:
undefined index archivo
This is my ajax call (PD. All the other parameters works properly, I only have problems with the file input value)
function Registrar() {
var cat = $('#cat').val();
var nom = $('#name').val();
var desc = $('#description').val();
var image = $('#archivo').val();
//Also tried with this, to remove the fakepath string... $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: { categoria: cat, nombre: nom, descripcion: desc, archivo: image, activo: act, disponible: disp, precio: prec },
success: function (data) {
console.log(data);
}
});
}
PHP file:
<?php
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_POST['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
And the important parts of my HTML:
<form id="registerForm" method="post" role="form" enctype="multipart/form-data" >
<input name="archivo" id="archivo" style="width: 70%;" name="textinput" class="btn btn-block" type="file" onchange="showimagepreview(this)" />
EDIT: showimagepreview
function showimagepreview(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
document.getElementsByTagName("img")[0].setAttribute("src", e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
How can I solve this?
Send your form data like this:
var formData = new FormData($("form")[0]);
$.ajax({
url: '../../class/upload.php',
method: 'POST',
data: formData,
success: function (data) {
console.log(data);
}
});
And you have to get the file with $_FILES, you can not get it in $_POST in php code.
Here is you solution
HTML
<form id="registerForm" method="post" enctype="multipart/form-data">
<input name="archivo" id="archivo" style="width: 70%;" class="btn btn-block" type="file" onchange="PreviewImage(this)" />
<img id="uploadPreview" />
<button type="submit">Submit</button>
Java Script
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("image").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
//ajax
$("#registerForm").submit(function(event) {
var formData = new FormData($(this)[0]);
if ($(this).valid()) {
$.ajax({
url : '../../class/upload.php',
type : 'POST',
data : formData,
contentType : false,
cache : false,
processData : false,
success: function(e) {alert(e) },
error : function(x, t, m) {},
});
}
});
PHP
<?php
echo "<pre>"; print_r($_FILES);echo "</pre>"; die; //this will show you the file transfered by form.
$categoria = $_POST['categoria'];
$nombre = $_POST['nombre'];
$descripcion = $_POST['descripcion'];
$img = $_POST['archivo'];
$activo = $_FILES['activo'];
$disponible = $_POST['disponible'];
$precio = $_POST['precio'];
$IdCategoria = 0;
$filepath = "";
//Imagen
if($categoria=="Piano") {
$IdCategoria = 1;
$filepath = "../Files/Productos/Piano/".$img;
}
$filetmp = $_FILES['archivo']['tmp_name'];
move_uploaded_file($filetmp, $filepath);
echo $IdCategoria.$nombre.$descripcion.$filepath.$activo.$disponible.$categoria.$precio;
?>
change this
$img = $_POST['archivo'];
to
$_FILES['archivo'];
Files object cannot be recieved in $_POST
I am using jquery, php and json to store and update the clicks on a single download button. It's working flawlessly but now I need to be able to store and update the clicks from multiple download buttons and display them individually.
Can you guys give me a hand with this?
What I have so far is:
jQuery:
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
$.ajax({
url: "downloads.php",
success: function(response) {
if (response = 'success') {
// The counter file has been updated in the background, but we should update the results on screen to tell the user
var count = $('.small').html();
$('.small').html(parseFloat(count) + 1);
// Then redirect so that file can download
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
}
});
return true;
});
$.ajax({
url: "get-downloads.php",
success: function(data) {
var data = JSON.stringify(data, null, 4);
var data = $.parseJSON(data);
$('.small').html(data.count);
}
});
downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'] = $json['count'] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
get-downloads.php
<?php
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
header('Content-Type: application/json');
echo json_encode($json);
?>
and the downloads.json
{"count":174}
try like this
for example for 3 button
<input type='button' name='btn1' class='download'/>
<input type='button' name='btn2' class='download'/>
<input type='button' name='btn3' class='download'/>
send name of button to server and show count in different .smallbtn1،.smallbtn2،.smallbtn3
$('.download').click(function(event) {
event.preventDefault();
ga('send', 'event', 'Button', 'Clicks', 'Downloads');
var redirectUrl = $(this).attr('href');
//get name of button
var name= $(this).prop('name');
//==================
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
$("#cover").fadeIn(600);
$("body").addClass("hidescroll");
window.location.href = "download/imagins_._ro_free_files_format_icons.rar";
}
});
//===================
}
}
});
return true;
});
in downloads.php open json file
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.json
{"countbtn1":0,"countbtn2":0,"countbtn3":0}
this is my test and working for me
I currently have two php files (index.php and update.php) In index.php, there is some javascript code and a button that sends a variable, called $sid, to update.php, where it is processed based on $sid. Here is the code for both index.php and update.php. I am not pasting it directly into StackOverflow, simply because of how you have to add code to your text on StackOverflow, and how JavaScript works with it's spacing hierarchy.
http://pastebin.com/fq87vvgz
Currently, when you press the button, an alert box does not pop up. If you put the PHP code in a PHP code checker, no errors appear.
Here is my code:
This is what is in index.php
<?php
$sid = 11;
?>
<script type="text/javascript">
$(document).ready(function(){
$('#vote').click(function(){
$.ajax({
url : 'update.php', // Notice how this sends to update.php
type : 'POST',
data : {
action : 'vote_server',
sid : $('#sid').data('sid')
},
dataType : 'JSON',
success : function(result) {
if (result.xhr == 'success') {
alert('You bumped your server!');
} else if (result.xhr == 'voted_already')
alert('You can only bump every 24 hours!')
}
});
});
})
</script>
<input type="button" class="btn btn-primary" id="vote" value="Vote up your server">
This is what is contained in update.php
<?php
define('action',$_POST['action']);
$result = array(
'xhr' => 'error'
);
if (action == 'vote_server')
{
$sid = (int)$_POST['sid'];
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$dbTime = #mysql_result(mysql_query("SELECT `id`, `last_updated` FROM `servers` WHERE `id` = '$sid'"), 0);
$timeDiff = $time - $dbTime;
if($timeDiff >= 86400){
mysql_query("UPDATE `servers` SET `last_updated` = '$time' WHERE `id` = '$sid'");
$result['xhr'] = 'success';
} else { $result['xhr'] = 'voted_already'; }
}
echo json_encode($result);
?>
Use query and ajax
in your index page...
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$( ".button" ).click(function() {
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
$.ajax({
type: "POST",
url: 'update.php',
data: {postedVar:var1, postedVar2:var2},
success: function(data)
{
alert(data);
}
});
});
});
</script>
<html>
<button class="button" data-var1="<?php echo "this is var1"; ?>" data-var2="<?php echo "this is var2"; ?>">Button</button>
</html>
On you update page...
access your vars like this
<?php
var1 = $_POST['postedVar1'];
var2 = $_POST['postedVar2'];
echo var1;
?>
...NOT TESTED