File downloading using AJAX not working - php

I am creating simple file downloading script using AJAX in PHP. My script is not working. Means it displaying the content of the pdf/doc file below download link after clicking on it. Below image will illustrate the problem.
Below is my code
AJAX and HTML:
$(function() {
$(".download_link").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
$.ajax({
type: "POST",
url: "download_file.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
}
});
return true;
});
});
<a href="#" class="download_link" id="d_link">
PHP Script: (download_file.php)
<?php
ob_start();
$file = 'file.doc';
header("location:".$file);
?>

You are using $("#display").after(html); thats why its displaying the content of the file. You can download the file by following code.
$(function() {
$(".download_link").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
$.ajax({
type: "POST",
url: "download_file.php",
data: dataString,
cache: false,
success: function(html){
window.location = 'your_file.pdf';
}
});
return true;
});
});

I think your approach is incorrect.
With your script you are trying to append file.doc contents into DOM object -> browser do not know on AJAX request how to manage document's encoding, it will not work.
For downloading documents I would not use AJAX, I think would be fine if you just open a new window with the document's url and let the borwser to manage the content's response:
window.open("download_file.php");
If you just want to display documents contents in the same page, I would use an iframe as follows:
<form action="download_file.php" method="GET" target="docIframe">
<input type="submit" value="Download"/>
</form>
<iframe name="docIframe" width="600px" height="500px"/>

You need to set header content type to tell the browser how it renders the content for PDF or DOC.
<?php
//Set header for pdf
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='file_to_download.pdf'");
readfile("original.pdf");
?>

Related

Jquery Ajax is neither passing data to PHP nor returning anything on success()

I am trying to pass the jquery variable to PHP with Ajax but the receiving php file is returning error " Undefined index" Code is:
<div class="img">
<a href="ss.php">
<img id="theme_bg" src="images/themes/theme1.jpg">
</a></div>
$(document).ready(function($){
$('.img').on('click','img',function(){
var imgsrc = $(this).attr('src');
alert(imgsrc); //this is returning the img src correctly
$.ajax({
type: "POST",
url: 'ss.php',
dataType: 'json',
data: {imgpath:imgsrc },
success: function(response) {
content.html(response); // i tried alert here but it shows nothing
}
});
});});
receiving PHP file code is:
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
I tried it with GET also but same error.. I haven't used Ajax before this. I checked other responses here on similar questions but none of them was has anything majorly different from mine code. so dont know what's the error..
updated Screen shots of code both files
updated screen shots of output
You have dataType set to json
so PHP should php <?php echo json_encode([$imagepath])
The better solution would be dataType: text instead of JSON
Note that in $.ajax the dataType is for response not request
Check $.ajax manual http://api.jquery.com/jquery.ajax/
Why you wrote ss.php in anchor you dont need that that's why it redirecting ss.php on click and getting error undefined index.
Your html code should be like this:
<form id="myForm" method="post" action="ss.php">
<div class="img">
<img id="theme_bg" src="images/themes/theme1.jpg">
<input name="imgpath" id="imgpath" type="hidden"/>
</div>
</form>
Jquery code:
$(document).ready(function ($) {
$('.img').on('click', 'img', function () {
var imgsrc = $(this).attr('src');
$("#imgpath").val(imgsrc); //this is returning the img src correctly
$("#myForm").submit();
});
});
ss.php
<?php
$imagepath = $_POST['imgpath'];
echo $imagepath;
?>
Try this one. Add this one to document.ready function
$(".img").click(function() {
$.ajax({
type: "POST",
url: "ss.php",
data: {imgpath:imgsrc},
dataType: "text",
cache:false,
success:
function(data){
alert(data);
}
});// you have missed this bracket
return false;
});

include $variable in ajax success function

I am trying to return an image when Ajax is done, but i don't know how to include a session variable in the response, this is my code:
$(document).ready(function(){
$("#process").click(function(){
$.ajax({
type: 'POST',
url: 'process.php',
success: function (msg) {
$('#new-image').html('<img src="uploads/img/$_SESSION["sess_img"];" class="img-upload" alt="new image">')
}
});
});
});
Then, I want show the image $_SESSION["sess_img"]; within the div #new-image
You can echo that image filename in process.php like this:
<?php
// using time() as the cache buster, the image will never be cache by the browser
// to solve it, you need to add condition that will check if the image has change or not.
// or maybe you need to change the filename if it changes without adding a cache buster.
echo $_SESSION['sess_img_chofer']."?v=".time();
And in your javascript code:
$(document).ready(function(){
$("#process").click(function(){
$.ajax({
type: 'POST',
url: 'process.php',
success: function (image) {
$('#new-image').html($('<img>').attr('src', 'uploads/img/' + image).attr('class', 'img-upload'));
}
});
});
});

TCPDF generated file does not open on ajax call

Everything work fine if I use this:
form name="nnewOBR" id="inewOBR" method="POST" action="targetsample_pdf.php" target="_blank"
The data from the form will be saved in the database and the PDF will be opened. But when I use ajax, it will only execute the insertion of data in the database but it will not open the PDF. My ajax statement is as follows:
$(function() {
$("#inewOBR").submit(function() {
var datos = $('#inewOBR').serialize();
$.ajax({
type: "POST",
url: "targetsample_pdf.php",
data: datos,
success: function(data) {
alert("Successful");
}
});
return false;
});
});
I would really appreciate your help. Thank you very much.

Sending a JQuery var into php var

I installed OpenCart CMS and wanted to modify some option in the admin panel mainly the look and feel of the template. I also added the jpicker script for color picking. Also i created the css file with the standard php code and it works fine
<?php header("Content-type: text/css; charset: UTF-8"); ?>
<?php
$headerColor;
$menuColor = '#121212';
$bodyColor = '#fffaaa';
?>
#header {
background-color: <?=$headerColor; ?>;
}
In order to create the color picker view you need to add the id of the div in a script
$(document).ready(function(){
$('#Expandable').jPicker(
{
window:
{
expandable: true
}
});
});
And here is the standard code for the html
<div id="Expandable"></div>
I am not very good at JQuery but i know that it can be done either with .ajax or post. What i want to do is send the hex value from the jpicker to a php variable in the css file so it can change the color. Here is the link to jpicker http://www.digitalmagicpro.com/jPicker/. I also found an example
var colorValue = '#ababab';
$.post("view/stylesheet/stylesheet-template.css", {var_value: colorValue}, function(data) {
alert(colorValue);
});
It only sends alert and the colorValue from the variable, but i still don't know how to send the colorValue to php from the jpicker.
Thanks
function sendToPhp(jCell){
$.ajax({
url: "php/ajax.php",
data: {cell: jCell, queryNr: "0"},
type: "POST",
async: false,
success: function(data){ callback(data); }
});
}
now cell and queryNr is sent to php
if u do a switch case function depending on query nr you can access multiple functions in php this way
for the comment:
function sendToPhp(jCell, phpUrl){
$.ajax({
url: phpUrl,
data: {cell: jCell, queryNr: "0"},
type: "POST",
async: false,
success: function(data){ callback(data); }
});
}
now you can hand over a specific path by calling the function like:
sendToPhp("VAR YOU WANT TO SEND TO PHP", "php/ajax.php"); // or any other path

Parsing URL jQuery AJAX form

Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.
There is a way of inputting a video url into this. I've got everything working except one thing.
If i put this through: http://www.youtube.com/watch?v=g1lBwbhlPtM
it works fine.
but this: http://www.youtube.com/watch?v=g1lBwbhlPtM&feature=feedu
doesn't.
I've done some tests and it's because when i send the second url through &feature=feedu gets read as a separate $_POST value.
This is the problem:
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
because its reading like
var dataString = 'title='+title+'&content='+IMAGES, TEXT AND STUFF+'&feature=feedu OTHER IMAGES AND STUFF&date='+date+'&Submit=YES';
it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that & before sending it through ajax
Any ideas how to solve this?
EDIT:
Here's the full code that's the problem:
var title = $('input#title').val();
var content = $('textarea#content').val();
var date = $('input#date').val();
var dataString = 'title='+title+'&content='+content+'&date='+date+'&Submit=YES';
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: dataString,
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})
return false;
if content equals:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI&feature=feedu</vid>
<br>Text 3<br>
the content variable gets put through the ajax call as:
&content= <br>Text 1<br> <img>http://someimage.com/image.jpg</img>
<br> Text2<br> <vid>http://www.youtube.com/watch?v=isDIHIHI
with an extra variable that is
&feature=feedu</vid>
<br>Text 3<br>
So how do u stop the ajax reading &feature as a separate $_POST variable?
Did you encodeURI() before pass the your video url?
If you need it in PHP then URLEncode
I used this bit of code in the php file
if(isset($_POST['feature'])){
$content=htmlspecialchars_decode(stripslashes(nl2br("<br />".$_POST['content'].'&feature='.$_POST['feature']."<br />")));
}
But it's not very dynamic as it only applies to youtube URLs
In JS do (before ajaxing)
dataString = encodeURI(dataString);
And then decode it on PHP
$dataString = urldecode($_POST['data']);
Or do:
$.ajax({
type: "POST",
url: "./inc/php/file.php",
dataType: "json",
data: {
'title': $('input#title').val(),
'content': $('textarea#content').val(),
'date': $('input#date').val(),
'Submit': 'Yes'
}
success: function(data) {
if(data.error == true){
$('.errordiv').show().html(data.message);
}else{
$('.errordiv').show().html(data.message);
$(':input','#addstuff')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
}
},
error: function(data) {
$('.errordiv').html(data.message+' --- SCRIPT ERROR');
}
})

Categories