I am using DOMPDF and I want my form input text to be available in PDF format. So when I type something in input fields, and I press export to PDF, I want it to be there. So here is how I planned my solution. The problem appears when I call the PHP with POST from HTML because It does not update the input values. It just sends the blank ones. I need to change that so it updates them.
1) Fill in the input fields with text
2) Click Export to PDF
3) Use JQuery to change the HTML with input values
4) Call the PHP file ($dompdf->loadHtml(file_get_contents('index.php'));
I tried using AJAX for this but it doesn't work. I DON'T need to send ANY data to the PHP File. I just need to call if after the JQuery changed the HTML.
Here's my PHP File:
<?php
require_once 'autoload.inc.php';
// reference the Dompdf namespace
use Dompdf\Dompdf;
// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml(file_get_contents('index.php'));
// (Optional) Setup the paper size and orientation
$dompdf->setPaper('A4', 'landscape');
// Render the HTML as PDF
$dompdf->render('doc.pdf');
// Output the generated PDF to Browser
$dompdf->stream();
?>
And my JQUERY File
function ajax() {
alert('in');
$.ajax({
url: 'jobsheet.php',
type: 'POST',
data: formData,
success:function(response){
alert(response);
}
});
}
If you have any other solution for this, please let me know!
I see two problems with your technique.
First, Dompdf (as of 0.6.1) does not parse PHP so you will need to pre-parse that before passing it off to dompdf. You can use output buffering for that:
<?php
ob_start();
require_once 'index.php';
$html = ob_get_clean();
ob_end_clean();
require_once 'autoload.inc.php';
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$dompdf->stream();
?>
Second, if all you want to do is display the results why use AJAX at all? It requires significantly more work to fetch and display the PDF document this way when you could simply use a form post. If you have a particular need for using AJAX you should specify.
Related
So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");
So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here
I'm making a change to the way a site works and trying to find a solution that requires as little re-writing as possible.
At the moment, I have a file (myFile.php) which loads (using Wordpress) into a page. It uses a PHP array for outputting data. The PHP array is $property_list_featured_search and the content looks something like this:
<?php
foreach($property_list_featured_search as $individual_property){
?>
<span><?php echo $individual_property['info']['status'] ?></span>
<?php
}
?>
So in my small example, it's outputting data from $property_list_featured_search and this works OK.
My problem is that I now want to load the HTML&PHP above using jQuery AJAX. When a user clicks a button, it loads the HTML (which is stored in a file, called myFile.php into a div on the page:
function loadView(view){
$.ajax({
type: "POST",
url: 'path/to/file/property-search/myFile.php',
data: property_data,
success: function(result)
{
$("#search-page-content").html(result);
});
}
In the case above, property_data is the $property_list_featured_search data localized using Wordpress so that the file can access it. I have tested it and can confirm that the file loaded in with AJAX is able to see the data. My problem is that I now have a file with PHP echo everywhere and the data in JSON format.
Is it possible to still use this data in this way? I'm guessing because the data is JSON that it's not possible to use echo $data[key] at all like it was in the original file?
What's the best way to output all the data in the JSON file on the page?
You can try something like this:
When u get your data:
$checked = $_POST['property_data'];
$checked = array('first' => $checked[0], 'second' => $checked[1], 'third' => $checked[2], 'forth' => $checked[3]);
Then you can echo it like this:
$checked['first'], $checked['second'] and so on.
Hope this helps
I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');
I use a php to create a guest message board so user can leave message.
I didn't use any database, it is just a text file and append new data.
Is there any easy way to use something like jQuery for user to add new content into the message he left before?
To be clear, I don't want to use any database. Thanks
Create the file with a good structure so the information is easily parseable.
Open file with PHP and parse the information into an object.
Export the object with for example json_encode trough an api
Fetch the object with jQuery
When someone adds a message send it trough jQuery to back-end where you append the message to the file.
Since javascript/jquery is a client language while PHP runs on server. You can use jQuery ajax to send text in a saperate php file via query string where you can append text using PHP fwrite function. here is an idea example to make clear:
jQuery:
var textfield = $('textarea'); //your text area field
var pathToPHP = "Your path to php script/text.php?text="+textfield;
//get text via query string
$.ajax({ URL:pathToPHP , method:"GET", cache:false, type:"HTML" });
//Send text to PHP script using Ajax
You can find further ajax options via jQuery ajax API
PHP:
$text = $_GET['text']; //Get the Text
$txt_file_path = "file.txt"; //Path to text file
$read = fopen($txt_file_path,"w"); //Open Text file in write mode
$new_content = $read." ".$text; //Old Content + New Content
fwrite($read,$new_content); //Rewrite Text file
fclose($read); //Close file
This php code is just for idea and you can refer to fopen and fwrite for complete solution