Reading blob data using PHP and JavaScript - php

I have an application where a user is allowed to save some text data into a MYSQL database through a web interface. In addition, they can also attach a file to this text and I save this into a blob field. The file types that get attached are simple .txt files.
I am able to save this data into the database but I am having trouble retrieving it. This is what I am doing to retrieve it right now:
//Events that take place when trying to retreive an attached file
function getFile(rowid){
//Make an AJAX Request to fetch the file
$.ajax({
type: 'get',
url: 'point-of-contact.php',
data: 'page=attachment&row='+rowid,
dataType: 'text',
success: function(data) {
console.log (data);
}
});
}
The AJAX request above leads to the following PHP code:
$attachments = $poc -> getPOC($_GET['row']);
header('Content-type: text/plain');
echo $attachments;
The problem I face is that when I console log the data received from the AJAX request I get this:
How do I go about getting the data in simple text format?
Could it be that the way I am uploading the file to the database is incorrect? This is how the file is uploaded to the DB:
//File upload code
var fileInput = document.getElementById('upload');
var file = fileInput.files[0];
//Hide the save button
$("#save-button-1").hide();
//Make the AJAX request
$.ajax({
type: 'post',
url: 'point-of-contact.php?page=add',
data: 'point_of_contact=' + $("#textarea1").val() + '&point_of_contact_attachment=' + file,
success: function(data) {
$('#done-1').show();
setTimeout(function() {
$('#done-1').fadeOut();
}, 2500);
$('.loader').fadeOut();
}
});

There is problem in your upload section. The line
var file = fileInput.files[0];
assignes file object into file variable. Later, when you add it to
"point_of_contact_attachment="
it gets converted to string. So you will have
"point_of_contact_attachment=[object file]"
And that is it.

try pointing the browser directly to the file instead of using ajax.
Like this
document.location = point-of-contact.php?page=attachment&row='+rowid;
Since it is not a file the browser can read, it will just download it.
However you will still need to get the TXT via ajax, because document.location redirect to the user to a plain text page.

Related

external PHP echo in a local HTML file

I have an external PHP, located on a hosting server. The app that I want to build is using Cordova, so I have a HTML on my phone local storage. I have a login form that POSTS to that external php the name and the password of the user. I want that when I click on submit, to stay on my current page, and display the values recieved by the PHP below the form, in a <p> or <h1> tag.
I will be grateful if you can help me with this.
You can make use of Ajax to get the content/data to your view from an external file.
You will need jQuery to use $.ajax().
//Get form Data
var form_data = $('#form').serialize();
$.ajax({
url:'http://something.com/dosomthing.php',
type:'POST',
data: form_data,
success:function(data){
// See what data was returned
console.log(data);
if(data.success == "1"){
$('#err-element').html("User Authenticated");
// Fade in new Page
}else{
$('#err-element').html("User Not found");
}
}
});
It is good practice to return a JSON object from your back-end.
if($user_matches){
echo json_encode(["success"=>"1", "OtherInfo"=>"Kitty"]);
}
post the data to the same page using query or something, use post or get variable to store it in a variable and append with javascript.
//post using query
$.ajax({
type: "POST",
data:{ whatyouwant: yourdata }
})
//in php
$data = $_GET['whatyouwant'];
//in javascript
data = '<?php echo $data;?>'; // if it's a string or you can use json_encode for arrays and such
$('#targetDiv').html('<p>'+data+'</p>');

Upload image via Ajax

Well the thing is there is already a edited form with a lot of fields but all the save and validate goes trough ajax.
They asked me now to put a file upload , i tough that just will be set a input and get it on back , but since all goes trough ajax i cant.
I don't want to change all the function and go trough a submit if it's not necessary.
I looked for some uploaders of file trough ajax but all of them are type drag and drop and i don't like them because y only need a simple file.
And the ones that i found that looked simple where in flash...
Is there any simple script that allows me to upload a simple file trough ajax without need of change the type of submitting the fields.
Thank's in advance mates ;)
//the js that saves all the inputs
function _edit_campaign(){
var data = formvalues_inspinia("body");
data.action=_action;
data.status=$("#smf_ior_status").val();
$.ajax({
url: "/save_changes",
dataType: "json",
data: data,
method:"POST",
success: function (response) {
if(!response.status){
toastr_error(response.desc);
$( "#submit_confirm" ).prop( "disabled", false );
$("#"+response.camp).focus();
}else{
toastr_success(response.desc);
}
}
});
}
client side
$.ajax({
url: "ajax_php_file.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
{
});
server side
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
You can achieve this in simpler way using "ajaxSubmit".
Include jquery.form.js on your page and submit your form.
$(form).ajaxSubmit({
url: url,
type: "POST",
success: function (response) {
// do what you need with response
});
It sends all form data including file on server then you can handle these data in regular manner.

Download CSV Via AJAX Post

Hi there Stackoverflow. I am trying to call a PHP script via AJAX that will create and download a CSV file. I know this isn't normally supposed to be done, however I would like to do it this way.
My ajax below returns the csv data as shown by this output:
$.ajax({
type: "POST",
url: "<?=site_url('front_office/get_csv/')?>",
data: {hashed_center_ids : hashed_center_ids, print_data : print_data},
dataType: "text",
success: function(response) {
console.log(response)
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
window.open(uri, 'test.csv');
}
});
The problem is that using the lines
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
window.open(uri, 'test.csv');
does not download the file as a CSV. But rather it give it no extension with the name "download". Does anybody know how can I make it so it downloads with the .csv extension? Thanks.
I can't comment, so: You can change the name of the csv by adding following to the header
filename=whatever.csv

Jqgrid - Clear File upload from form

I'm using Jqgrid and Ajaxfileupload to upload a file. It works fine but when I'm going to upload another file in the form appears the file that I have upload. I would like to clear the file fields
This is my code
afterSubmit : function(response, postdata){
var respuesta = response.responseText;
var param = $("#resTables").jqGrid('getCell',lastSel,'idProyecto');
$.ajaxFileUpload({
url: "doajaxfileupload.php?imagen=&tabla=proyectos&categoria="+ param,
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json'
});

Calling PHP function when link is clicked

I have a PHP function
function ExportExcel()
{
// code
}
and a link on the page Download in Excel
<a>Download in Excel</a>
So what I want is when users clicks on that link, PHP function would be called and data will be downloaded in excel.
I may need to Ajax for that. How do I go about doing that ?
You could possibly just use a GET statement, so it would look something like this...
HTML
Download in Excel
PHP
function ExportExcel()
{
// code
}
if($_GET['init'])
{
ExportExcel();
}
here is the function i implemeted recently:
$('#toexcel').live("click",function() {
$.ajax({
url: "toExcel.php",
data: "sql="+encodeURIComponent(sql),
beforeSend: function(){
$("#wait").show();
},
complete: function(){
$("#wait").hide();
},
success: function(response){
window.location.href = response.url;
}
});
});
where sql variable actually stores sql query to the server,
and then toExcel.php if getting passed sql, submitting it to the server and outputs the result using PHPExcel() object.
EDIT
i think i understood what you trying to achieve. your ExporExcel() function already outputs the results you need, right? is so, then you can do it as follow:
$('#toexcel').click(function() {
$.ajax({
url: "toExcel.php", // should contain and _call_ you ExportExcel() function
beforeSend: function(){
$("#wait").show(); // this is loading img to show
},
complete: function(){
$("#wait").hide(); ;// this is loading img to hide once complete
},
success: function(response){
window.location.href = response.url;
}
});
});
first let me make sure you know php is only parsed when the page is first being distributed. If you click a link on the page, it has no idea the php function on the same page exists because the function only existed server-side while the code was being parsed. That being said, you can easily make a separate page called download.php and call your function on that page. Then your link can just link to that page.
If you want your custom download page to return to the user as an excel file, you can use custom php headers to convince the browser that it is downloading an excel file. (you'd have to specify the MIME type for excel files)
edit:
this would cause a download to start of an excel file created by your function call and activated by your link click. You don't need any JS or JQuery for this.
edit2:
here's example code for the download file to get you started
<?php
header("Content-type: application/excel");
print($data); /* print out the contents of the excel file here */
exit();
?>
If you do it like this, your php page will not redirect from your original page, but will bring up a download box from the browser instead. If your using csv files instead of xls files, you'll need to change the mime type.
you can handle the request in your js scrpit file
$("a").click(function(){
jQuery.ajax({
url: "path/to/controller",
type: "POST",
dataType: 'json',
data: {'mentod':'ExportExcel'},
success: successCallback,
error:failureCallback
});
});
Just provide link of that excel file in href of anchor , browser will download automatically
If your file form DB then providelink of excel.php , and in excel.php do processing of getting excel file and creation of it .
read this artical..do like that

Categories