NoReceipt4Panda NoReceipt4Panda - 5 months ago 14
Javascript Question

AJAX/JS/PHP: How to replace text in file sent to PHP file, and pass successful attribute?

I have this button by ID of genPDF, which if clicked has this function:

$('#genPDF').click(function () {

var str = "headingText=" + jQuery("#headingText").val();

$.ajax({
url: 'indexpdf.php',
data: str,
dataType: "json",
type: 'post',
success: function () {
console.log("Success!");
}
});
})


It's supposed to take the text from input "headingText" and send to the php file indexpdf.php.

Then here's my indexpdf.php:

<?
$headingText = trim(isset($_POST['headingText']) ? $_POST['headingText'] : '');

$initialpdf = file_get_contents('file_html.php');

$initialpdf = str_replace(array(
'%headingText%'
), array (
$headingText,
), $initialpdf);

file_put_contents($fp, $initialpdf);
?>


This file is supposed to decalre the headingtext variable from the previous page, and replace each "%headingText%" in file_html.php, then save this html/php file as "file_html2.php"

The problems are, I don't think I'm saving the finalized php file right, and for some reason, while passing the "str" into the ajax php call, it doesn't succeed. If I get rid of the line, "data: str,", it succeeds.

How can I pass in these string variables, replace them in the php file, and save that file as a different file succesfully? What's wrong here?

Answer

An Alternative Way

<script>
$('#genPDF').click(function () {
  var str = $("#headingText").val();
  $.ajax({url:"indexpdf.php?headingText="+str,cache:false,success:function(result){
        console.log("Success!");
  }});
})
</script>

Use _GET

<?
$headingText = trim(isset($_GET['headingText']) ? $_GET['headingText'] : '');

$initialpdf = file_get_contents('file_html.php');

$initialpdf = str_replace(array(
        '%headingText%'
    ), array (
        $headingText,
    ), $initialpdf);

$initialpdf->saveHTMLFile("file_html2.php");
?>