Press a button to Insert text into html from client. - javascript

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

Related

How to save html form data in txt file using javascript

I have a html form. I want to store form data in another txt file using javascript.
For ex: I have a html form and store-data.txt file . when user fill the form and hit submit, so data stored in store-data.txt file.
How I will do this using javascript.
Javascript can`t save data on server. JS can save data on clients machine. Data on clients machine can be stored using cookie. But I feel, it isnt an aim. Store data from froms can server side apps, driven like php.
You can use filesaver.js library for a clean implementation or follow along with this codepen It is the quickest.
if you wanted to store input values assign all values in an object then JSON.stringify then throw it to this function to get text file of json
function createTextFile(str){
var file = new Blob([str])
anchor = document.createElement("a")
anchor.href = URL.createObjectURL(file)
anchor.download = "fileName"
anchor.click()
URL.revokeObjectURL(anchor.href)
anchor.remove()
}
var input = "this is a string to test"
createTextFile(input)
and if you wanted to save in server side with php there is function in php
file-put-contents

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

Call PHP File after JQuery

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.

Capture onClick event in serverside php file using Ajax

I am very new to Ajax. My application uses ajax (and a server side php page called Req.php) to fetch records from a database, create table using those fetched records and display it. Now I want a column to be added having Delete option to it. May be something like this:
echo '<td>Delete</td>';
This deleteIt() method lies inside Req.php (server side) file like this:
<script type = "text/javascript">
function deleteIt(rowID)
{
//Some Code
}
</script>
Now considering the fact that it is a server side file, and delete event happens at client side, what should be the procedure to capture this delete event so that it takes $rowID from the table made by server side php file and deletes the correponding record.
Any help would be highly appreciated. And please let me know if there's insufficient information so that I can give more details.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
jQuery.ajax({
url:'YOUR PHP url which contains DELETE code',
type:'POST',
data:'SEND YOUR DATA',
success:function(results){
jQuery("#oresponsecontainer").html(results);
}
});
In your PHP
$id = $_POST["id"];
An Ajax request would be then be sent from your javascript with the id and action (deleting) of the column your accepping php file would then search for the row and delete it.
please specify what has been done in php for deleting.
You should create another php script that handles POST request (or GET, i've used post ajax)
so function should execute something like this
$.post("/trackDeletion.php",{rowID:rowID},function(successResponse){
//client handler
})
and PHP will be
rowID = $POST['rowID']
//do you code on backend

How to dynamically create a xml file and set it to the upload control using javascript or jquery

I want to dynamically create a xml file using jquery or javascript and i don't want to download it. I want to assign it to the upload control. Then on button click i want to send it to the controller. How can i able to do that using jquery. Any help is appreciated.
You can't send a xml file generated by JS in the client side because what you will have is not a file is just a string. But you can send the string to the server using the jquery post function (http://api.jquery.com/jQuery.post/). So create your valid XML string:
var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" +
"<root>" + getXML() + "</root>"
And send it to the server:
$.post('test.html',{ data : xml }, function(data) {
$('.result').html(data);
});
Hope it helps ;)

Categories

Resources