I know that this question is already asked many times by different ways. But still i am not able to figure out the answer. I mean i did not find a proper descriptive answer.
I use mpdf library to generate PDF. I post some data of hidden fields to a PHP script by means of ajax.
Following are the code snippets.
//ajax_file
$("#button_id").click(function(e){
var table_clone=$("#table_id").clone();
var tableData=table_clone.prop('outerHTML');//html for pdf generation
dataString='page='+tableData;
$.ajax({
type: 'POST',
url: 'pdfgenerator.php',
data: dataString,
cache: false,
success: function(response)
{
//what to do here in order to display pdf
},
error: function(............){
.
.
}
});
});
PHP Script
//pdfgenerator.php
<?php
include('../mpdf/mpdf.php');
if(/*checking post items are set*/)
{
//retriving post items
$mpdf=new mPDF('c','A4-L');
$mpdf->WriteHTML($tableData);
$mpdf->output('xyz.pdf','I');
exit;
}
?>
Following are my constraints
-> I don't want to save file permanently on server (which is possible by means of 'F' option in output()).
-> I have to display it in browser from where it can be downloaded.
PHP script works correctly if called without ajax. Hence it returns correct data but i am unable to display it in pdf inside the browser.
While searching for answers i found that it is not possible by means of ajax.
so is there any way around by doing something in PHP or javascript. Please provide a descriptive answer.
Thanks,
You can use this code
$.ajax({
type: 'POST',
url: 'pdfgenerator.php',
data: dataString,
cache: false,
success: function(response)
{
var tag ='<object width="400" height="500" type="application/pdf" data="'+xyz.pdf+'" id="show_obj1" class="obj"></object>';
$(#pdfdiv).html(tag);
},
error: function(............){
.
.
}
});
});
Here #pdfdiv in $(#pdfdiv).html(tag); is the id of the div in which you want to show the pdf
Related
I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});
I have this code which makes a binary image from a normal image and displays it into an .img
$host=$_POST['hostname'];
$type=$_POST['type_char'];
include('rrdtools.inc.php');
include('graphs/'.$type.'.inc.php');
function graph_error($string,$rrd_options)
{
$graphfile ='/tmp/'. strgen().'.png';
$rrd_options .= ' HRULE:0#555555';
$rrd_options .= " --title='".$string."'";
rrdtool_graph($graphfile, $rrd_options);
header('Content-type: image/png');
$fd = fopen($graphfile, 'r');
fpassthru($fd);
fclose($fd);
unlink($graphfile);
}
graph_error($type,$rrd_options);
I send the hostname,type_char to the file using ajax and this is the code
$('.print_graph').click(function(e) {
e.preventDefault();
var type_char='fortigate_sessions';//$('#graph').val();
var hostname='10.10.0.144';//$(this).attr('id');
//$('#device_host').val(id);
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: {'hostname':hostname,'type_char':type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
as you can see in the javascript code I used this code to display image
$("#grph").attr("src", 'SNMP/graph.php');
and this code will call graph.php again without parameters and the result is wrong
how can I pass parameters to graphs.php .
I wish I explained my problem clearly
You can solve this by making graph.php look for GET parameters instead of POST and then setting the image source directly without using AJAX:
Change
$host=$_POST['hostname'];
$type=$_POST['type_char'];
to
$host=$_GET['hostname'];
$type=$_Get['type_char'];
and also change
$.ajax({
type: 'POST',
url: 'SNMP/graph.php',
data: {'hostname':hostname,'type_char':type_char },
success: function(data) {
alert(data);
// show the response
$("#grph").attr("src", 'SNMP/graph.php');
console.log(data);
}
});
to simply
$("#grph").attr("src", 'SNMP/graph.php?hostname='+hostname+'&type_char='+type_char);
This will mean that the image data returned by graph.php is used directly in the img tag instead of ending up in a JavaScript variable.
P.S. I note you are using the $type variable to directly create an include() statement in PHP. This is potentially very insecure, as you're letting the client have very direct control over what code is executed and this could be abused to execute code which shouldn't be executed at this time. You should make sure the value submitted contains a value you are expecting and is allowed before using it in your include() statement.
Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.
This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.
I am trying to upload a file through AJAX. I have searched over a lot but found examples using form submit only, but I can not use form submit. I have tried several examples but nothing reaches my server. When I tried this link, it worked but again it was through a form submission.
Here is the piece of code relevant to the context
JS Code
function _upload(filedata) {
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: 'multipart/form-data',
mimeType: 'multipart/form-data', //Property added in 1.5.1
success: function (data) {
alert(data);
}
});
}
$("#cpc-uploadBtn").click(function (evt) {
var data;
data = new FormData();
data.append('file', $('#cpc-upload')[0].files[0]);
_upload(data);
});
HTML Part
<input id="cpc-upload" name="file" type="file" />
<button id="cpc-uploadBtn" type="button">Upload</button>
Edit
Is there any other way to do this without using form submit and formdata?
Assuming that you are using Safari/FireFox (only those support FormData), you need to modify your $.ajax call:
$.ajax({
url: './myURI',
data: filedata,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
Seeting contentType option to false will force jQuery not to add a Content-Type header for you (otherwise the boundary string will be missing from it). Also the processData flag must be set to false so jQuery will not try to convert your FormData into a string.
Now if you know that your clients are using HTML5 you should try using new JavaScript File API - check following articles:
Working with files in JavaScript, Part 1: The Basics
Working with files in JavaScript, Part 2: FileReader
Working with files in JavaScript, Part 3: Progress events and errors
Working with files in JavaScript, Part 4: Object URLs
Working with files in JavaScript, Part 5: Blobs
In all other cases you are forced to use custom plugins, for example:
Uploadify
jQuery Form Plugin
I suppose currently FormData objects are only supported in Safari/Firefox, it has not been adopted by most of the browsers yet.
I recently struggled a lot finding ajax file uploader for asp.net and I am currently using this one in my project:
https://github.com/valums/file-uploader
there is a small alternative if you want to use
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here