0

I was wondering if you'd be able to help me with this issue please?

I'm looking to pass variable length HTML (or any data in fact) to a PHP file via POST in a JavaScript AJAX method.

I want to use JavaScript for my entire project so I can cut my teeth on it - I know a lot of solutions are provided in jQuery for AJAX but hopefully you can help me via vanilla JavaScript. :)

I pass the data in the 'prepare' variable in the URL as follows:

ajax("doit.php?preparedOutput=" + prepare);

The AJAX function:

function ajax(queryURL) {
alert(queryURL); // check the right data is being sent
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        alert(xhttp.responseText);
        output2.value = xhttp.responseText;
        result.innerHTML = "<h3>your HTML</h3>" + xhttp.responseText;
    }
}
//var encodedQueryURL = encodeURIComponent(queryURL);
xhttp.open("POST", "doit.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//alert(encodedQueryURL); // check the right encoded data is being sent
xhttp.send(queryURL);
}

The alerts show me what data is supposedly being sent, whether encoded or not. All seems fine. But the response I get back from the PHP is... nothing.

<?php
$preparedOutput = $_POST['preparedOutput'];

echo $preparedOutput;
?>

Even if I use isset($preparedOutput) in an if/else block, else is triggered. Nothing's getting through. Not even if I try to pass simple numbers or letters without spaces, aside from HTML. Nothing's getting to the PHP file apparently.

I've been toying with the setRequestHeader, trying all sorts, namely "text/html" etc. Nothing changes the outcome. I feel I'm missing a key piece of the puzzle here!

If it helps, my environment is PHP enabled in IIS7 using FastCGI - if this makes any difference. PHP works, I previously had the PHP script embedded within the same page and it returned the entire page's HTML rather than the HTML in the preparedOutput variable, which is why I shifted it to its own file.

Thanks

Mark Hardy
  • 35
  • 4
  • http://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest –  Mar 31 '17 at 21:56

1 Answers1

1

That's because you doubled the url string. Take a look:

You called it by

ajax("doit.php?preparedOutput=" + prepare);

and the url you use in open is "doit.php"

so you basically call something like http://whatever/doit/?doit.php?preparedOutput=" + prepare.

Change to:

ajax("preparedOutput=" + prepare);
Nelson Teixeira
  • 5,856
  • 4
  • 31
  • 60