Discussion: Obtaining the value from an html text input in real time
3 messages from 3 displayed.
//= Settings::TRACKING_CODE_B ?> //= Settings::TRACKING_CODE ?>
Hi Douglas,
first of all, you're binding the event to the input twice. Once as
$('#query').change
and for the second time via the HTML
onChange
attribute. Remove the attribute since you already set it
via JavaScript.
Your code should look something like this:
<script>
$(function() {
$('#query').change(function() {
$.ajax({
type: "POST",
url: "home.php",
data: {query: $(this).val() }
});
});
});
</script>
<input name='searchBar' type='text' size='100' id='query'></input>
<?php
$x = $_POST['query'];
echo $x;
?>
Notice I've also used the DOM ready event
$(function() { .... });
to execute all the JavaScript to ensure
that the input element is loaded when the script is executed.
If I understood correctly, you have all this in a single PHP file. Therefore,
the PHP block is executed every time you load the page and that's why you got
the error notice as there is nothing in the POST yet. Place the PHP block in a
different PHP file. You also don't print any results in JavaScript, so you won't
see the PHP variable even you print it using echo()
. I'd add
something like:
<script>
$(function() {
$('#query').change(function() {
$.ajax({
type: "POST",
url: "home.php",
data: {query: $(this).val() },
dataType: "text"
})
.success(function(data) {
console.log(data);
});
});
});
</script>
Which will print everything that the PHP script printed into the browser's console which is accessible via the F12 key or the Ctrl + Shift + J combination.
So what you need is to process your request in a separated PHP file which would then print some output that would be then returned to that AJAX callback where you can process it and print it into the page where you want it.
Thanks! Much appreciated.
3 messages from 3 displayed.