0

I use the following code to select data to show the user without having to move to another page.

<script type="text/javascript">
$(document).ready(function() {
  $('#testform input[name=date]').datepicker({
    autoHide: true
  });
  $('#testform').submit(send);
});

function send() {
  const data = $(this).serialize();
  $('#output').text("FormData: " + data);
  $.ajax({
    type: "POST",
    url: "receiving_file.php",
    data,
    success: function(data) {
  document.getElementById("PrintData").outerHTML = data;
  document.getElementById("PrintImg").src = data;
    }
  });
  return false;
}
</script>

To display the output without going to another page, I write in the code:

<p id="PrintData">

The code in the file receiving_file.php looks like this:

<?php
$date = $_POST['date'];
print $date;
?>

The problem is that I want to use JavaScript within the data that comes and it does not work. However, when I try to view the source code in the browser I can't see the data.

Does anyone have an idea how to solve the problem?

Thanks

2 Answers 2

1

You need to prevent the default submission behaviour otherwise your form will continue to submit as normal and you won't see the ajax part complete.

function send(e) {
    e.preventDefault(); // prevent native submission
    // ... rest of your code as before
}

I've amended your example a little to get it working in this jsFiddle. You won't need all these changes but when simulating Ajax requests in jsFiddle you have to POST the html you want to see in the response.

Sign up to request clarification or add additional context in comments.

Comments

0

If I understood your question correctly the problem should be that you are trying to modify the outerHTML of an element instead of the innerHTML:

document.getElementById("PrintData").outerHTML = data;

whereas it should be:

document.getElementById("PrintData").innerHTML = data;



The outerHTML modifies the HTML tag itself, not its content.

2 Comments

I don't think this is a problem since a block of html is returned in the response. Whilst this may affect the format of the rendered html it wont have any bearing on wether the Ajax request works or not.
Yeah that makes sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.