I have a <textarea>
in the middle of a page which is styled with CSS. I have an input box underneath. I want user input from the second box to be sent to the same file using ajax, and then some logic at the top of the file to take the input and echo some stuff into <textarea>
and not return anything else. At the moment what is happening is that the textarea is being filled with the HTML of the page. Anyone help?
If you are wanting text in the textarea to be appended to by the text from the input box then
file_get_contents
)If your page and AJAX handler are one and the same thing, you need something to distinguish between the two 'modes' so the page acts appropriately.
In the case of the AJAX request, you want to return (output) something specific, rather than the page source code. Here's a simple means:
<?php
if (isset($_POST['input'])) { //<-- replace with the name of your input
die("response to go in textarea here");
}
?>
The die
command terminates output, optionally with a given string (the AJAX response), so the remaining HTML of the page will not be output as well.
It's better to have your page and AJAX handler as separate files. As one, you're unnecessarily loading a larger file than is necessary for each AJAX request as it contains unwanted HTML.
Use some variable to define the action the script needs to take. An AJAX call to the script would presumably not echo out all the html for the page but just some text for your text area.
Try something like:
<?php
if ($_GET['action'] == 'text') {
echo 'Some text for the textarea';
} else {
//regular page load
}
?>
$.ajax({
'type': 'GET',
'url': '/thisScript.php',
'data': 'action=text',
'success':function(data) { $('textarea').val(data); },
});
You can use switch statements for many different actions per script.
Cheers.
See this article: http://davidwalsh.name/detect-ajax
You can check to see if the request is AJAX at the top of the file.
/* AJAX check */
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
die($content);
}