I'm facing an unexpected issue while sending one simple form field data to another PHP file through Ajax. I have done it a lot of time but this time I don't know what I'm doing wrong.
Please help!
Here is my form:
<form action="textify.php" method="post">
<input type="text" name="textify">
<button>textify it!</button>
<pre style="display: none;"></pre>
</form>
And here this is my jQuery with AJAX:
$(document).ready(function(){
$('form').submit(function(){
var textify = $('input[name=textify]').val();
$.post('textify.php', {data: textify}, function(txt){
$('pre').show();
$('pre').text(txt);
});
return false;
});
});
And here is my file where I'm sending data to (textify.php)
class textify
{
function __construct() {
$textify = $_POST['data'];
echo $textify;
}
}
new textify;
And this is the unexpected issue:
<br /><b>Notice</b>: Undefined index: data in <b>C:\Users\omer\Desktop\textify\textify.php</b> on line <b>19</b><br />
The error is pretty simple the key name is invalid. You use keyname data
but you get text
which does not exists.
change
$.post('textify.php', {data: textify}, function(txt){
to
$.post('textify.php', {text: textify}, function(txt){
or better use serialize() to avoid such mistakes.
Edit:
change code to:
$(document).ready(function(){
$('form').submit(function(ev){
ev.preventDefault();
$.post('textify.php', $(this).serialize(), function(txt){
$('pre').show();
$('pre').text(txt);
});
});
});
in PHP
echo $_POST['textify'];